A deep understanding of the Python closure mechanism

Source: Internet
Author: User

This article takes Python as an example to explain the closure in a brief way. According to Baidu Encyclopedia, closures are functions that can read other functions inside variables, such as JavaScript, where only sub-functions inside functions can read local variables, so closures can be understood as "functions defined inside a function" In essence, closures are bridges that connect functions inside and outside of functions

Understanding the definition of closures


Definition: Closure (closure) is a function that can read the internal variables of other functions

Understanding: According to split statement analysis, closures are ... function, the original closure is a function, then look at the details, the closure is what kind of function, the closure can also read other function internal variables, in other words, the closure function can get the information of other functions internal variables--so that the information is encapsulated, like a package, compare the image

Instance:

Def make_averager ():    series = []    def averager (new_value):        series.append (new_value) Total        = SUM ( Series) return        Total/len (series)    return Averager
>>> avg = Make_averager () >>> avg (TEN) 10.0>>> avg (one) 10.5>>> avg (12) 11.0

Note: Closures (closure) are short for lexical closures (lexical closure) and are an important grammatical structure for functional programming.

Python namespace, scope rules

In C + +, there is a special keyword namespace (in the English namespace)

In Python, there are four types of namespaces:

1) local namespace : Local Variables

2) nonlocal namespace : variable of outer function in nested function (python3.x)

3) global namespace : Global variables

4) build-in namespace : Built-in variables

namespace is a mapping of the variable name to the actual object, and most of the namespace is implemented as a dictionary in Python.

nonlocalKeywords are introduced in Python3.0, which makes it easy to access and modify the outer variables of nested functions (if only access is not modified without nonlocal keywords)

If you modify the outer variables without using nonlocal keywords, you will get an error:

Def make_averager ():    count = 0    total = 0    def averager (new_value):        count + = 1    # same As:count = Count + 1 Total        + = New_value        return total/count    return average
>>> avg = Make_averager () >>> avg (Traceback) (most recent): ... Unboundlocalerror:local variable ' count ' referened before assignment>>>

To modify an outer variable, you must use the nonlocal keyword:

Def make_averager ():    count = 0    total = 0    def averager (new_value):        nonlocal count    Declaration of namespace.        Count + = 1 Total        + = New_value        return total/count    return average
>>> avg = Make_averager () >>> avg (TEN) 10.0>>> avg (one) 10.5>>> avg (12) 12

Explanation: In the Averager function, count, total is a free variable (the free variable refers to a variable that is not locally bound ), and the free variable is often declared in one scope and used in another scope (such as the series above, Count, Total

So why in the example of "Understanding the definition of closure", the series variable is a free variable for the inner layer function but can be modified directly? To differentiate the meaning of the "modified" of the variable type and the immutable type, the series list is a mutable sequence, and the method is used to modify the value of the append() list in situ , where we only use the "list mutable" List of properties , But for immutable numeric objects count, total, count += 1 such operations actually generate new objects

Always remember that a free variable can only be referenced and cannot be modified (unless a Mutable object can be modified in-place, in fact it is implemented in python2.x), and the nonlocal keyword must be used to modify it



Closures and lambda expressions

A Python lambda expression is an anonymous function that can be equated

For demonstration purposes, a list derivation with a for loop or pythonic is a good choice:



Closures and decorators

To implement your own adorner (decorator) in Python, you must know: 1) closure + nesting function, 2) nonlocal keyword (python3.x introduced)

"" "Implement a decorator, which return the runtime of the program." " Import Timedef Clock (func):    def clocked (*args):        t0 = time.pref_counter ()        result = Func (*args)        elapsed = Time.pref_counter ()-T0        name = func.__name__        arg_str = ', '. Join (REPR (ARG) for Arg in args)        Prin T (' [%0.8fs]%s (%s),%r '% (elpased, name, ARG_STR, result))        return result    return clocked

This article takes Python as an example to explain the closure in a brief way. According to Baidu Encyclopedia, closures are functions that can read other functions inside variables, such as JavaScript, where only sub-functions inside functions can read local variables, so closures can be understood as "functions defined inside a function" In essence, closures are bridges that connect functions inside and outside of functions

Understanding the definition of closures

Definition: Closure (closure) is a function that can read the internal variables of other functions

Understanding: According to split statement analysis, closures are ... function, the original closure is a function, then look at the details, the closure is what kind of function, the closure can also read other function internal variables, in other words, the closure function can get the information of other functions internal variables--so that the information is encapsulated, like a package, compare the image

Instance:

Def make_averager ():    series = []    def averager (new_value):        series.append (new_value) Total        = SUM ( Series) return        Total/len (series)    return Averager
>>> avg = Make_averager () >>> avg (TEN) 10.0>>> avg (one) 10.5>>> avg (12) 11.0

Note: Closures (closure) are short for lexical closures (lexical closure) and are an important grammatical structure for functional programming.

Python namespace, scope rules

In C + +, there is a special keyword namespace (in the English namespace)

In Python, there are four types of namespaces:

1) local namespace : Local Variables

2) nonlocal namespace : variable of outer function in nested function (python3.x)

3) global namespace : Global variables

4) build-in namespace : Built-in variables

namespace is a mapping of the variable name to the actual object, and most of the namespace is implemented as a dictionary in Python.

nonlocalKeywords are introduced in Python3.0, which makes it easy to access and modify the outer variables of nested functions (if only access is not modified without nonlocal keywords)

If you modify the outer variables without using nonlocal keywords, you will get an error:

Def make_averager ():    count = 0    total = 0    def averager (new_value):        count + = 1    # same As:count = Count + 1 Total        + = New_value        return total/count    return average
>>> avg = Make_averager () >>> avg (Traceback) (most recent): ... Unboundlocalerror:local variable ' count ' referened before assignment>>>

To modify an outer variable, you must use the nonlocal keyword:

Def make_averager ():    count = 0    total = 0    def averager (new_value):        nonlocal count    Declaration of namespace.        Count + = 1 Total        + = New_value        return total/count    return average
>>> avg = Make_averager () >>> avg (TEN) 10.0>>> avg (one) 10.5>>> avg (12) 12

Explanation: In the Averager function, count, total is a free variable (the free variable refers to a variable that is not locally bound ), and the free variable is often declared in one scope and used in another scope (such as the series above, Count, Total

So why in the example of "Understanding the definition of closure", the series variable is a free variable for the inner layer function but can be modified directly? To differentiate the meaning of the "modified" of the variable type and the immutable type, the series list is a mutable sequence, and the method is used to modify the value of the append() list in situ , where we only use the "list mutable" List of properties , But for immutable numeric objects count, total, count += 1 such operations actually generate new objects

Always remember that a free variable can only be referenced and cannot be modified (unless a Mutable object can be modified in-place, in fact it is implemented in python2.x), and the nonlocal keyword must be used to modify it



Closures and lambda expressions

A Python lambda expression is an anonymous function that can be equated

For demonstration purposes, a list derivation with a for loop or pythonic is a good choice:



Closures and decorators

To implement your own adorner (decorator) in Python, you must know: 1) closure + nesting function, 2) nonlocal keyword (python3.x introduced)

"" "Implement a decorator, which return the runtime of the program." " Import Timedef Clock (func):    def clocked (*args):        t0 = time.pref_counter ()        result = Func (*args)        elapsed = Time.pref_counter ()-T0        name = func.__name__        arg_str = ', '. Join (REPR (ARG) for Arg in args)        Prin T (' [%0.8fs]%s (%s),%r '% (elpased, name, ARG_STR, result))        return result    return clocked

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.