Python Namespace – Python Variable Scope

To become a better programmer, one of the most important things to understand is the Python namespaces and variable scopes. The reason is that when you create multi-class and multi-file programs, knowing the scope of the variables that you define can mean the difference between the right outputs and getting strange outputs here.

So without any further delay, let’s get right into it.

What is a Python namespace?

A namespace in Python is a collection of underlying keywords and objects that Python has within memory. It’s a very common concept in Object-Oriented Programming.

In Python, a namespace is a key-value pair implemented as a Dictionary. There are 4 namespaces in Python:

  1. Built-In
  2. Global
  3. Enclosing
  4. Local

Getting a deeper understanding of namespaces…

If you split the word namespace, there are two elements – a name and space.

Each name within the space is essentially an object. When you define more variables, classes, or functions within a Python program, you expand the namespace. They continue to get added to the local or global Python namespaces depending on the scope of the object defined.

Have a look at the example implementation of two namespaces below:

nameA and nameB. Each object within the namespace is defined with a var_name which is the name for the object.

So nameA and nameB are namespaces, and the var_name1, var_name2, etc are names within the namespace.

nameA={ ‘var_name1’=object1, ‘var_name2’=object2, …}
nameB={ ‘var_name1’=object3, ‘var_name2’=object5, ‘var_name3’=object6, …}

What is a variable scope in Python?

As you may notice that both namespaces defined above, have similar names but because they exist in different namespaces, the variables do not collide with each other.

This difference is what scopes are. So how does Python define what’s the scope of a variable or object in a program? Let’s take a look at the below example:

name = 'Andy'  # define name

def printBob():
   name = 'Bob'  # define name in function
   print('printing from the def: ', name)  # print from function

# the main function
print('printing from the main: ', name)  # print from the main
printBob()  # call the function to print

The produced output will be

printing from the main:  Andy
printing from the def:  Bob

As you can see, both the variables, while having the same name, are defined within different scopes:

  1. First is in the global scope where the entire program can access it (name = Andy)
  2. Second one is defined within the printBob() function where only that function can access the value of the variable

This is also the reason why when you print out the variable without calling the function, the default value will be the one defined in the Global scope.

def printBob():
   var = 'print it'
   print('printing from the function: ', var) # this statement will run without errors

# call the function to  print the variable value
# try to access the object from outside of its scope
print('printing from the main: ', var)  # this will produce error

So, you will see the output like below.

Python Namespace – Python Variable Scope

As you see, the second print statement produces an error. The reason is that the variable named var is defined within the scope of the printBob() function in the above example.

Since there’s no globally accessible variable available, the second print statement produces an error.

Example of Python nested function scopes

The scope of variables is similar to Python’s namespaces where name within the namespace lives within the scope of the namespace. Calling it from outside will require access to the scope.

var = 0
name = 'absicsa'

def function_outer():
   # global var    ; no need to declare to call the value
   name = 'nabisco'

   def function_inner():
       global var  # need to declare global to modify the value
       name = 'outlet'
       var = 23
       print('name :',name, ', var :', var)

   print('name :', name, ', var :', var)

print('name :', name, ', var :', var)

The output of the code will be:

Python Namespace – Python Variable Scope

Here you can see that we’ve defined nested functions. Each function has a scope of its own. The inner functions cannot access variables from outer scopes. But the functions from the outside can access inner functions.

So function_outer() function can be called from the main function’s scope while the function_inner() function can be called from the function_outer() function’s scope.

In comparison, if you define variables outside of any function, they are global variables and can be accessed by the entire program. If you wish to access variables from outer scopes, you can use the nonlocal keyword defined in Python 3.x.

Lifetime of the Namespace

The lifetime of the namespace differs. This is because the variables themselves are allocated to memory at different times during the execution of the program. When the scope ends, the objects that are created in that scope usually deleted.

So, that’s all about the Python Namespaces and variable scopes. I have you’ve gotten a much deeper understanding of the Python scopes and namespaces in this article. If you have any questions, feel free to comment below!

References: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *