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 with statement. It takes care of the notifying.
For example, file objects are context managers. When a context ends, the file object is closed automatically:
open_file = ...
Many context managers return an object when entered. You can assign that object to a new name in the with statement.
For example, using a database connection in a with statement could give you a cursor object:
with database_connection as cursor:
cursor.execute(sql_query)
File objects retur...
A context manager is any object that implements two magic methods __enter__() and __exit__() (although it can implement other methods as well):
class AContextManager():
def __enter__(self):
print("Entered")
# optionally return an object
return "A-ins...
It is also possible to write a context manager using generator syntax thanks to the contextlib.contextmanager decorator:
import contextlib
@contextlib.contextmanager
def context_manager(num):
print('Enter')
yield num + 1
print('Exit')
with context_manager(2) as cm:
# the ...
You can open several content managers at the same time:
with open(input_path) as input_file, open(output_path, 'w') as output_file:
# do something with both files.
# e.g. copy the contents of input_file into output_file
for line in input_file:
output_file.write(line...