Journey to Master Python (WIP)
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Namespace
In python there are three different namespace
- global
- local
- builtin
Rougly namespace in python in a dictionary containing bunch of variables. So every object has __dict__
associated with it.
That contains all the attributes that belong to that object. You can modify them for fun and profit.
Tricky bit is the scope of the namespace and where are those visible. This is defined by the scope. Variable is first searched in the inner most namespace, and then to enclosing namespace (for example functions inside functions) and moves to global and finally builtin.
Global Namespace
To see what to see in modules' namespace, you need to access its __dict__
which is done by calling globals()
.
If you are running a standalone python file then the module is called __main__
module_dict = globals()
Builtin Namespace
Python automatically imports all the builtin functions into every modules' namespace without polluting the modules' __dict__
.
So when you see modules' dictionary you wont see them directly. You can still access them in variety of ways.
In below example we are modifying builtin function.
vars()
returns the local namespace. If it is called inside function it returns functions __dict__
It also takes an argument which could be any object and returns its __dict__
object.
Local Namespace
This could be module or function or class. To get access to local namespace dict you can call locals()
or if you want to access any object's namespace call vars(objname)
.
Inside function if you call locals()
or vars()
you will get currently visible namespace as dictionary and should not be modified.
But inside class/module you get the object's __dict__
. You can modify for fun and profit.