Python Tutorial - Local Functions (Including Nonlocal Keywords)

Python Exercise Lists

Through the previous learning, we know that variables can be defined inside Python functions, which results in local variables. Some readers may ask, can Python define functions inside functions? The answer is yes. Python supports defining functions inside functions, which are also called local functions.

So, what are the characteristics of local functions, and what do you need to pay attention to when using them? Next, the reader is introduced to the usage of Python local functions in detail.

First, like local variables, by default local functions can only be used within the scope of the function they are in.

For example:

#Global functions
def outdef ():
    #Local functions
    def indef ():
        print ("http://www.freelearningpoints.com/python/")
    #Calling local functions
    indef ()
#Call global function
outdef ()
           

The output is:

http://www.freelearningpoints.com/python/

Just as a global function returns its local variable, you can expand the scope of the variable. By using the local function as the return value of the function, you can also expand the scope of the local function. For example, modify the above program to:

#Global functions
def outdef ():
    #Local functions
    def indef ():
        print ("Call a local function")
    #Calling local functions
    return indef
#Call global function
new_indef = outdef ()
#Calling local functions in global functions
new_indef ()
           

The output is:

Call a local function

Therefore, the scope of a local function can be summarized as follows: if the local function does not return a local function, the available range of the local function is limited to the local function; conversely, if the local function has a local function as the return value, the role of the local function The domain will be expanded, which can be used inside the function where it is located or in the scope of the function where it is located.

Take outdef and indef function in the above program as examples. If outdef function does not use indef as the return value, indef can only be used inside the outdef function; otherwise, the indef function can be used internally in the outdef function and can also be used in the scope of the outdef function, that is, globally.

It is also worth mentioning that if a local function defines a variable with the same name as the variable in the function, the problem of "shadowing" will also occur. Example:

#Global functions
def outdef ():
    name = "name variable defined in function"
    #Local functions
    def indef ():
        print (name)
        name = "name variable defined in local function"
    indef ()
#Call global function
outdef ()
           

When executing this program, the Python interpreter will report the following error:

---------------------------------------------------------------------------
UnboundLocalError      Traceback (most recent call last)
[ipython-input-40-50453fdd2d0e] in [module]
8 indef ()
9 #Call global function
---> 10 outdef ()
[ipython-input-40-50453fdd2d0e] in outdef()
6 print (name)
7 name = "name variable defined in local function"
----> 8 indef ()
9 #Call global function
10 outdef ()
[ipython-input-40-50453fdd2d0e] in indef()
4 #Local functions
5 def indef ():
----> 6 print (name)
7 name = "name variable defined in local function"
8 indef ()
UnboundLocalError: local variable 'name' referenced before assignment

This error literally means "local variable name is used before it is defined". The reason for this error is that the name variable defined in the local function indef obscures the name variable defined in the function outdef. In addition, the definition of the name variable in the indef function is located after the print output statement. As a result, the print (name) statement could not find the defined name variable during execution, so the program reported an error.

Because the name variable here is also a local variable, the globals function or the globals keyword explained in the previous section are not suitable for solving this problem. Here you can use the nonlocal keyword provided by Python.

For example, modify the above program to:

#Global functions
def outdef ():
    name = "name variable defined in function"
    #Local functions
    def indef ():
        nonlocal name
        print (name)
        #Modify the value of the name variable
        name = "name variable defined in local function"
    indef ()
#Call global function
outdef ()
           

The output is:

name variable defined in function

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises