If I create a global variable in one function, how can I use that variable in another function?

We can create a global with the following function:

def create_global_variable(): global global_variable # must declare it to be a global first # modifications are thus reflected on the module's global scope global_variable = 'Foo'

Writing a function does not actually run its code. So we call the create_global_variable function:

>>> create_global_variable()

Using globals without modification

You can just use it, so long as you don't expect to change which object it points to:

For example,

def use_global_variable(): return global_variable + '!!!'

and now we can use the global variable:

>>> use_global_variable() 'Foo!!!'

Modification of the global variable from inside a function

To point the global variable at a different object, you are required to use the global keyword again:

def change_global_variable(): global global_variable global_variable = 'Bar'

Note that after writing this function, the code actually changing it has still not run:

>>> use_global_variable() 'Foo!!!'

So after calling the function:

>>> change_global_variable()

we can see that the global variable has been changed. The global_variable name now points to 'Bar' :

>>> use_global_variable() 'Bar!!!'

Note that "global" in Python is not truly global - it's only global to the module level. So it is only available to functions written in the modules in which it is global. Functions remember the module in which they are written, so when they are exported into other modules, they still look in the module in which they were created to find global variables.

Local variables with the same name

If you create a local variable with the same name, it will overshadow a global variable:

def use_local_with_same_name_as_global(): # bad name for a local variable, though. global_variable = 'Baz' return global_variable + '!!!' >>> use_local_with_same_name_as_global() 'Baz!!!'

But using that misnamed local variable does not change the global variable:

>>> use_global_variable() 'Bar!!!'

Note that you should avoid using the local variables with the same names as globals unless you know precisely what you are doing and have a very good reason to do so. I have not yet encountered such a reason.

We get the same behavior in classes

A follow on comment asks:

what to do if I want to create a global variable inside a function inside a class and want to use that variable inside another function inside another class?

Here I demonstrate we get the same behavior in methods as we do in regular functions:

class Foo: def foo(self): global global_variable global_variable = 'Foo' class Bar: def bar(self): return global_variable + '!!!' Foo().foo()

And now:

>>> Bar().bar() 'Foo!!!'