What are Namespaces in Python?🤔

"Namespaces are one honking great idea—let’s do more of those! :rocket:
-The Zen of Python

In Python, everything is considered as an object, be it a variable, a function or anything.

And every object has a “name” to it which are references to other objects.

We can keep creating hundreds of such objects and all these names need to properly managed.

Enter Namespaces.:bulb:

Namespaces are essentially a collection of all the names of objects and the elements or objects they refer to.

When you say a = 2, it is stored in the namespace in the form of a dictionary as {‘a’:2}, where “a” is a name of 2.

Now there can be multiple instances of an object named as “a”. How does Python know that when which of the “a” is called?:bulb:

The answer is, the Scope of the Namespace.

L-The objects defined within a function are in the Local Namespace of that function.

E-Any objects outside of this function act as Enclosing Namespace to the function inside it.

G-All the objects defined at the main function level, or with the “global” declaration (global a = 2) are in the Global Namespace

B-All the pre-loaded objects like the print function are in the Built In Namespace.

When an object is called, it’s searched in this particular order - LEGB.:zap:

#python #datascience