python notes: with and context manager

The with statement is a simplified syntax provided by Pyhton. It is suitable for accessing resources. It ensures that necessary "cleaning" operations are performed and resources are released regardless of whether an exception occurs during use. The with statement is mainly used to simplify code operations.

context manager

  • Context is the literal translation of context, which is used in programs to represent the surrounding environment during code execution.
  • Any object that implements __enter__() and __exit__() is a context manager
  • Above: Operations before normal code execution; Below: Operations after normal code execution, such as exceptions or end/close code
  • The context manager can use the with keyword to ensure that the file can be closed, which is an alternative to try/finally
class Foo(object):

    def __init__(self):
        print('实例化一个对象')

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

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

obj = Foo()

with obj:
    print('正在执行')

Instantiate an object
Enter
Executing
Exit

Because when we defined Foo, we defined the __enter__ and __exit__ methods, then the object obj we instantiated is a context manager

with context manager:
 statement body

When with encounters a context manager, it will execute the context manager's __enter__ method before executing the statement body. It is generally used to process pre-operation content, such as object creation, initialization, etc.; and then execute the statement body. After executing the statement body, the __exit__ method is finally executed, which is generally used to handle some finishing work, such as closing files, closing databases, etc. The overall process is as follows:.

  1. Call the enter method to perform preprocessing operations
    2. Perform user operations
    3. Call the exit method to complete the cleanup operation

2. When calling the __enter__ () method of the context manager; if the as clause is used, the return value of the __enter__() method is assigned to the target in the as clause.

with context manager as target:
code statement body

class Foo(object):

    def __init__(self):
        print('实例化一个对象')

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

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

with Foo() as obj:
    print(obj,type(obj))
    print('正在执行')

Insert image description here
Uncomment the line of code we commented out in the above code. The result is as follows: with
Insert image description here
must be followed by a context manager. If as is used, the return value of the enter () method of the context manager is assigned to the target. Target can Is a single variable, or a tuple enclosed by "()" (it cannot be a list of variables separated only by ",", "()" must be added)

with and exception handling

with语句类似以下功能
  try :
		语句体
  except:
		exit()
  finally:
  	其它

The with statement will pass the exception type, value and traceback to the __exit__ method, allowing the __exit__ method to handle the exception. When an exception occurs, if exit returns False (the default is False when the return value is not written), the exception will be re-thrown and the statement logic other than with will handle the exception. This is also a common practice; if it returns True, it is ignored Exception, the exception will no longer be handled and the subsequent code will continue to be executed.

class Foo(object):

    def __init__(self):
        print('实例化一个对象')

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

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

obj = Foo()

with obj:
    raise ImportError
    print('正在执行')

The result is as follows:
Insert image description here
Uncomment the line of code we commented out in the above code, the result is as follows:
Insert image description here

A common way to read files:

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

  1. When executing the with statement, the open code following the with statement is first executed.
  2. After the code is executed, the result of the code will be saved to f through as [return value of the enter method]
  3. Then implement the actual operation below
  4. After the operation, there is no need to write the file closing operation. The file will be automatically closed after use [exit method execution]

The with statement is used here. Regardless of whether an exception occurs during file processing, it is guaranteed that the open file handle has been closed after the with statement is executed . If you use the traditional try/finally paradigm, you would use code similar to the following:

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

In comparison, using the with statement can reduce the amount of coding.

other:

with can only be used with context managers. Common context managers include

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

Reference links:
1.https://www.cnblogs.com/huchong/p/8268765.html

Guess you like

Origin blog.csdn.net/qq_44804542/article/details/115980557