0

Just a random question - is there any way to run a Python function step by step? I want to be able to simulate things like dovetailing - where for each input I can run one step of the function at the time, so that it outputs all the return statements, without being stuck in an infinite loop. I would want it to be something like this:

f = (collatz conjecture function)
processes = []
i = 0
while True:
    processes.append(f(i)) # Add the function on that input but dont run it
    for p in processes:
        (run p for 1 step. If it halts, print its input)
    i+=1

Is there any way to do this, or am I just crazy? Kind of like pdb, but I dont want it to be debugging.

martineau
  • 119,623
  • 25
  • 170
  • 301
Arya
  • 1,382
  • 2
  • 15
  • 36
  • 2
    Why don't you want to use a debugger, when what you want is exactly what debuggers do? – DYZ May 03 '17 at 18:48
  • Your pseudocode appears to generate an infinite number of processes—which is probably not what you want. What is it then? – martineau May 03 '17 at 18:52
  • The crazy way to do this would be, given that the functions are super simple, have them in a list of strings and call `eval` for each. – Josep Valls May 03 '17 at 19:03
  • The [`sys.settrace()`](https://docs.python.org/3/library/sys.html#sys.settrace) function allows the implementation of debuggers, so you could probably use it to do something like this. – martineau May 03 '17 at 19:03
  • @martineau that's exactly what I want – Arya May 03 '17 at 21:07
  • @DYZ Debuggers have all of this interface around them, I just want to be able to run a function line by line. – Arya May 03 '17 at 21:14
  • I might be able to come up with something, but still need clarification on the number-of-processes issue I brought up earlier. – martineau May 03 '17 at 21:15
  • @JosepValls It would be hard to give them all their own state as well though. – Arya May 03 '17 at 21:15
  • @martineau What's your idea, if we knew we were going to run the program for only up to i=10000 or something? – Arya May 03 '17 at 21:16
  • `sys.settrace()` can be made work with threads, so each process could be made into a separate thread in a multi-threaded program. 10,000 threads shouldn't be a problem (but an infinite number would be). – martineau May 03 '17 at 21:20
  • @Arya If that is the only problem, you can actually provide `eval` with dictionaries for globals and locals. – Josep Valls May 03 '17 at 21:48
  • It's not the only problem - the other one I just thought of is what if there's a loop - it's hard to keep track of all the states, and it would be nice if I didn't have to make a python interpreter for this to work. – Arya May 04 '17 at 01:50

0 Answers0