Context manager for Python deep learning,

Source: Internet
Author: User

Context manager for Python deep learning,

Context manager is a syntax supported by Python2.5 and is used to specify the scope of use of an object. Once you enter or exit the scope of use, special operations will be called (such as allocating or releasing memory for objects ). Its Syntax format is with......

Close file

We will do this: open the file, read/write, and close the file. Programmers often forget to close files. The context manager can automatically close files when they are not needed.

Let's take a look at the two procedures below:
Copy codeThe Code is as follows:
# Without context manager
F = open ("new.txt", "w ")
Print (f. closed) # whether the file is open
F. write ("Hello World! ")
F. close ()
Print (f. closed)

And:
Copy codeThe Code is as follows:
# With context manager
With open ("new.txt", "w") as f:
Print (f. closed)
F. write ("Hello World! ")
Print (f. closed)

The two programs actually perform the same operation. Our second program uses the context Manager (with... ...). The context manager has a program block that belongs to it. When the execution of the program block ends (that is, it is no longer indented), the context Manager Automatically closes the file (we use f. closed to check whether the file is closed ). We use indentation to specify the scope of use of object f.

The preceding context manager is based on the _ exit _ () special method of the f object (remember how we use special methods to implement various syntaxes? See Special Methods and multi-paradigm ). When we use the context manager syntax, we actually require Python to call the _ enter _ () method of the object before entering the program block, call the _ exit _ () method at the end of the block. For file object f, it defines the _ enter _ () and _ exit _ () methods (which can be seen through dir (f ). In the _ exit _ () method of f, There is a self. close () statement. Therefore, when using the context manager, we do not need to close the f file in plain text.

Custom

Any object that defines the _ enter _ () and _ exit _ () methods can be used in the context manager. File object f is a built-in object, so f automatically carries these two special methods and does not need to be customized.

In the following example, the custom object for the context manager is myvow:
Copy codeThe Code is as follows:
# Customized object

Class VOW (object ):
Def _ init _ (self, text ):
Self. text = text
Def _ enter _ (self ):
Self. text = "I say:" + self. text # add prefix
Return self # note: return an object
Def _ exit _ (self, exc_type, exc_value, traceback ):
Self. text = self. text + "! "# Add suffix


With VOW ("I'm fine") as myvow:
Print (myvow. text)

Print (myvow. text)

The running result is as follows:

Copy codeThe Code is as follows:
I say: I'm fine
I say: I'm fine!

We can see that the text attribute of the object is changed when the context is entered and the context is left (the original text attribute is "I'm fine ").

_ Enter _ () returns an object. The context Manager uses this object as the variable referred to by as, that is, myvow. In _ enter _ (), we add a prefix ("I say:") for myvow. text :"). In _ exit _ (), we added a suffix ("! ").

Note: There are four parameters in _ exit. When an exception (exception) ,__ exit _ () occurs in the block, exc_type, exc_value, and traceback are used to describe the exception. We can process these three parameters accordingly. If normal operation ends, all three parameters are None. This feature is not used in our programs.

Summary:

Through the context manager, we control the features of objects in different intervals of the program. The context Manager (with EXPR as VAR) is roughly equivalent to the following process:

Copy codeThe Code is as follows:
# With EXPR as VAR:

VAR = EXPR
VAR = VAR. _ enter __()
Try:
BLOCK
Finally:
VAR. _ exit __()

Because of the convenience brought by the context manager, it is a tool worth using.




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.