Understand namespace and scope for classes in Python (2023)

"Namespaces are a great idea - let's do more of them!"
--The Zen of Python

Objects are building blocks of Python and a namespace is a map to access those blocks. Python has several code block types, each with its own scope or namespace. This article describes scopes and namespaces for classes. Key concepts related to object-oriented programming (OOP) and namespaces in Python are introduced first. Then, using these concepts, namespaces and scopes are described in terms of classes and objects in Python.

Python is a high-level programming language that supports multiple programming paradigms, including functional programming and object-oriented programming. Everything in Python is an object of a specific class, which makes it possible to support higher-order functions. The latter gives Python functional programming capabilities, but behind the scenes, even functions are first class objects in Python. For example, Python creates a function object func using the def statement and we can assign attributes to it.

def func():
happen
print(type(function))
func.at = 20
print(func.at)

Exit

<class 'Function'>
20

Objects are instances of classes, for example an Integer object is an instance of the Numbers class. Classes are "blueprints" for creating objects and provide a way to package data and functionality. Creating a new class creates a new object type, which allows new instances of that type to be created. Attributes can be attached to each class instance to maintain its state. Class instances can also have methods (defined by their class) for changing an object's state. The following code defines a class for a family of circles. This class has three attributes, namely r, Perimeter and Area. With the circle class, we can create a circle of radius r and evaluate its perimeter and area. To understand the use of the word self, the local variable r within the Perimeter method, and the Perimeter method within the Area method, we need to understand how the concept of namespace and scope works in Python.

Understand namespace and scope for classes in Python (1)

Before defining a namespace, let's first see what a name is in Python. As we've already seen, everything in Python is an object. A name or identifier is simply a name given to the object. Name is a way to access the underlying object. For example, object 10 is referenced with the name "t". Both t and 10 have the same memory address.

(Video) Python Tutorials - Namespace and Variable Scope

t = 10
press
print(id(t))
print (id(10))
t = t+1
print(id(t))
print(id(11))

Exit

10
140707570557616
140707570557616
140707570557648
140707570557648

One important thing to note here is that assignments don't copy the data - they just bind the names to objects. So in the example above, t was first bound to 10 and is now bound to 11 because they both have the same memory address.

Now, a namespace is a mapping of names to objects implemented as Python dictionaries. The three main examples of namespaces are built-in, global, and local namespaces. The global and local names for a module can be accessed through the built-in functions globals() (returns a dictionary) and locals(), respectively.

war = 7
globals()['var']
7

When the Python interpreter is started, a built-in namespace for functions like abs(), id(), etc. is created. The global namespace is created when a module containing variables, functions, classes, etc. is run by the interpreter. A local namespace is created for the local names within a function or class. Namespaces are completely independent of each other, two different modules can define the same variable name "var" without confusion. References to names in modules are attribute references. Example: modname.funname — modanme is a module object and funcname is an attribute of it. Consider the case for the func() function below, func is mapped to module __main__ which is the currently used script.

def func():
happen
Funk

Exit

<Function __main__.func()>

Different namespaces have different lifetimes - the built-in namespaces are created when the Python interpreter starts and are never deleted. The global namespaces are created when the interpreter reads module definitions and persist until the interpreter shuts down. As mentioned, the top-level statements in a module have a global namespace (func in the example above) and are considered part of the __main__ module. Likewise, the built-in names live in a built-in module. The local namespaces are created when functions are called and destroyed when the function returns or throws an error.

A scope is the body of a program from which a namespace can be accessed directly without a prefix. The innermost range containing local names is searched first. It then searches for the region of the enclosing function that is closest to the innermost region. This scope contains a non-local namespace, but also a non-global namespace. Next to the last scope, the namespace in the current module (__main__) is searched - this is the scope of the global namespace. Finally, the outermost scope is searched with built-in names. The following example explains various areas in Python.

(Video) Python - Namespace and Scope

def python_scope(): #You must have a non-local scope
def local_scope(): #has local scope
var = "local Variable"
def nonlocal_scope():
nonlocal var
var = "non-local variable"
def global_scope():
there is a global one
var = "global Variable"
var = "Testvariable"
local_scope()
print("After local allocation:", var)
nonlocal_scope()
print("After non-local assignment:", var)
global_scope()
print("After global assignment:", var)
python_scope()
print("In global scope:", var) #has global scope

Exit

After local assignment: test variable
After non-local assignment: non-local variable
After global assignment: non-local variable
In global scope: global variable

