The nonlocal keyword in Python is used within nested functions to indicate that a variable refers to a previously bound variable in the nearest enclosing but non-global scope. This allows modification of variables in an outer function from within an inner function without making them global.
Example:
Python
def outer():
message = "Hello"
def inner():
nonlocal message # Reference the enclosing variable
message = "Hello, Python!" # Modify it
print("Inside inner:", message)
inner()
print("Inside outer:", message)
outer()
OutputInside inner: Hello, Python!
Inside outer: Hello, Python!
Explanation: Here, nonlocal message
ensures that message
inside inner(
)
modifies the message
variable from outer()
instead of creating a new local variable.
Why use nonlocal ?
In Python, variables have different scopes:
- Local Scope: Variables defined inside a function.
- Enclosing Scope: Variables in an enclosing function but not global.
- Global Scope: Variables declared at the top level of the script.
- Built-in Scope: Names preassigned in Python.
When a variable is declared inside a function, it is local by default. The nonlocal
keyword allows modifying an enclosing function's variable instead of creating a new local variable.
nonlocal vs global
While both nonlocal
and global
allow modifying variables from an outer scope, their scope is different:
Keyword | Scope affected | can modify local variable ? | can modify global variable ? |
---|
nonlocal | Enclosing (non-global ) function scope | Yes | No |
---|
global | global scope | No | Yes |
---|
Example:
Python
a = "I am global"
def outer():
b = "I am enclosing"
def inner():
global a
nonlocal b
a = "Modified global"
b = "Modified enclosing"
inner()
print("Inside outer:", b)
outer()
print("Outside outer:", a)
OutputInside outer: Modified enclosing
Outside outer: Modified global
Explanation: Here, a
is modified globally using global
, while b
is modified in the enclosing scope using nonlocal
.
Rules and Restrictions of non local
- It cannot reference global or local variables; it only works within nested functions.
- The variable being referenced must exist in the nearest enclosing function scope.
nonlocal
cannot be used at the module level or in a function without an enclosing scope.
Example: Incorrect usage
Python
# Global variable
global_a = 'geeksforgeeks'
def outer():
def inner():
nonlocal global_a # Attempting to reference global variable
global_a = 'GeeksForGeeks' # Modifying the variable
print(global_a)
inner()
outer()
Output:
Hangup (SIGHUP)
File "/home/guest/sandbox/Solution.py", line 6
nonlocal global_a # Attempting to reference global variable
^^^^^^^^^^^^^^^^^
SyntaxError: no binding for nonlocal 'global_a' found
Explanation: This will result in an error because nonlocal
can only reference variables from an enclosing function, not from the global scope.
Scope resolution with nonlocal
When multiple nested functions have a variable with the same name, nonlocal references the nearest enclosing function’s variable, not the global one.
Python
def fun1():
name = "geek"
def fun2():
name = "Geek"
def fun3():
nonlocal name
name = 'GEEK' # Modify before using
print(name)
fun3()
print(name) # Modified value in fun2()
fun2()
print(name) # Unchanged value in fun1()
fun1()
Explanation: fun3() uses nonlocal to modify name in fun2() to "GEEK", which both fun3() and fun2() print. fun1() remains unaffected, printing "geek", showing nonlocal affects only the nearest enclosing scope.
Practical application of nonlocal
One common use case of nonlocal
is maintaining state in closures, such as implementing a counter function.
Python
def counter():
count = 0 # Enclosed variable
def increment():
nonlocal count # Reference count from the outer function
count += 1
return count
return increment
# Create a counter instance
counter1 = counter()
print(counter1())
print(counter1())
print(counter1())
Explanation: This code uses nonlocal in a closure to maintain count across calls, allowing increment() to update and return it.
Advantages of nonlocal
- Allows access to variables in an upper scope (excluding global scope).
- Saves memory by reusing the referenced variable’s memory address.
- Useful in closures where state persistence is needed.
Disadvantages of nonlocal
- Cannot be used for global or local scope variables.
- Only applicable within nested functions.
Similar Reads
Python Keywords Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. List of Keywords in PythonTrueFalseNoneandornotisifelseelifforwhilebreakconti
11 min read
Keyword Module in Python Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are una
2 min read
Python in Keyword The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary.Example:Pythons = "Geeks for geeks" if "for" in s: print("found") else: print("not found")
3 min read
as Keyword - Python as keyword in Python plays a important role in simplifying code, making it more readable and avoiding potential naming conflicts. It is mainly used to create aliases for modules, exceptions and file operations. This powerful feature reduces verbosity, helps in naming clarity and can be essential whe
3 min read
Python def Keyword Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the âdefâ keyword. In Python def
6 min read
locals() function-Python locals() function in Python returns a dictionary representing the current local symbol table, allowing you to inspect all local variables within the current scope e.g., inside a function or block. Example:Pythondef fun(a, b): res = a + b print(locals()) fun(3, 7)Output{'a': 3, 'b': 7, 'res': 10} Exp
4 min read
Python "from" Keyword The from keyword in Python is mainly used for importing specific parts of a module rather than the entire module. It helps in making the code cleaner and more efficient by allowing us to access only the required functions, classes, or variables.Here's an example.Python# Importing only sqrt function
2 min read
python class keyword In Python, class keyword is used to create a class, which acts as a blueprint for creating objects. A class contains attributes and methods that define the characteristics of the objects created from it. This allows us to model real-world entities as objects with their own properties and behaviors.S
1 min read
is keyword in Python In programming, a keyword is a âreserved wordâ by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Py
2 min read
Use of nonlocal vs use of global keyword in Python Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. Python3 def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across en
3 min read