Global and local scope of Python variables

In [1]:
# - compatibility with Python 3
from __future__ import print_function  # print('me') instead of print 'me'
from __future__ import division  # 1/2 == 0.5, not 0

Variable scope refers to the places that you can see or access a variable.

If you define a variable at the top level of your script or module or notebook, this is a global variable:

In [2]:
my_var = 3

The variable is global because any Python function or class defined in this module or notebook, is able to access this variable. For example:

In [3]:
def my_first_func():
    # my_func can 'see' the global variable
    print('I see "my_var" = ', my_var, ' from "my_first_func"')
In [4]:
my_first_func()
I see "my_var" =  3  from "my_first_func"

Variables defined inside a function or class, are not global. Only the function or class can see the variable:

In [5]:
def my_second_func():
    a = 10
    print('I see "a" = ', a, 'from "my_second_func"')
In [6]:
my_second_func()
I see "a" =  10 from "my_second_func"

But here, down in the top or global level of the notebook, we can't see that variable:

In [7]:
a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-60b725f10c9c> in <module>()
----> 1 a

NameError: name 'a' is not defined

The variable a is therefore said to be local to the function. Put another way, the variable a has local scope. Conversely the variable my_var has global scope.

The rules on variable scope cover many more cases than these very simple examples.

See http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/scope_resolution_legb_rule.ipynb for a nice walkthrough.