In the example above, when the python_scope function is called, the definitions of the local_scope, nonlocal_scope, and global_scope functions are read. Then var is assigned the value "test variable". Next, running local_scope creates a local namespace for the function. The "local variable" value is only bound to this namespace. Because of this, the value of var remains "test variable" after the local_scope function is executed. If the variable is declared nonlocal inside the nonlocal_scope function, the name "var" is bound to the namespace of the python_scope function, and therefore the value of "var" is "nonlocal variable" after the nonlocal_scope function is executed. Finally, when var is declared global, it is bound to the global (module) namespace, but we're still within the scope of the python_scope function's namespace. Because of this, the value of the variable "var" is still "non-local variable". Once we move the scope of the python_scope function to the global scope, the value of "var" becomes "global variable".

In summary, when a name is declared global, all references and assignments to it go into the scope containing the names of the __main__ module. When a name is declared nonlocal, all references and assignments to it go into the namespace immediately outside the namespace in which a variable is declared. When no global or non-local statement is in effect, all references and assignments to a name go to the innermost scope.

When a class is defined, a local namespace is created, similar to when a function is defined. As already mentioned, a function (called a method) can be defined inside the class. The function has its own namespace within the class. The instance objects of the class have their own namespace, independent of the class's namespace. A class can inherit parent classes and its namespace is associated with parent classes. Let's understand the namespace for classes using the example class for a family of circles.

In the example below, if we use the dir() function to check the names in the scope (__main__) of the module, we can see that the name Circle is bound in that scope. We can verify this by printing Circle(), which returns the Circle object as an attribute of the __main__ module and a location.

class group:
rad = "A circle of radius r"
print(dir())
print(circle())

Exit

['Kreis', 'In', 'Out', '_', '_2', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', ' __Paket__', '__spec__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9' , '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'quit']
<__main__.circle object at 0x000001FFD57EE548>

Let's check the names in the scope of the Circle class using the __dict__ function.

(Video) Namespaces in Python: Built-in, Global, Enclosing, and Local

print(circle.__dict__)
print(circle.rad)
{'__module__': '__main__', 'rad': 'A circle of radius r', '__dict__': <attribute '__dict__' of 'Circle' objects>, '__weakref__': <attribute '__weakref__' of 'Circle 'objects>, '__doc__':none}
A circle of radius r

We can see here that the variable "rad" is in scope of the Circle class and is bound to the Circle object. Also, each instance of the class has different namespaces. The following code creates two instances of the Circle class, C1 and C2, and assigns them to an attribute section. When the dictionary is printed containing names in the range of C1 and C2, we can see that both have different ranges.

C1 = circle()
C2 = circle()
C1.scope = 'this is in the scope of C1'
C2.scope = 'this is in the scope of C2'
print(C1.__dict__)
print(C2.__dict__)

Exit

{'Scope': 'this is within the scope of C1'}
{'Scope': 'this is within the scope of C2'}

Finally, let's understand the scope and namespace for methods within the class. Each method within the class has its own namespace. In the code below, Perimeter() is a function within the class. When executed, this function throws a naming error. This is because Perimeter() is assigned to Circle's scope while we are trying to access it in global scope (of the module).

class group:
rad = "A circle of radius r"
def scope(s):
print(f'value of perimeter is {2*3.14*r}')
Scope(5)

Exit

naming error: Name 'Perimeter' is not defined

When we associate class_func with Circle class namespace, there is no error as shown below.

Circle.Perimeter(1)Value of the circumference is 6.28

Okay, but the purpose of a function within a class is to update or return the properties of class objects. Let's call this function on an object (instance) of the Circle class.

Circle().Perimeter(1)TypeError: Perimeter() takes 1 positional argument, but 2 were specified

The above code throws a type error because when we assign a function to an object, the object is automatically passed as a parameter to the function. Therefore, in the definition of the function, we need to pass an object (instance) of the class. That's whereselfis used. "Self" is just a name given to an object of the class, and that name is tied to the object's namespace.

(Video) Python tutorial: Variable Scopes & Namespaces - global/local/nonlocal | Explained with animations

class group:
rad = "A circle of radius r"
def perimeter(self, r):
print(f'value of perimeter is {2*3.14*r}')
Circle().Perimeter(1)

Exit

Value of the circumference is 6.28

Generally, when we create objects using classes, they are created with some initial states. Here the built-in method __init__ can be used to define an initial state. For example, we can define a circle with a given radius "r". Also, you don't have to explicitly call the __init__ method. It is called automatically when an instance of the class is created. See the example below.

