The Python contextlib module USES examples

  • 2020-04-02 14:36:00
  • OfStack

The most common way to look at this module is to open a file:


with open( " filename " ) as f:
f.read()

With can invoke a context manager to produce a runtime context. The context manager mainly defines two methods, s/s and s/s. S/s return the object operated on within the context, such as f. S/s s/s are the destroy object and exception handling.

The contextlib module has three external interfaces,
Contextmanager decorator, the decorator function must be a generator. Then returns a function, which returns a context manager when the function is called.

To invoke multiple context managers at once, put all of the context managers' s s into vars, yield return once, and then unpack. You have multiple objects. __exit__ put all the exits in the list, in the finally unified call, these __exit__ resulting from a manager in the calling context, how to deal with. If false is returned, the exception will continue to be thrown, and if true is returned, the exception will not be thrown.

Closing, which I've used before, turns out to be a class, not a function. This is to turn an object with a close method but no/s method into a context manager. The code is simple:


class closing(object):
    def __init__(self, thing):
        self.thing = thing
    def __enter__(self):
        return self.thing
    def __exit__(self, *exc_info):
        self.thing.close()


Related articles: