Usage in python with, the context manager

First look at a piece of code:

Copy the code
class Foo (Object): 

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

    DEF The __enter __ (Self): 
        Print (' enter ') 

DEF The __exit __ (Self, exc_type, exc_val, exc_tb): Print (' exit ' ) obj = Foo () with obj: Print ( 'executing')
Copy the code

 

Results of the above code:

Instantiate an object 
into the 
executing 
exit

 

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.

 

Look at this code:

Copy the code
class Foo (Object): 

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

    DEF The __enter __ (Self): 
        Print (' enter ') 

    DEF The __exit __ (Self, exc_type, exc_val, exc_tb): 
        Print (' exit ' ) 
     # return True obj = Foo () with obj: The raise ImportError Print ( 'executing')
Copy the code

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 when to return a value Ture __exit__, 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

 
Copy the code
class Foo (Object): 

    DEF the __init __ (Self): 
        Print ( 'instantiate an object') 

    DEF The __enter __ (Self): 
        Print ( 'enter') 
        # return Self 

    DEF The __exit __ (Self, exc_type, exc_val, exc_tb): 
        Print ( 'exit') 


with Foo () AS obj: 
    Print (obj, of the type (obj)) 
    Print ( 'executing')
Copy the code

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 "()")

 

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:

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

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.

 

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

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


转载:https://www.cnblogs.com/huchong/p/8268765.html

Guess you like

Origin www.cnblogs.com/coxiseed/p/11619419.html