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
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
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
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
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
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
The variable ‘a’ is called as non-local variable inside nest1() function
We will discuss how all these scopes work together and the issues we may get into in the next post