Scope in python classes

Namespaces and Scope in Python

A namespace is a system that has 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. Let’s go through an example, a directory-file system structure in computers. Needless to say, that one can have multiple directories having a file with the same name inside every directory. But one can get directed to the file, one wishes, just by specifying the absolute path to the file.
Real-time example, the role of a namespace is like a surname. One might not find a single “Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both first name and surname are same for multiple students).
On similar lines, the Python interpreter understands what exact method or variable one is trying to point to in the code, depending upon the namespace. So, the division of the word itself gives a little more information. Its Name (which means name, a unique identifier) + Space(which talks something related to scope). Here, a name might be of any Python method or variable and space depends upon the location from where is trying to access a variable or a method.

Читайте также:  Javascript local variable this

Types of namespaces :

When Python interpreter runs solely without any 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 the creation of local functions creates the local namespace. The built-in namespace encompasses the global namespace and the global namespace encompasses the local namespace.

The 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 the inner namespace’s objects from an outer namespace.

Источник

Scope in Python

Scope in Python

The scope defines the accessibility of the python object. To access the particular variable in the code, the scope must be defined as it cannot be accessed from anywhere in the program. The particular coding region where variables are visible is known as scope. Variables are not visible to the entire code; their visibility can be restricted. Scope verifies which variable can be ‘Seen’. The scope defines the set of rules which tell us how and where a variable can be searched. The variable is searched either to retrieve a value or for assigning value. The namespace is the unique identification of the variable or the method. Namespace tells the python interpreter about the name of the object and the location from where it is trying to access it.

The Namespaces are searched for scope resolution according to the LEGB rule. The LEGB stands for :L: Local, E: Enclosed, G: Global, B: Built-in. The sequence of LEGB is important. The variable is first searched in Local, followed by Enclosed, then global and finally built-in.

Читайте также:  Gradle java jar file

Types of Scope in Python

Following are the top 4 types of scope in python:

Types of Scope in Python

Let’s study how to declare a variable and how to access its scope:

1. Local Scope

The Variables which are defined in the function are a local scope of the variable. These variables are defined in the function body. Let’s understand this concept with the help of an example. In this example 1, we have taken one variable num. Num = 0 is defined outside the function, so it is not a local variable. As per our definition, the variables which are declared inside the function body is a local variable. Here num=1 is a local variable that is declared and printed inside the function demo. If we run this code, the output is given below.

num=0 def demo(): #print(num) num=1 print("The Number is:",num) demo()

Scope in Python1

Num is local to the function. When we use the num variable value in the function before declaring it locally, it raises an error.

Refer to Example 2: Here first print statement raises a python error as we are trying to access it before the assignment.

num=0 def demo(): print(num) num=1 print("The Number is:",num) demo()

Scope in Python 2

2. Global Scope

The Variable which can be read from anywhere in the program is known as a global scope. These variables can be accessed inside and outside the function. When we want to use the same variable in the rest of the program, we declare it as global.

In the following Example 1, we have declared a variable Str, which is outside the function. The function demo is called, and it prints the value of variable Str. To use a global variable inside a function, there is no need to use the global keyword.

def demo(): print(Str) # Global Str = "You are clever" demo()

In the Following Example, 2, We tried to change the value of the global variable Str inside the function; that’s why it raised an exception. If we modify or assign a new value to the variable inside the function, then we must write global. If you want to tell a python interpreter that you want to want to use a global variable, then the keyword “global” is used. If it has not been declared as global, then python treats that variable as local if it is created or modified inside the function. In this first line throws an exception because python assumes that we want assignment as a local variable due to assignment to str inside of function demo().

def demo(): print(Str) Str = "You are smart" print(Str) # Global scope Str = "You are Clever" demo() print(Str) 

Global Scope

When we want to change the value of the global variable inside the function global keyword is used.

The following Example 3 solved the problem which is encountered above.

def demo(): print(Str) Str = "You are smart" print(Str) # Global scope Str = "You are Clever" demo() print(Str) 

3. NonLocal or Enclosing Scope

Nonlocal Variable is the variable that is defined in the nested function. It means the variable can be neither in the local scope nor in the global scope. To create a nonlocal variable nonlocal keyword is used. In the following code, we created an outer function, and there is a nested function inner(). In the scope of outer() function inner() function is defined. If we change the nonlocal variable as defined in the inner() function, then changes are reflected in the outer function.

def func_outer(): x = "local" def func_inner(): nonlocal x x = "nonlocal" print("inner:", x) func_inner() print("outer:", x) func_outer()

NonLocal or Enclosing

If we just want to use the outer function’s value and do not want to make any changes, then comment (nonlocal a) line.

def func_outer(): a = "local" def func_inner(): #nonlocal a a = "nonlocal" print("inner:", a) func_inner() print("outer:", a) func_outer()

NonLocal or Enclosing

4. Built-in Scope

If a Variable is not defined in local, Enclosed or global scope, then python looks for it in the built-in scope. In the Following Example, 1 from math module pi is imported, and the value of pi is not defined in global, local and enclosed. Python then looks for the pi value in the built-in scope and prints the value. Hence the name which is already present in the built-in scope should not be used as an identifier.

# Built-in Scope from math import pi # pi = 'Not defined in global pi' def func_outer(): # pi = 'Not defined in outer pi' def inner(): # pi = 'not defined in inner pi' print(pi) inner() func_outer()

Built-in

Conclusion – Scope in Python

In this article, we learned about the python variable scope. We learned four types of scope – global scope, local scope, enclosed scope, and built-in scope. We also learned when to use global and nonlocal keywords. I hope you understood this concept.

Recommended Article

This is a guide to Scope in Python. Here we discuss types of Scope in Python and its Examples along with Code Implementation and Output. You can also go through our other related articles to learn more –

Источник

Оцените статью