class group:
"""A class for the family of circles"""
def __init__(self, radius):
self.r = Radius

Kreis(1)

Exit

<__main__.Circle at 0x1ffd5899488>

Also note that self.r is used here to concatenate the name "r" to the object's namespace. So that it can be accessed in the scope of the object's namespace with (Circle().r). And using the same terminology, a method in a class can access another method in the class, as shown in the example below.

class group:
"""A class for the family of circles"""
def __init__(self, radius):
self.r = Radius
def scope (self):
return 2*self.r*3.14
def area (self):
return self.Perimeter()*self.r/2
C = circle(1)
print(C.Perimeter())
print(C.Area())

Exit

6.28
3.14

In the example above, the Perimeter() method is used in the Area() method. Again, "self" is used with the Perimeter() method to associate it with the namespace of the "self" object.

(Video) Python Namespace and Scope

In summary, the following figure illustrates the concept of namespace and scope for the Circle class. First, definitions of the Circle class that are in the global namespace are read and a namespace for the Circle class is created. Namespaces for the object (C) and methods (Perimeter, Area) are also created. When we execute the Area method using C.Area(), we first look for the names in the area of ​​the method (Area), then in the area of ​​the C object, and finally in the area of ​​the Circle class. For example, the word perimeter is searched first in the scope of the area method, then in the scope of the object (C/self). The name Perimeter is tied into the object's namespace with self.Perimeter and can therefore be used within the Area method. If we use "Perimeter" without the word "self", it is not scoped to the object and is not accessible to the Area method.

Understand namespace and scope for classes in Python (2)

FAQs

What is namespace of a class in Python? ›

Namespaces in Python. A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves.

What is the difference between namespaces and scope? ›

Namespaces are collections of different objects that are associated with unique names whose lifespan depends on the scope of a variable. The scope is a region from where we can access a particular object. There are three levels of scopes: built-in (outermost), global, and local.

What is the scope of a variable in a class in Python? ›

A variable is only available from inside the region it is created. This is called scope.

What are the three types of namespaces in Python? ›

We can define namespace as a collection of names associated with the address in the main memory. There are three types of namespaces in python - Built-in Namespace, Global Namespace, and Local Namespace.

What is the difference between namespace and class? ›

The namespace and classes are two different concepts. Classes are datatypes. Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one.

Can a class have namespace? ›

This is because a class acts like a namespace; the names declared within the class definition have scope that is limited to that definition. In order to use those names outside of the class definition, they must be qualified in the same way that names in a namespace must be qualified.

How do you explain a namespace? ›

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is the biggest advantage of using namespaces? ›

Advantages of namespace

By using namespace - the same variable names may be reused in a different program. The use of libraries - Namespaces and named spaces help a lot to use both libraries together, and defining the name using the scope resolution operator, helps determine the variable we try to access.

What is the primary purpose of a namespace? ›

In computing, a namespace is a set of signs (names) that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.

What is the scope of a class variable? ›

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.

What is scope in Python explain with an example? ›

For example, if you assign a value to a name inside a function, then that name will have a local Python scope. In contrast, if you assign a value to a name outside of all functions—say, at the top level of a module—then that name will have a global Python scope.

What are two basic scopes of variable in Python? ›

In Python, there are two types of scope:
  • Local scope/local variables.
  • Global scope/global variables.

Why should I use namespace in Python? ›

Python Namespaces are collections of different objects that are associated with unique names whose lifespan depends on the scope of a variable. The scope is a region from where we can access a particular object.

Why is namespace important in Python? ›

The namespace helps the Python interpreter to understand what exact method or variable is trying to point out in the code. So its name gives more information - Name (which means name, a unique identifier) + Space (related to scope). In Python, there are four types of namespaces which are given below.

What is the difference between module and namespace in Python? ›

In Python-speak, modules are a namespace—a place where names are created. And names that live in a module are called its attributes. Technically, modules correspond to files, and Python creates a module object to contain all the names defined in the file; but in simple terms, modules are just namespaces.

Can a class exist without a namespace? ›

Yes we can create class without namespace.

Can one namespace have multiple classes? ›

You can have a class in 1 to many files (if you use the "partial" keyword). You can have many classes in a namespace.

Can a class have multiple namespaces? ›

In c#, we can define and access multiple namespaces in our application with using keyword. To access the custom namespace classes, we need to import the custom namespace with using keyword and need to create an instance for that classes in our application.

