Python Forum
Non Volatile Local Variables?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Non Volatile Local Variables?
#1
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
Reply
#2
Can you elaborate on what you mean by "non-volatile local variables"?
Reply
#3
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.
Reply
#4
do you know about OOP/classes?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
+1 to OOP being the solution to this problem. Consider checking out https://python-forum.io/Thread-Classes-Class-Basics
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020