Learn Python Programming, Third edition by Fabrizio Romano Heinrich Kruger

Learn Python Programming, Third edition by Fabrizio Romano Heinrich Kruger

Author:Fabrizio Romano, Heinrich Kruger
Language: eng
Format: epub
Tags: COM051010 - COMPUTERS / Programming Languages / General, COM051230 - COMPUTERS / Software Development & Engineering / General, COM051360 - COMPUTERS / Programming Languages / Python
Publisher: Packt
Published: 2021-10-27T14:23:32+00:00


The output from running this is very similar to the previous example:

$ python context/generator.py About to enter 'with' context Entering 'with' context 139768531985040 Inside 'with' context 139768531985040 type(e)=<class 'Exception'> e=Exception("Exception inside 'with' context") e.__traceback__=<traceback object at 0x7f1e65a42800> Exiting 'with' context After 'with' context

Most context manager generators have a similar structure to my_context_manager() in this example. They have some setup code, followed by a yield statement inside a try statement. Here, we yielded an arbitrary object, so that you can see that the same object is made available via the as clause of the with statement. It is also quite common to have just a bare yield with no value (in which case None is yielded). In such cases, the as clause of the with statement will typically be omitted.

One very useful feature of generator-based context managers is that they can also be used as function decorators. This means that if the entire body of a function needs to be inside a with statement context, you could save a level of indentation and just decorate the function instead.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.