Context Manager

Introduction

  • A Python context manager is a tool used to manage resources efficiently, ensuring proper setup and teardown of actions. The with statement is commonly used with context managers to define a block of code where resources are acquired, used, and then released automatically. such as client session, file resource

...
# open a context manager
with ContextManager() as manager:
	# ...
# closed automatically
  • The above code which equal to

...
# create the object
manager = ContextManager()
try:
	manager.__enter__()
	# ...
finally:
	manager.__exit__()
  • __enter__ and __exit__ methods are standard method to let you declare your customization logic when setting up and closing of your context manager class

Example

  • Output

References

Last updated