I am reading the Python Cookbook where the following is mentioned:
@contextmanager
is really only used for writing self-contained context-management functions. If you have some object (e.g. a file, network connection, or lock) that needs to support thewith
statement, you still need to implement the__enter
and__exit__
methods separately.
I can't quite understand this. Why can't we use a file object with a context-management function? Aren't functions decorated with @contextmanager
equivalent to classes with __enter__
and __exit__
methods?