What is the difference between class library and namespace? ›

Namespaces provide a notional separation for classes, class libraries provide a physical separation (in windows think a standalone dll). Class libraries are useful for when you want to wrap up functionality that can be shared with other projects.

What is namespace class method? ›

A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.

How do you access a class in a namespace? ›

The simplest way to access a class inside a namespace is simply to prefix the classname with its namespace(s): include 'namespaced-class.

What is the five types of namespace? ›

The Types of a . NET Namespace
  • Classes. In VB.NET, classes are reference types; that is, when you create an instance of a class in code, you work with a pointer (or reference) to the object rather than with the object itself. ...
  • Structures. ...
  • Enumerations. ...
  • Interfaces. ...
  • Delegates.

What is a namespace and which problems does it solve? ›

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

What is namespace in REST API? ›

Classes are grouped as namespaces. In other words, Namespaces contain related classes which contains methods, So, in REST API Explorer, to access a particular API method, the relevant class has to be chosen. This is the simple definition of namespace.

Why should you not use using namespace? ›

Bad Practice: using namespace std. Since using namespace std brings all the identifiers from the std namespace into the global namespace, this can create naming conflicts with other namespaces. For instance, there may be other entities with the name cout other than the one in the std namespace.

What are the two types of namespaces? ›

When creating a namespace, you must choose one of two namespace types: a stand-alone namespace or a domain-based namespace.

What is the best practice in namespaces? ›

Best Practices for Kubernetes Namespaces
  • About the List.
  • Use Semantic, Scalable Names.
  • Don't Put Everything in the Default Namespace.
  • Leverage Role-Based Access Control.
  • Know When to Use Multiple Namespaces.
  • Know What Belongs in a Namespace.
  • Limit Resource Usage for Specific Namespaces.
  • Know When It's Time to Add More Clusters.
Jun 13, 2022

Do you need namespace? ›

Namespaces are used to provide a "named space" in which your application resides. They're used especially to provide the C# compiler a context for all the named information in your program, such as variable names. Without namespaces, for example, you wouldn't be able to make a class named Console, as .

What is namespace and how is it used for accessing the data? ›

A namespace is a container for the identifier. A namespace defines a scope where identifiers like variables, functions, classes, etc., are declared. The main purpose of using a namespace is to prevent ambiguity when two identifiers have the same name.

What is the difference between cluster and namespace? ›

Namespaces are a way to organize clusters into virtual sub-clusters — they can be helpful when different teams or projects share a Kubernetes cluster. Any number of namespaces are supported within a cluster, each logically separated from others but with the ability to communicate with each other.

What are the three types of variable scope? ›

PHP has three different variable scopes:
  • local.
  • global.
  • static.

How do you determine the scope of a variable based on storage class? ›

The scope of variable declared using static storage class is the function or block in which variable is declared. The visibility of variable is the function or block in which variable is declared. The static variable remains in memory until the program is terminated.

What is a class defined as scope of an object? ›

Class scope defines the accessibility or visibility of class variables or functions. The term scope is defined as a place where in variable name, function name and typedef are used inside a program.

What are the four scopes in Python? ›

You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.

What are the scopes of learning Python? ›

Web developer with Python skills can also earn in the range of Rs 8,00,000 per annum. Other related job roles include lead software engineer (up to Rs 2,000,000 per annum), data scientist (Rs 7,00,000 per annum), machine learning engineer (Rs 6,70,000 per annum), data analyst (4,17,000 per annum), and more.

How do you explain scope? ›

The scope of a project is a detailed outline which encompasses all the work needed to deliver a product or service. This includes the project's goals, deliverables, tasks, project members, deadlines, and milestones.

What is a namespace of a class? ›

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is namespace example? ›

In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace.

What is __ init __ in Python? ›

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

Videos

1. Python - Namespaces and Function Variable Scope with Code Examples - Python for Beginners APPFICIAL
(Appficial)
2. Python Scope | Namespaces | Name Resolution and First-Class Objects
(Very Academy)
3. Python Tutorial: Variable Scope - Understanding the LEGB rule and global/nonlocal statements
(Corey Schafer)
4. Python Namespaces
(John Philip Jones)
5. Python Namespace and Local Scope
(John Philip Jones)
6. Namespace or Scope - Python Advanced Tutorial Series - 26
(Daily Tuition)
Top Articles
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated: 12/04/2022

Views: 6448

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.