Class/instance variable not set to zero when restarting a Pythonista program
I have definition like this:
class Task(): last_id = 0 def __init__(self, note, priority, tags=' '): Task.last_id += 1 self.id = Task.last_id
I use the variable to number tasks in my program. The 1st task will be number 1, the 2nd, number 2, etc. However, if I create 2 tasks, then stop the program and restart the program, the 1st task I create is given the number 3 instead of 1. I can't figure out how to fix this. If I kill Pythonista, I always get the correct numbers, but it is a pain to kill Pythonista between runs.
Omega0 last edited by
I think context will be necessary. I can't seem to recreate the issue with just the class in the program file.
You can see my script at github
JonB last edited by
There is an option in the pythonista settings to clear global variables each time you press run. I think it is disabled by default to allow more of an interactive debugging type environment.
A few other options exist: you could press and hold clear in the console, which will restart pythonista.
A better option for your situation would be that your main script should reinitialize any global variables it wants to use.
Or, you may want to ask why you need a global at all...another option is to instead create all of your tasks in a list, or another container like a deque, rather than create your own linked list implementation. Such containers are probably easier to expose to the ui methods for example.
omz last edited by
Well, the easiest fix would be adding this to the script where you use the
import tasklist; reload(tasklist)
The reason this happens is basically that Pythonista runs a single interpreter that exists for the lifetime of the process (i.e. until you quit the app). It's unfortunately not really possible to do this any other way on iOS because I can't launch a subprocess (Apple policy). I try to reset the global state when you run a script, but this isn't 100% reliable, and Python caches modules after the first time you import them, so they're not executed again afterwards...
Thanks! I chose the reload route.