Namespace

It is important to understand how varaible names are located when a program is executed. Python will search the local space that the program is running for the varaibel being utilised.If it cannot find the varailbe it will then search down the layers of classes and fucntions to find the value that is required.

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def function1(x):
    x = 4
    print (x)
    return x

def function2(x):
    x = 3
    function1(x)
    print (x)
    return x

def function3(x):
    x = 2
    function2(x)
    print (x)
    return x

x = 1

function3(x)
Returns:
1
2
3
4
3
2

Example 2

If we update the program above but we request a varaible in function 1 that is in the global namespace.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def function1(x):
    x = 4
    print (x)
    print (y)
    return x

def function2(x):
    x = 3
    function1(x)
    print (x)
    return x

def function3(x):
    x = 2
    
    function2(x)
    print (x)
    return x

x = 1
y = 6
function3(x)
Returns:
1
2
3
4
4
6
3
2



Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines