top of page
Writer's pictureRajesh Singh

Scope of Objects and names in Python:

Updated: May 18, 2020



Scope refers to the coding region from which exacting Python object is accessible. So one cannot access any exacting object from everywhere from the code, the accessing has to be permitted by the scope of the object. The scope of an object is the set of functions/methods in which the object is valid. Names and objects are very dissimilar things i.e. a name may have a very different scope than the object.

Example:

def is_even(number):

return number % 2 == 0

a = 83

print (is_even(a))

In this program the name ‘number’ has a scope that is limited only to the function ‘is_even’; you can’t access that name outside of is_even.

Though when the function ‘is_even’ it is called on line 5 the name ‘number’ will refer to the integer object 83 - which is also accessible outside of the function - see that the name ‘a’ also refers to exactly the same object and we could set any number of names to refer to the integer object 83.



What is namespace?

A namespace is a system to have a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary.

Types of namespaces:

When Python interpreter runs solely without and user-defined modules, methods, classes etc. Some functions like print (), id () are always present, these are built in namespaces. When a user creates a module, a global namespace gets created, later creation of local functions creates the local namespace. The built-in namespace encompasses global namespace and global namespace encompasses local namespace.



Lifetime of a namespace:

A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access inner namespace’s objects from an outer namespace.

# Python program processing

# global variable

count = 5

def some_method():

global count

count = count + 1

print(count)

some_method()

Output: 6



887 views0 comments

Recent Posts

See All

Comments


bottom of page