- Python supports simple context management in the standard library (
contextlibmodule) - The module dictates that, two magic methods should be present
__enter__- The interpreter invokes the object's
__enter__method before thewithstatement's suite starts.
- The interpreter invokes the object's
__exit__- The interpreter always invokes the object's
__exit__method after thewithstatement suite ends.
- The interpreter always invokes the object's
- If we create a class with the above two magic method we can safely say it conforms to the context management protocol.
- We can also use
__init__magic method into the above combination.__init__is executed even before__enter__.- Defining
__init__is not mandatory in the context management protocol.
with open('todos.txt') as tasks:
for chore in tasks:
print(chore, end="")__init__is invoked as soon as the interpreter see thewithstatement.__enter__is invoked soon after the__init__is invoked.__exit__is invoked at the end of thewithstatement.__exit__take's few extra parameter to inform about wrong full termination ofwithstatement.
- Flask has an internal configuration called
app.configwhich is a dictionary.