search
HomeBackend DevelopmentPython TutorialPython Advanced: Closures Carrying State

Closure

In Python, a function is also an object. Therefore, when we define a function, we can define another nested function and return the nested function, for example:

from math import pow
def make_pow(n):
    def inner_func(x):     # 嵌套定义了 inner_func
        return pow(x, n)   # 注意这里引用了外部函数的 n
    return inner_func      # 返回 inner_func

In the above code, the function make_pow defines an inner function inner_func, and then Return this function. Therefore, we can use make_pow to generate another function:

>> > pow2 = make_pow(2)  # pow2 是一个函数,参数 2 是一个自由变量
>> > pow2
<function inner_func at 0x10271faa0 >
>> > pow2(6)
36.0

We also noticed that the inner function inner_func refers to the free variable n of the outer function make_pow, which means that when the life cycle of the function make_pow ends Afterwards, the variable n will still be saved in inner_func, which is referenced by inner_func.

>> > del make_pow         # 删除 make_pow
>> > pow3 = make_pow(3)
Traceback(most recent call last):
    File "<stdin>", line 1, in < module >
NameError:
    name &#39;make_pow&#39; is not defined
>> > pow2(9)     # pow2 仍可正常调用,自由变量 2 仍保存在 pow2 中
81.0

---|---

Like the above situation, a function returns an internal function, which refers to the relevant parameters and variables of the external function. We put the The returned inner function is called a closure.

In the above example, inner_func is a closure that refers to the free variable n.

The role of closure

  • The biggest feature of closure is that it references free variables. Even if the environment that generated the closure has been released, the closure still exists;

  • A closure can have multiple instances at runtime, even if the parameters passed in are the same, for example:

>> > pow_a = make_pow(2)
>> > pow_b = make_pow(2)
>> > pow_a == pow_b
False
  • Use closure Packages, we can also mock instances of classes.

Construct a class here to find the distance from one point to another:

from math import sqrt
class Point(object):
    def __init__(self, x, y):
        self.x, self.y = x, y
    def get_distance(self, u, v):
        distance = sqrt((self.x - u) ** 2 + (self.y - v) ** 2)
        return distance
>> > pt = Point(7, 2)        # 创建一个点
>> > pt.get_distance(10, 6)  # 求到另一个点的距离
5.0

Use closure to implement:

def point(x, y):
    def get_distance(u, v):
        return sqrt((x - u) ** 2 + (y - v) ** 2)
    return get_distance
>> > pt = point(7, 2)
>> > pt(10, 6)
5.0


As you can see, the result is the same, but using closures is more concise than using classes.

Common Misunderstandings

The concept of closure is very simple, but it is prone to some misunderstandings in its implementation, such as the following example:

def count():
    funcs = []
    for i in [1, 2, 3]:
        def f():
            return i
        funcs.append(f)
    return funcs

In this example, we A function is created in the for loop and stored in funcs. Now, when calling the above function, you may think that the return result is 1, 2, 3, but in fact it is not:

>> > f1, f2, f3 = count()
>> > f1()
3
>> > f2()
3
>> > f3()
3

Why? The reason is that the above function f refers to the variable i, but the function f is not executed immediately. When the for loop ends, the value of the variable i is 3, and the variables referenced by the functions in funcs are all 3, and the final result is all 3.

Therefore, we should try to avoid referencing loop variables in closures, or variables that will change subsequently.

How to solve the above situation? We can create another function and pass the value of the loop variable to the function, as follows:

def count():
    funcs = []
    for i in [1, 2, 3]:
        def g(param):
            f = lambda: param    # 这里创建了一个匿名函数
            return f
        funcs.append(g(i))        # 将循环变量的值传给 g
    return funcs
>> > f1, f2, f3 = count()
>> > f1()
1
>> > f2()
2
>> > f3()
3

Summary

  • A closure is a function that carries free variables, even if When the life cycle of the external function that created the closure ends, the free variables referenced by the closure still exist.

  • A closure can have multiple instances at runtime.

  • Try not to reference loop variables in closures, or variables that will change later.

The above is the content of Python advanced: closure carrying state. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor