Questions

Which is not Valid Namespace in Python?

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

Related Topics

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.