Open In App

Python nonlocal Keyword

Last Updated : 14 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python nonlocal keyword is used to reference a variable in the nearest scope. 

Python nonlocal Keyword Example

 In this example, we demonstrate the working of the nonlocal keyword.

Python3




def foo():
    name = "geek" # Our local variable
 
    def bar():
        nonlocal name          # Reference name in the upper scope
        name = 'GeeksForGeeks' # Overwrite this variable
        print(name)
         
    # Calling inner function
    bar()
     
    # Printing local variable
    print(name)
 
foo()


Output

GeeksForGeeks
GeeksForGeeks

What is nonlocal keyword in Python

The nonlocal keyword won’t work on local or global variables and therefore must be used to reference variables in another scope except the global and local one. The nonlocal keyword is used in nested functions to reference a variable in the parent function. 

Advantages of nonlocal:

  • It helps in accessing the variable in the upper scope.
  • Since the referenced variable is reused, the memory address of the variable is also reused and therefore it saves memory.

Disadvantages of nonlocal:

  • The nonlocal keyword can’t be used to reference global or local variables.
  • The nonlocal keyword can only be used inside nested structures.

Example 1: In this example, we see what happens when we make a nonlocal variable to refer to the global variable.

Python3




# Declaring a global variable
global_name = 'geeksforgeeks'
 
 
def foo():
   
    # Defining inner function
    def bar():
       
        # Declaring nonlocal variable
        nonlocal global_name        # Try to reference global variable
        global_name = 'GeeksForGeeks'# Try to overwrite it
        print(global_name)
         
    # Calling inner function
    bar()
     
foo()


Output:

SyntaxError: no binding for nonlocal 'name' found

Example 2: In this example, we will see which variable nonlocal refers to when we have multiple nested functions with variables of the same name.

Python3




def foo():
 
    # Local variable of foo()
    name = "geek"
 
    # First inner function
    def bar():
        name = "Geek"
 
        # Second inner function
        def ack():
            nonlocal name # Reference to the next upper variable with this name
            print(name)   # Print the value of the referenced variable
            name = 'GEEK' # Overwrite the referenced variable
            print(name)
 
        ack() # Calling second inner function
     
    bar() # Calling first inner function
    print(name) # Printing local variable of bar()
 
foo()


Output

Geek
GEEK
geek

Example 3: In this example, we will build a reusable counter (Just for demonstration purpose

Python3




# Our counter function
def counter():
  c = 0 # Local counter variable
   
  # This function manipulate the
  # local c variable, when called
  def count():
    nonlocal c
    c += 1
    return c
   
  # Return the count() function to manipulate
  # the local c variable on every call
  return count
 
# Assign the result of counter() to
# a variable which we use to count up
my_counter = counter()
for i in range(3):
  print(my_counter())
print('End of my_counter')
   
# Create a new counter
new_counter = counter()
for i in range(3):
  print(new_counter())
print('End of new_counter')


Output

1
2
3
End of my_counter
1
2
3
End of new_counter

Note: Notice how the local c variable keeps alive on every call of our counter variables.



Similar Reads

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. C/C++ Code def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested f
3 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Python assert keyword
Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn't allow the code to execute further. Assert Keyword in PythonIn simpler terms, we can say that ass
7 min read
finally keyword in Python
Prerequisites: Exception Handling, try and except in Python In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on. So, in order to handle these situations, Python provides a ke
3 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 unaware of all the keywords of Python you can use thi
2 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 Python, keywords are case-sensitive. Python is Keywo
2 min read
Python IMDbPY - Searching keyword
In this article we will see how we can search a keyword in the IMDb database.Keyword : It is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discov
1 min read
Python IMDbPY – Searching movies matching with keyword
In this article we will see how we can find movies that have similar keyword. Keyword is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discover t
1 min read
Python None Keyword
None is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. C/C++ Code def check_return(): pass print(check_return()) Output: NoneNull Vs None in Python
2 min read
Python as Keyword
In this article, we are going to see 'as' Keyword. The keyword 'as' is used to create an alias in python. Advantages with 'as' keyword: It is useful where we cannot use the assignment operator such as in the import module.It makes code more understandable to humans.The keyword as is used to make alias with programmer selected name, It decreases the
2 min read
Python or Keyword
Python OR is a logical operator keyword. The OR operator returns True if at least one of the operands becomes to be True. Note: In Python or operator does not return True or False. The or operator in Python returns the first operand if it is True else the second operand.Python OR Keyword Truth TableInput 1Input2OutputTrueTrueTrueTrueFalseTrueFalseT
2 min read
Python False Keyword
A boolean expression results in two values(True, False) similar to this a boolean variable can also be assigned either (True, False). Here False keyword represents an expression that will result in not true. Example 1 : In this example first, we will give one boolean expression which will result in False (10 < 6). Next, we assigned the False key
2 min read
How to Fix: SyntaxError: positional argument follows keyword argument in Python
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python An argument is a value provided to a function when you call that function. For example, look at the below program - Python Code # function def calculate_square(num): return num * num # call the function result = calculate_squa
3 min read
Python in Keyword
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 Python, keywords are case-sensitive. Python in Keywo
2 min read
Python Raise Keyword
In this article, we will learn how the Python Raise keyword works with the help of examples and its advantages. Python Raise KeywordPython raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it c
3 min read
How to check if a string is a valid 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. What is Keywords in PythonPython also reserves some keywords that convey special meaning. Knowledge of these is a necessary part of lea
2 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 keyword is the most used keyword. Python def Synta
7 min read
Python | yield Keyword
In this article, we will cover the yield keyword in Python. Before starting, let's understand the yield keyword definition. Syntax of the Yield Keyword in Python def gen_func(x): for i in range(x): yield iWhat does the Yield Keyword do?yield keyword is used to create a generator function. A type of function that is memory efficient and can be used
6 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
Keyword and Positional Argument in Python
Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call. Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Keyword and Positional ArgumentKeyword-Only Argument
4 min read
The yield Keyword in Ruby
We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with
2 min read
Scala this keyword
Keywords are the words in a language that are used to represent some predefined actions or some internal process. We use the this keyword when we want to introduce the current object for a class. Then using the dot operator (.), we can refer to instance variables, methods and constructors by using this keyword. this keyword is also used with auxili
2 min read
Scala | yield Keyword
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn't work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over
2 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Practice Tags :