Context without manager

Dieter Maurer dieter at handshake.de
Sun Nov 26 12:50:38 EST 2023


Piergiorgio Sartor wrote at 2023-11-25 22:15 +0100:
> ...
>Apparently, the "with" context manager is not usable
>in classes, at least not with __init__() & co.

You can use `with` in classes -- with any context manager.
However, you would usually not use `with` with a file you have opened
in `__init__`.

If a class defines `__enter__` and `__exit__` (i.e.
the "cntext manager protocol"), then its instances
can be used with the `with` statement.

The important use case for a context manager is the
situation:
	set up a context (--> method `__enter__`)
	perform some operations in this context (--> body of `with` statement)
	tear down the context (--> method `__exit__`).
If you do not have this case (e.g. usually if you open the file
in a class's `__init__`), you do not use a context manager.


More information about the Python-list mailing list