Global Variables

I am struggling with maintaining global variables. I have calculated variables inside a definition in a module named Globals.

When I go to apply the values from the calculations to a label, the value displayed is zero. Not the value I calculated.

I’m sure this is user error, but I am stumped.

Any help greatly appreciated.

Are you importing the module inside the forms you are both setting and referencing the variable from?

Example, create a client side module called “my_globals”, then :

# Form1
import my_globals
...
my_globals.abc = "hello"

# Form2
import my_globals
...
print(my_globals.abc)

This will print “hello” from form 2, assuming you run form 1 first to set the variable.

3 Likes

Also, if you’re inside a function remember to use the global keyword to tell Python that you want to modify the variable in the global scope (see here for more about global vs. local scope).

This modifies the variable in the local scope:

foo = 1234

def do_a_thing():
    foo = 8796

do_a_thing()

print(foo)  # prints 1234

This modifies the variable in the global scope:

foo = 1234

def do_a_thing():
    global foo
    foo = 8796

do_a_thing()

print(foo)  # prints 8796
3 Likes

Also, make sure you don’t confuse server modules with modules.

2 Likes

This is exactly what I needed.

That solved my problem.

Thank you everyone for your help.

1 Like

Great! You can mark the correct answer as “solved” by clicking the :white_check_mark: at the bottom of the answer.

2 Likes