| Start |
|---|
| Introduction to context managers and the with statement A context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the For example, file objects are context managers. When a context ends, the file object is closed automatically: The above example is usually simplified by using the Anything that ends execution of the block causes the context manager's exit method to be called. This includes exceptions, and can be useful when an error causes you to prematurely exit from an open file or connection. Exiting a script without properly closing files/connections is a bad idea, that may cause data loss or other problems. By using a context manager you can ensure that precautions are always taken to prevent damage or loss in this way. This feature was added in Python 2.5. |
| Writing your own context manager A context manager is any object that implements two magic methods If the context exits with an exception, the information about that exception will be passed as a triple If an exception occurs and is passed to the Note that in the second example even though an exception occurs in the middle of the body of the with-statement, the If you only need an |
| Writing your own contextmanager using generator syntax It is also possible to write a context manager using generator syntax thanks to the produces: The decorator simplifies the task of writing a context manager by converting a generator into one. Everything before the yield expression becomes the If an exception needs to be handled by the context manager, a This produces: |
| Multiple context managers You can open several content managers at the same time: It has the same effect as nesting context managers: |
| Assigning to a target Many context managers return an object when entered. You can assign that object to a new name in the For example, using a database connection in a File objects return themselves, this makes it possible to both open the file object and use it as a context manager in one expression: |
Manage Resources
Using these magic methods ( Use File class: Syntax
RemarksContext managers are defined in PEP 343 (opens new window). They are intended to be used as more succinct mechanism for resource management than In this PEP, context managers provide It then goes on to define the The translation of the above statement is: |
Read Article
https://develop.horje.com/learn/1434/reference