Python advanced with syntax

Source: Internet
Author: User
Tags generator generator throw exception

One: Cause

(0) The basic syntax of Python is easier for a person who has learned other languages, but there is still a way to get a good command of Python's advanced syntax.

(1) The WITH statement replaces the try......finally statement; Yield syntax generator generator, sequence generator, functional programming (Map/reduce/filter, PS: map/reduce here is not the Mr of Hadoop)

(3) For example, see

Two: with basic syntax

(0) to speak with the syntax, first of all talk about context Manager

For example, when you write Python code, you often put a series of actions in a block of statements:

When a condition is true – execute this block of statements; When a condition is true – the loop executes this block of statements; sometimes we need to keep a state when the program is running in a block of statements and end it after leaving the statement block.

So, in fact, the task of the context manager is-to prepare the code block before execution, and to clean up after the code block executes.

Look at the code is the best way to learn, to see how we usually open a file and write "Hello world"?

filename = ' my_file.txt ' mode = ' W ' # mode, allows to write to the FileWriter = open (filename, mode) writer.write (' Hello ') Writer.write (' World ') writer.close ()

1-2 lines, we indicate the file name and open mode (write).

Line 3rd, open the file, 4-5 lines write "Hello World", line 6th closes the file.

That's fine, why do you need a context manager? But we overlooked a small but important detail: What if we didn't get a chance to close the file on line 6th?

For example, the disk is full, so we throw an exception when we try to write to the file on line 4th, and line 6th does not have a chance to execute at all.

Of course, we can use the try-finally statement block to wrap:
writer = open (filename, mode) Try:    writer.write (' hello ')    writer.write (' World ') finally:    Writer.close ()

The code in the finally statement block executes regardless of what happens in the try statement block. Therefore, the file must be closed. What's the problem with this? Of course not, but when we do something more complicated than writing "Hello World"

Things, try-finally statements become ugly. For example, to open two files, one to read and one to write, and two to copy between files, the With statement ensures that both can be closed at the same time.

(1) The syntax format of the WITH statement is as follows:

With Context_expression [as Target (s)]:        with-body
here context_expression to return a context manager object, which is not assigned to target (s) in the AS clause, and if an AS clause is specified, returns the __enter__ () method of the context manager .

The return value is assigned to target (s). Target (s) can be a single variable, or a tuple enclosed by "()" (cannot be a list of variables separated by only "," and "()" must be added).

(2) Python has improved some of the built-in objects by adding support for the context manager, which can be used in the WITH statement, such as the ability to automatically close files, automatically fetch and release the lock, and so on. Suppose you want to do a file

Operation, using the WITH statement can have the following code: Manipulate the file object with the WITH statement

With open (R ' Somefilename ') as Somefile: For line in        somefile:            print line            # ... more code
The WITH statement is used here to ensure that the open file handle has been closed after execution of the WITH statement, regardless of whether an exception occurred during the processing of the file.

(3) If you are using the traditional try/finally paradigm, use a code similar to the following: (For comparison with the with)

Somefile = open (R ' somefilename ')    try: For line in        somefile:            print line            # ... more code    finally:        Somefile.close ()

By comparison, using the WITH statement can reduce the amount of coding. There are also modules threading, decimal, etc. that have been added to the context management protocol.

Three: Example Description

(1) the WITH statement executes in a code block similar to the following:

    Context_manager = context_expression    exit = Type (Context_manager). __exit__      value = Type (Context_manager). __ enter__ (context_manager)    exc = True   # True indicates normal execution, even if an exception is omitted; False indicates a re-throw exception, need to process the exception    try:        try            : target = value  # If the AS clause            is used with-body     # executes with-body        except:            # An exception occurred during execution            exc = False            # if __exit__ returns TRUE, the exception is ignored, and if False is returned, the exception will be re-thrown            by the outer code if not            exit (Context_manager, *sys.exc_info ()):                Raise    finally:        # Normal Exit, or exit # via Break/continue/return statement in Statement-body        or ignore exception exit        if exc:< C22/>exit (Context_manager, none, none, none)         # Default return none,none is considered False in Boolean context
Executes the context_expression, generating the context manager Context_manager

Invokes the __enter__ () method of the context manager and assigns the return value of the __enter__ () method to the target (s) in the AS clause if an AS clause is used

Execute Statement Body With-body

Execution of the __exit__ () method of the context manager, regardless of whether an exception occurred during execution or not, the __exit__ () method is responsible for performing "cleanup" work, such as freeing resources. If no exception occurs during execution, or if statement Break/continue/return is executed in the body of the statement, call __exit__ (none, none, none) as a parameter with none, or use SYS.EXC_ if an exception occurs during execution. Info gets exception information for parameter call __exit__ (Exc_type, Exc_value, Exc_traceback)

When an exception occurs, if __exit__ (type, value, Traceback) returns FALSE, the exception is re-thrown, allowing statement logic outside of with to handle the exception, which is also a common practice, and if True, ignores the exception and no longer handles the exception

(2) In addition, there is a module contextlib in the Python library, so that you can use with: (more practical) without having to construct a class containing __enter__, __exit__.

>>> from contextlib import contextmanager>>> from __future__ import with_statement>>> @ ContextManager ... def context ():     ... print ' Entering the zone '     ... Try:         ... Yield ...     Except Exception, E: ...         print ' with ' Error%s '%e         ... Raise e ...     else:         ... print ' with no error ' ...>>> with context (): ...     print '----in context call------' ... entering the zone----in the context of the call------with no error

(3) @property can access a Python-defined function as a property, providing a more friendly way to access it, but sometimes setter/getter is needed.

Class Parrot:    def __init__ (self):        self._voltage = 100000    @property    def voltage (self):        "" "Get the Current voltage.        "" " return Self._voltageif __name__ = = "__main__":    # instance    p = Parrot ()    # similarly invoke "getter" via @proper Ty    print p.voltage    # Update, similarly invoke "setter"    P.voltage = 12


Python advanced with syntax

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.