Python with statements

Source: Internet
Author: User

Python with statements

In Python, when we open a file, for the robustness of the code, we usually consider some exceptions, such as:

Try :     = Open ('/path/data')    = ccfile.readlines ()    ccfile.close () except IOError:    log.write ('no data read\n')

We throw the real work code into the TRY statement block and write an error log if there is an exception to the file operation;

Consider a situation where if the file is opened successfully, but the ReadLines () call fails, the exception handling immediately jumps to except execution, so that the file is closed without a chance to be executed.

One solution is to put the close () statement in the finally clause, and finally the feature is that it will be executed regardless of the exception.

Try :     Try :         = Open ('/path/data')        = ccfile.readlines ()    except  IOError:        log.write ('no data read\n')  Finally    ccfile.close ()

Another alternative style of finally:

Try :     Try :         = Open ('/path/data')        = ccfile.readlines ()    finally  IOError:        ccfile.close ()except  IOError:    log.write (' No data read\n ')

The use of standardized try-except and try-finally as described above is to ensure that resources are allocated and recycled, such as files (data, logs, databases, etc.), thread resources, database connections, and so on, but they are not elegantly written. The purpose of the WITH statement is to remove the try, except, finally keyword, and resource allocation and release related code from the flowchart,

An instance of the with processing file operation:

With open ('/etc/passwd') as F:    for in  f:         Print

The purpose of this code: to open a file, if everything is normal, assign the file object to F, and then use the iterator to traverse each line of the file, when finished, close the file, and no matter where in this code, if an exception occurs, the file will still be closed.

With seems so simple, but there is still some work to do behind it, because you can't use the WITH statement for any of the Python symbols, it works only with objects that support context Management protocol . That is, only objects with the built-in "context management" can work with the, and currently the objects that support the protocol are:

    • File
    • Decimal. Context
    • Thread. LockType
    • Threading. Lock
    • Threading. Rlock
    • Threading. Condition
    • Threading. Semaphore
    • Threading. Boundedsemaphore

Now let's look at the syntax of with:

With Context_expr as Var:    With_suite

When the WITH statement executes, the context expression (context_expr) is executed to obtain a context manager, and the role of the context manager is to provide a context object to handle the details in the WITH statement block:

Once the context object is acquired, its __enter__ () method is called, and all preparations for the WITH statement block are completed, and if the WITH statement follows the AS statement, the return value of the __enter__ () method is used to assign the value;

When the WITH statement block ends, whether it is a normal end, or because of an exception, the __exit__ () method of the context object is called, the __exit__ () method has 3 parameters, and if the With statement ends normally, all three parameters are none; If an exception occurs, The values of the three parameters are equal to the three values returned by the call to the Sys.exc_info () function: Type (Exception Class), value (exception instance), and trace record (Traceback), corresponding to the tracking Record object.

Because the context manager primarily acts on shared resources, the __enter__ () and __exit__ () methods are basically dry, requiring low-level work to allocate and release resources, such as: Database connection, lock assignment, semaphore Plus/minus, state management, File open/Close, exception handling, and so on.

Now we can create the __enter__ () and __exit__ () methods inside the custom class so that we can create the class instance with the WITH statement:

 class   A:  def   print   " __enter__ () called   '  

You can see the output as:

__enter__ () Calledgot instance __exit__ () called

In addition, there is a module contextlib in the Python library, so that you do not have to construct a class containing __enter__, __exit__ can use with:

 from __future__ Importwith_statement fromContextlibImportContextManager @contextmanagerdefcontext ():Print 'Entering the zone'    Try:        yield    exceptException, E:Print 'With an error%s'%eRaiseeElse:      Print 'With no error'With context ():Print '----in context call------' 

Reference Documentation:

http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/

Python with statements

Related Article

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.