Python with Keyword
Example
Use with
to manage a resource via a context manager:
import contextlib
with contextlib.nullcontext("resource") as r:
print("Using", r)
Try it Yourself »
Definition and Usage
The with
keyword wraps a block of code using a context manager.
It ensures setup and cleanup logic (__enter__
/ __exit__
) happen automatically, simplifying resource management and exception handling.
More Examples
Example
Create and use a custom context manager class:
class MyCtx:
def __enter__(self):
print("Enter")
return "res"
def __exit__(self, exc_type, exc, tb):
print("Exit")
with MyCtx() as res:
print("Using", res)
Try it Yourself »
Example
Use multiple context managers in one statement:
import contextlib
with contextlib.nullcontext("A") as a, contextlib.nullcontext("B") as b:
print(a, b)
Try it Yourself »