Amity School of Engineering &
Technology
PYTHON NAME and NAMESPACE
Amity School of Engineering &
Technology
What is Name in Python?
Name (also called identifier) is simply a name given to objects. Everything in
Python is an object. Name is a way to access the underlying object.
Amity School of Engineering &
Technology
# Note: You may get different values for the id
a=2 Output
print('id(2) =', id(2)) id(2) = 9302208
print('id(a) =', id(a)) id(a) = 9302208
Here, both refer to the same object 2, so they have the same id(). Let's make
things a little more interesting.
# Note: You may get different values for the
id Output
a=2
print('id(a) =', id(a)) id(a) = 9302208
a = a+1 id(a) = 9302240
print('id(a) =', id(a)) id(3) = 9302240
print('id(3) =', id(3)) id(b) = 9302208
b=2 id(2) = 9302208
print('id(b) =', id(b))
print('id(2) =', id(2))
Amity School of Engineering &
Technology
What is happening in the above sequence of steps? Let's use a diagram to explain
this:
Memory diagram of variables in Python
Initially, an object 2 is created and the name a is associated with it, when we do a
= a+1, a new object 3 is created and now a is associated with this object.
Note that id(a) and id(3) have the same values.
Furthermore, when b = 2 is executed, the new name b gets associated with the
previous object 2.
Amity School of Engineering &
Technology
This is efficient as Python does not have to create a new duplicate object. This
dynamic nature of name binding makes Python powerful; a name could refer to
any type of object.
>>> a = 5
>>> a = 'Hello World!'
>>> a = [1,2,3]
All these are valid and a will refer to three different types of objects in different
instances.
Amity School of Engineering &
Technology
What is a Namespace in Python?
There are three types of Python namespaces- global, local, and built-in. It’s
the same with a variable scope in python. Also, the ‘global’ keyword lets us
refer to a name in a global scope. Likewise, the ‘nonlocal’ keyword lets us
refer to a name in a nonlocal scope.
Amity School of Engineering &
Technology