How variable scope works in Python function?


In this article we will discuss about how a variable scope works in Python function.

The scope of a name is the area of a program in which you can clearly access a name, such as variables.

Hence, a variable scope is the region in which we can access a variable as shown in the following example -

def multiplication():
   product = 7*9

Here, the “product” variable is created inside the function, therefore it can only be accessed within it.

In general, the python scope concept is presented using the rule called as the LEGB rule which is based on the four main categories of a variable scope. It stands for -

  • Local

  • Enclosing

  • Global

  • Built-in.

Let’s discuss about all the scopes one-by-one.

Local Scope

When a variable is defined within a function, its scope is restricted to the function. It exists as long as the function is running (Source) and is available from the time it is defined until the end of the function. Which implies that neither its value nor even access from outside the function is possible.

Example

Following is an example of local scope variable -

def prime_numbers():
   first_prime_no = 2
   print("The first prime number is: ", first_prime_no)

# the driver code
prime_numbers()
print("The first prime number is: ", first_prime_no)

Output

By using the function "prime numbers()," we were able to print the value of the "first prime no" variable. However, it raised a NameError when attempting to read and then print the same variable from outside the function. Because "first prime no" is "local" to the function and cannot be accessed from outside the function body as seen in the below output:

The first prime number is: 2
Traceback (most recent call last):
   File "C:\Users\Lenovo\Desktop\untitled.py", line 6, in <module>
      print("The first prime number is: ", first_prime_no)
NameError: name 'first_prime_no' is not defined

Global Scope

Possibly this is the simplest scope to learn . A variable becomes a global variable whenever it is defined outside of any function, and its scope is anywhere within the entire program. This means that it can be used inside any function. Additionally, we can modify the value of a global variable.

Example

Following is an example of global scope variable -

animal = "Lion"
def animal_species():
   pantheria = "Pantheria"
   print('The name and species of the animal is:',animal, pantheria)
def animal_kingdom(name):
   print('The name and kingdom of the animal is:',animal, name)
animal_species()
animal_kingdom("Animalia")

Output

Following is an output of the above code -

The name and species of the animal is: Lion Pantheria
The name and kingdom of the animal is: Lion Animalia

Enclosing Scope

A special scope that is only available for nested functions is the enclosing (or nonlocal) scope. The enclosing scope is the scope of the outer or enclosing function if the local scope is an inner or nested function. The names that you define in the enclosing function are contained in this scope.

Example

Within the 'Lion()' function of the example code, the variable'species' is utilised. It is neither a local nor a global scope in that situation. The term "enclosing scope" refers to this -

def animal():
   species = "Pantheria"
   def Lion():
      kingdom= "Animalia"
      print('The species of the animal is:', species)
      print('The kingdom of the animal is:',kingdom)
   Lion()
animal()

Output

Following is an output of the above code -

The species of the animal is: Pantheria
The kingdom of the animal is: Animalia

Built-in Scope

In Python, this has the widest reach. Each reserved name in a module that comes with Python has its own built-in scope. The Python searches the built-in scope to determine if an identifier is defined there when it cannot be found in the local, enclosing, or global scopes.

Python would first check the local scope to verify which variables are defined there, then the enclosing scope, and finally the global scope. In the event that the identifier cannot be found anywhere, the built-in scope will be checked last.

Example

The functions int(), print(), and type() don't need to be defined in this case because they are defined in Python's built-in scope -

x = 17.89
int(x)
print('The value of x is:',x)
print('The type of x is:',type(x))

Output

Following is an output of the above code -

The value of x is: 17.89
The type of x is: <class 'float'>

Global keyword in Python

By using global, you instruct Python to use the globally declared variable rather than creating one locally. Simply type "global" and the variable name to utilise the keyword.

Example

Following is an example of using global keyword in Python -

animal = "Lion"
def animal_species(Pan):
   global animal
   animal = Pan
def animal_kingdom():
   animalia = "Animalia"
   print('The animal species and kingdom is:',animal,animalia)
animal_species('Pantheria')
animal_kingdom()

Output

Now that we've seen it, we can state that we wish to use the variable "animal," which is defined in the global scope, by using the global keyword. Hence, we changed the value outside of the function when we assigned the value "Pan" to the variable.

The animal species and kingdom is: Pantheria Animalia

Example

Following is an example of using global keyword in Python -

animal = "Lion"
def animal_name():
   animal = "Panther"
   print('The animal is:',animal)
animal_name()
print ('The animal is:',animal)

Output

The code above will print the values "Panther" and "Lion" because "animal" refers to "Panther" in the local scope variable and to the global variable outside of the method() function.

The animal is: Panther
The animal is: Lion

Nonlocal keyword in Python

Nonlocal is a useful keyword for nested functions. The previously bound variable in the closest enclosing scope is referenced by the variable as a result. In other words, it will stop the variable from trying to bind locally first and push it to move up a level. Like the global keyword, the syntax is same.

Example

In the following example "animal" refers to a "local variable" in the function "animal kingdom()", a "nonlocal variable" in the method "animal name()," and a "global variable" outside of these functions. The nonlocal variable is now used -

animal = "Lion-global variable"
def animal_name():
   animal = "Panther-nonlocal variable"
   def animal_kingdom():
      nonlocal animal
      animal = "Animalia-local variable"
      print('The animal is:',animal)
   animal_kingdom()
   print('The animal is:',animal)
animal_name()
print ('The animal is:',animal)

Output

In the function(), i.e., "animal kingdom()," we utilized the nonlocal keyword on the "animal" variable. Because of this, when we modified the value of the nonlocal variable, "animal," which is defined in the method() function i.e. "animal name()," it also changed its value.

The animal is: Animalia-local variable
The animal is: Animalia-local variable
The animal is: Lion-global variable

Updated on: 19-Dec-2022

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements