Talking in Python with (context manager) Usage

An example of a

First look at a piece of code:

class Foo(object):

    DEF  the __init__ (Self):
         Print ( " instantiate an object ' )

    DEF  the __enter__ (Self):
         Print ( ' enter ' )

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')

obj = Foo()

with obj:
    Print ( ' executing ' )

Results of the above code:

Instantiate an object
enter
Being implemented
drop out

Conclusion 1

We know that instantiate Foo, get the object obj, performs Foo's __init__ method, which is printed the first sentence;

According to the program execution from top to bottom, you should print "Progress" instead of asking first before it will print the entry, exit it after printing it?

 

Because when we define Foo, defined __enter__ and __exit__ method, then we instantiate the object obj is a context manager,

I.e. the object containing methods is __exit__ __enter__ and the context manager.

with context manager:
     Statement body

Before encounter with a context manager, will execute the statement in the body, perform __enter__ method context manager, and then execute the statement body after body after executing the statement, the last execution method __exit__

 

This is the reason why there is the case at the beginning of the article.

Examples of the dicarboxylic

Look at this code:

class Foo(object):

    DEF  the __init__ (Self):
         Print ( " instantiate an object ' )

    DEF  the __enter__ (Self):
         Print ( ' enter ' )

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')
     # return True

obj = Foo()

with obj:
    The raise ImportError
     Print ( ' executing ' )

The results are as follows:

 The code above the line that we commented uncommented, the following results

 

 We find that, although we deliberately throw an error, under normal circumstances, to perform local error will not be executed, while __exit__ is performed after seeing the body executing the sentence in the body, but still performed __exit_ _ method; when we give a return value in __exit__ Ture, it will ignore the error.

 

Conclusion 2

All we can find

with a similar statement

  try :

  except:

  finally:

Functionality: But with statements more concise. And safer. Less code.

   When an exception occurs, if __exit__ returns False (the default does not write the return value, that is False), will be re-thrown, let statement outside with logic to handle exceptions, and this is common practice; if it returns True, the ignore the exception, not to deal with exceptions

Examples of three

class Foo(object):

    DEF  the __init__ (Self):
         Print ( " instantiate an object ' )

    def __enter__(self):
        print('进入')
        # return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')


with Foo() as obj:
    Print (obj, of the type (obj))
     Print ( ' executing ' )

The code above the line that we commented uncommented, the following results

in conclusion

When you call __enter__ method context manager; if used as clause will __enter __ () method returns the value assigned to the clause as a target

with context manager as target:
    Code statement body

with must be followed by a context manager, if used as, is the return value of the context manager The __enter __ () method is assigned to target, target may be a single variable, or by a "()" enclosed tuple (it can not be merely a "," separated list of variables, you must add "()")

Examples of four

We often see this code:

with open("/tmp/foo.txt") as file:
    data = file.read()

 in conclusion

Here used with the statement, regardless of whether an exception occurs during the processing file, can ensure that after the implementation of the statement has been closed with the open file handles . If conventional try / finally paradigm will be employed similar to the following code:

somefile = open(r'somefileName')
try:
    for line in somefile:
        print line
        # ...more code
finally:
    somefile.close()

By comparison, with statement can reduce the amount of coding. Support has been added for context management protocol as well as module threading, decimal and so on.

supplement

with only with the context manager uses, there is a common context manager

file
decimal.Context
thread.LockType
threading.Lock
threading.RLock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore

 

Guess you like

Origin www.cnblogs.com/gwklan/p/11140059.html