Closure summary in Python and closure summary in Python

Source: Internet
Author: User

Closure summary in Python and closure summary in Python

A few days ago, someone posted a message in my article python project Exercise 1: Mark it instantly, but I am not sure about the use of a closure and re. sub. I searched my blog and found that I didn't write anything about closures. So I decided to sum up and improve the Python content on my blog.

1. Concepts of closures

First, we have to start with the basic concept. What is a closure? Let's take a look at the explanation on the Wikipedia:
Copy codeThe Code is as follows:
In computer science, Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment. A closure can have multiple instances at runtime. Different reference environments and the same function combination can generate different instances.
....

The two key points mentioned above are free variables and functions. I still have to repeat the meaning of "closure". I hope I can understand it as a closed package. This package is a function, and of course the internal logic of the function, the items in the package are free variables, which can wander around with the package. Of course, there must be a premise that this package was created.

In the Python language, A closure is that you call function A, and function A Returns function B to you. The returned function B is called a closure. The parameter you pass when calling function A is A free variable.

For example:
Copy codeThe Code is as follows:
Def func (name ):
Def inner_func (age ):
Print 'name: ', name, 'Age:', age
Return inner_func

Bb = func ('the5fire ')
Bb (26) # >>> name: the5fire age: 26

When func is called, a closure -- inner_func is generated and the closure holds the free variable -- name. Therefore, this means that after the lifecycle of the function func ends, the name variable still exists because it is referenced by the closure and will not be recycled.

In addition, closures are not a special concept in Python. All languages that use functions as first-class citizens have the concept of closures. However, closures can also be used in languages like Java where class is the first-class citizen, but they must be implemented using classes or interfaces.

For more conceptual information, refer to the final reference link.

2. Why use closures?

Based on the above introduction, I don't know if the reader feels similar to the class. The similarity is that they provide data encapsulation. The difference is that the closure itself is a method. Like classes, we often abstract common things into classes during programming (and, of course, we also model the real world-business) to reuse common functions. The same is true for closures. When we need to abstract the granularity of functions, closures are a good choice.

At this point, the closure can be understood as a read-only object. You can pass an attribute to it, but it can only provide you with an interface for execution. Therefore, in the program, we often need such a function object -- closure to help us complete a common function, such as the -- decorator mentioned later.

3. Use closures

The first scenario is the decorator, which is very important and common in python. Python provides a friendly "syntax sugar" for the decorator "--@, we can easily use the decorator. The decoration principle is not described too much. Simply put, adding @ decorator_func to a function func is equivalent to decorator_func (func ):
Copy codeThe Code is as follows:
Def decorator_func (func ):
Def wrapper (* args, ** kwargs ):
Return func (* args, ** kwargs)
Return wrapper

@ Decorator_func
Def func (name ):
Print 'My name is ', name

# Equivalent
Decorator_func (func)

In this example of the decorator, the closure (wrapper) holds the external func parameter, and can accept the externally passed parameters. The accepted parameters are passed to func intact, and return the execution result.

This is a simple example. A slightly more complex point can have multiple closures, such as the LRUCache decorator that is frequently used. The decorator can accept the parameter @ lru_cache (expire = 500. The implementation is the nesting of two closures:

Copy codeThe Code is as follows:
Def lru_cache (expire = 5 ):
# Default 5s timeout
Def func_wrapper (func ):
Def inner (* args, ** kwargs ):
# Cache processing bala
Return func (* args, ** kwargs)
Return inner
Return func_wrapper

@ Lru_cache (expire = 10*60)
Def get (request, pk)
# Omitting specific code
Return response ()

Those who do not know the closure must be able to understand the above Code. This is an interview question we often asked before.
The second scenario is based on a feature of the closure-"Evaluate inertia ". This application is common when accessing databases, for example:

Copy codeThe Code is as follows:
# Pseudocode Diagram

Class QuerySet (object ):
Def _ init _ (self, SQL ):
Self. SQL = SQL
Self. db = Mysql. connect (). corsor () # pseudocode

Def _ call _ (self ):
Return db.exe cute (self. SQL)

Def query (SQL ):
Return QuerySet (SQL)

Result = query ("select name from user_app ")
If time> now:
Print result # The database access is only executed at this time.

The above example shows how to use a closure to evaluate the inertia. However, the result returned by the preceding query is not a function, but a class with function functions. If you are interested, you can see the implementation of Django's queryset. The principle is similar.

In the third scenario, you need to assign values to the parameters of a function in advance. Of course, there is a good solution to accessing functools. parial in Python, but it can also be implemented using closures.

Copy codeThe Code is as follows:
Def partial (** outer_kwargs ):
Def wrapper (func ):
Def inner (* args, ** kwargs ):
For k, v in outer_kwargs.items ():
Kwargs [k] = v
Return func (* args, ** kwargs)
Return inner
Return wrapper

@ Partial (age = 15)
Def say (name = None, age = None ):
Print name, age

Say (name = "the5fire ")
# Of course, using functools is much simpler than this one.
# Only: functools. partial (say, age = 15) (name = 'the5fire ')

This seems to be a far-fetched example, but it is also a practice of the closure application.

Finally, the closure is easy to understand and widely used in Python. This article is a summary of the closure. If you have any questions, please leave a message.


Python Closure

This code should replace the text that matches the dictionary key in the text with the value corresponding to the key.
Rx. sub (one_xlat, text) does not pass a match parameter to sub. The first parameter is a function. The parameter of this function is the matchobject matched by the rx object, this function returns the replacement text adict [match. group (0)], that is, return the value of the key in the dictionary adict.

How to pass an inner function to the outer layer in the python closure function?

Closures are not required to implement this function.

Def fun (callback, * x ):
Return callback (* x)

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.