π Context Managers
A context manager is used to manage resources automatically, such as files, database connections, or network connections.
The most common way to use one is with the with statement.
π Using with
Instead of manually opening and closing a file:
file = open("data.txt", "r")
content = file.read()
file.close()We can use a context manager:
with open("data.txt", "r") as file:
content = file.read()Python automatically closes the file when the with block finishes.
πΉ Creating a Context Manager
A class can act as a context manager using:
__enter__()
__exit__()Example:
class MyContext:
def __enter__(self):
print("Entering")
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting")
with MyContext():
print("Inside")Entering
Inside
ExitingHere:
__enter__() β Runs when entering the with block
__exit__() β Runs when leaving the with blockwith β Setup β Use β Cleanup automatically π