Closures in Python

  • 2021-12-11 18:34:01
  • OfStack

Directory 1, Closure Concept 2, Closure Condition 3, Closure Complete Counting Effect 4, Closure Shortcomings and Functions

1. The concept of closure

The concept of closure in function is simply that a function definition refers to variables defined outside the function, and the function can be executed outside its defined environment. Such a function is called a closure. In fact, closure can be regarded as a more generalized function concept. Because it is no longer a function defined in the traditional sense.

The concept of closures is not limited to Python It exists in almost any programming language.

2. Closure conditions

Conditions for closures:

Internal functions are defined in external functions External functions have return values The return value is: internal function The inner function also references the variables of the outer function

The format is as follows:


def  External function ():
    ...
    def  Internal function ():
        ...
    return  Internal function 

Sample code:


def func():
    a = 100

    def inner_func():
        b = 200
        print(a, b)

    return inner_func


x = func()
print(x)  # <function func.<locals>.inner_func at 0x0000021704CD9620>
x()  # 100 200
#  So you can call directly inner_func Function, if return Do not return 1 There will be no output if you have an internal function 

3. Closure completes counting effect

Using closures can also accomplish the effects of counters


def generate_count():
    container = [0]

    def add_one():
        container[0] += 1
        print(f" This is the first {container[0]} Secondary call ")

    return add_one


count = generate_count()
count()  #  This is the first 1 Secondary call 
count()  #  This is the first 2 Secondary call 
count()  #  This is the first 3 Secondary call 

4. Disadvantages and functions of closures

The disadvantages of closures are as follows:

Scope is not so intuitive Because variables will not be garbage collected, there is a fixed memory consumption problem.

The function of closures is as follows:

You can use sibling scopes Read the internal variables of other elements Extended scope

Related articles: