Published on

Python using a globally defined variable in a function

Authors

It is generally bad practice to use global variables that change state. But if you are slapping something together quickly and need to do it in Python it is possible.

Normally if you define a variable in global scope and try to reassign it in a function, the variable is re-scoped and has only has that value for the scope of the function. The global value is not modified:

some_var = 1

def do_something():
    some_var = 3

print(some_var)
do_something()
print(some_var)

This will output:

1
1

The key here is you need to use the global keyword in the function to indicate that you are referring to the globally defined variable some_var:

some_var = 1

def do_something():
    global some_var
    some_var = 3

print(some_var)
do_something()
print(some_var)

Which as expected outputs:

1
3