Python Forum

Full Version: Non Volatile Local Variables?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

Does anyone know if Python supports non-volatile local variables Think ?

I was wondering if there was a way to keep the variable alive. I know that I can simply declare it as global, but then every function could read it. I was wondering if there was something I have over looked. I tried making a global variable reference the variable but that didn't work.

What do you think Think ?


def my_func():

    global g_arr_my_func
    
    try:
        a += 1
    except NameError:
        print("[my_func]: Exception (Name Error).")
        a = 0
    # end try

    print("[my_func]: a =:", a)

    g_arr_my_func["a"] = a

g_arr_my_func = {}
g_arr_my_func["a"] = 0

my_func()
my_func()
Output:
[my_func]: Exception (Name Error). [my_func]: a =: 0 [my_func]: Exception (Name Error). [my_func]: a =: 0
Can you elaborate on what you mean by "non-volatile local variables"?
Well let's say you have a function, and you want that function to keep count of the number of times you call it. If I create a variable named "a" in the function and increased its number by one every time I would probably use a global var. But I was wondering if there was another way.

The reason behind this question is that I'm working on this game RocksInSpace. Its got loads of little routines (some written when I was very much a beginner in Python and didn't know better). Anyway I'm working on getting as close as possible to 60 frames per second and was toying with the idea of global variables, but thought wouldn't it be nice if I could tell the compiler not to destroy the variable when the function has completed.

Hope that's made it a bit clearer.

MH.
do you know about OOP/classes?
+1 to OOP being the solution to this problem. Consider checking out https://python-forum.io/Thread-Classes-Class-Basics