Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

What is the nonlocal keyword in Python?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss the nonlocal keyword in Python.

Variables in Python are mainly of 2 types:

  • Global variables: Declared outside the function or in a global scope.

  • Local variables: Declared inside the function’s body or in a local scope.

The nonlocal keyword is used to work with variables inside nested functions whose local scopes are not defined.

In other words, when we declare a variable as nonlocal, it means it is neither local nor global.

Suppose we have a nested function, as shown in the code snippet below.

# First Function
def f():
x = 10
# Nested Function
def g():
x = 1
g()
print (x)
f()
Without using nonlocal keyword in Python

Expected output

Although we expect the output to be 1, that is not the case. The actual output here will be 10.

Explanation

x = 10 and x = 1 have different IDs, meaning that they are stored as different objects. So, when we call the f() function, the local variable x (which is equal to 10) is returned.

Now, if we want to get x = 1 as the output, we need to add the nonlocal keyword inside the nested function, as shown below.

# First Function
def f():
x = 10
# Nested Function
def g():
nonlocal x
x = 1
g()
print (x)
f()
Using nonlocal keyword in Pythod

Explanation

  • In line 2, we initiate our first function.

  • In line 3, we declare a local variable x = 10.

  • In line 6, we declare a nested function.

  • In line 7, we assign the nonlocal keyword to x, as a result of which any defined values of x will now be taken in subsequent entries and the result will be the new x.

  • In line 8, we assign a value of 1 to x.

  • In line 9, we call the g() function, which now carries x = 1 along with it.

  • In line 10, we print the value of x, which comes out to be 1.

  • In line 12, we call the f() function so that the entire function gets executed.

RELATED TAGS

communitycreator
python

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring