Forums

Store a value between runs

Hi, How can I store the value of a variable between runs of a function/script?

I am rather new to Python, but am experienced in c++. In c++ one can use "static" and I basically want the same behaviour. One solution is to save the value in a txt-file and overwriting it every run, but I believe a better solution exists.

Thanks in advance!:)

In Python, the equivalent of a C++ static variable is to use a module-level variable and the global keyword in the function.

Be aware, however, that this does not translate between processes (it does not in C++, either). So if you use it in a web app with multiple workers, each worker will have its own copy of the variable.

Another note: Neither the C++ static or the Python global will transfer between runs of a script, they are both entirely stored in memory and, when the script/program ends, they are destroyed.

Thank you for your answer, I see that my comparison with static will not apply to this after all. One example of where I need to store a variable is that I have a task running continuously checking if an entry in a db has been made. If no entry has been made after a certain time of the day, a sms is to be sent. The problem is that I only want to send a single sms, and would like to monitor if it has been sent, by for instance storing the timecode of the last sent sms.

Do you have a solution for this?

If you're already using a database, just store the time that the last SMS was sent in the database.

Yeah, I guess that will be the best solution. Thanks:)