
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Namespaces and Scope in Python
In Python we work with variables, functions, libraries and modules, etc. Sometimes, the variable name you choose may already exist as the name of another variable, function, or method. This can be confusing or it might lead to unexpected behavior in your program. In such scenario, we need to learn about how all these names are managed in Python. This is the concept of namespaces and scoping.
Namespaces in Python
A namespace is a mapping from names to objects, which means stores the names you define in your program (such as, variable names, function names, class names, etc.) and maps them to the objects they refer to. In simpler words, it is like a dictionary where each name is a key and the object it refers to is the value.
Following are the three categories of namespace ?
-
Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs.
-
Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the Python program. The global namespace includes all local namespaces within that module.
-
Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the Python interpreter that is loaded as the programing environment. It includes all the built-in functions and exceptions that are available by default in Python, such as abs(), print(), and len(). It encompasses Global Namespace which in turn encompasses the local namespace.
Example
From the following example, you will understand the difference between local, global, and built-in namespaces in Python using locals(), globals(), and dir(__builtins__) functions.
# Define global variable x = 100 name = "Global Name" def local_fun(): # Define local variable a = 10 name = "TutorialsPoint" print("Local Namespace:", locals()) # getting the local namespace local_fun() # getting the global namespace print("Global Namespace:", globals()) # getting the built-in namespace print("Built-in Namespace:", dir(__builtins__))
When we run above program, it produces following result ?
Local Namespace: {'a': 10, 'name': 'TutorialsPoint'} Global Namespace: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f9b0bff3f80>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/cg/root/682c9745587be/main.py', '__cached__': None, 'x': 100, 'name': 'Global Name', 'local_fun': <function local_fun at 0x7f9b0bfe6160>} Built-in Namespace: ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Scope in Python
The namespace has a lifetime when it is available. This is referred to as its scope. The scope also depends on the region in the code where the variable or object is located.
Example
From the below example you can see that how the variables declared in an inner loop are available to the outer loop but not vice-versa. Also please note how the name of the outer function also becomes part of a global variable.
prog_var = 'Hello' def outer_func(): outer_var = 'x' def inner_func(): inner_var = 'y' print(dir(), ' Local Variable in Inner function') inner_func() print(dir(), 'Local variables in outer function') outer_func() print(dir(), 'Global variables ')
Running the above program gives us the following result ?
['inner_var'] Local Variable in Inner function ['inner_func', 'outer_var'] Local variables in outer function ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'outer_func', 'prog_var'] Global variables
Example
Here is the another example demonstrating the scope of the local and global variables.
# Define global variable Money = 2000 # Define local function def AddMoney(): # this is a local variable Money = 5 Money = Money + 1 print("Local Variable:",Money) AddMoney() print("Global variable after executing the local function :",Money)
While executing the above code we get the following output ?
Local Variable: 6 Global variable after executing the local function : 2000