There are mainly three namespace in python: built-in (outermost), global, and local. A namespace gets created automatically when we execute a module or package.
Python implements the global and local namespaces as Python dictionaries (not the built-in namespace) and provides built-in functions called globals() and locals() to help us access these namespace dictionaries.
We can use the globals() function to access the objects in the global namespace.
Example:
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
As you can see, the interpreter already has several entries in globals(). Now, when you define a variable in the global scope:
>>> s = 'Mango'
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 's': 'Mango'}
A new object (‘Mango’) appears in the global namespace dictionary. The dictionary key is the object’s name, s, and the dictionary value is the object’s value, ‘Mango’.
Similarly, the locals() function helps us access objects in the local namespace.
>>> def l(p, q):
s = 'Apple'
print(locals())
>>> f(15, 0.7)
{'s': 'Apple', 'q': 0.7, 'p': 15}
When called within l() function, locals() returns a dictionary that represents the function’s local namespace. Apart from the local variables, locals() also includes the function parameters p and q since they are local to l().
Related Questions
- How do you write first code in Python?
- How do you write an infinite loop in Python?
- How do you write a matrix in python?
- What are Python namespaces why are they used?
- How do I write a Python script?
- Is while loop infinite Python?
- How do you write a 3×3 matrix in python?
- How do you create a namespace in Python?
- How do you make an infinite while loop?
- How do you create a matrix list in Python?
- What is datatype in Python?
- Which software is best for Python programming?
- Why is my FOR LOOP infinite Python?
- How many datatypes are there in Python?
Related Topics
- Python Programming
- 9 Best Python IDEs and Code Editors
- Python Input-Output (I/O) Using input() and print() Function
- List of Keywords in Python Programming
- Python Keywords and Identifiers (Variable names)
- Python List Comprehension (With Examples)
- Python Looping Techniques
- Python Main Function
- Python Matrix and Introduction to NumPy
- Python Namespace and Scope of a Variable
- Python PIP
- Python Statement, Indentation, and Comments
- Python Type Conversion and Type Casting (With Examples)
- Python Variables, Constants, and Literals
- Python Data Types
Leave a Reply