NameSpaces in Python (1/2)

Kranti
3 min readJun 24, 2021

Variable:

Unlike in some of the programming languages (C/C++/Java), there is no need to declare variables before assignment in Python. Accessible limits for these variables define the scope and is the topic for this blog post.

Python offers 4 different scopes: Local, Enclosing, Global, Built-in. Lets dive into what each of those scopes refers to

The hierarchy of namespaces: local > enclosed > global > built-in

Built-in Scope: There are various built-in functions provided by Python which are accessible across programs.

True, False, print(), dict(), None, class, return etc. fall into built-in scope

True, print, return which have built-in scope and available throughout

Global Scope: Also referred as module scope. Unlike other programming languages, global scope doesnt mean Built-in scope and make a note of the difference between these two.

global scope doesnt mean Built-in scope

The current working Jupyter notebook, Python Console , A Python file all fall into global scope

‘a’ is a global variable accessed inside the function f1()

By importing the necessary modules, the module scope can be extended to other modules as well. Thats how variables/functions defined in one module can be accessed in other module and this is referred as Global scope

Importing functions from one python file to other [Module Scope]

Tried accessing the function f1() defined in another file. At first it throws ‘undefined’ error. After importing the function from the respective file, able to call the function and fetch results. This is how module scope can be extended

Local Scope: Before discussing Enclosing space, lets first discuss Local scope. Like other programming langauges, local scope refers to the accessibility inside a function

‘b’ is a local variable and can be accessed inside the function f2()

In the above code snippet, ‘b’ is assigned to a value inside the function f2() and its scope is limited to that function. Accessing it outside the function results in error

Local variable ‘b’ not accessible outside the function f2()

Enclosing Scope: Enclosing scope is a super-set of local scope and comes into action for nested functions. Please check the example below for a nested function

‘a’ has enclosed scope inside the function nest1()

The variable ‘a’ is called as non-local variable inside nest1() function

Accessing ‘local’ and ‘enclosed’ variables inside the nested function

We will discuss how all these scopes work together and the issues we may get into in the next post

--

--