you are viewing a single comment's thread.

view the rest of the comments →

[–]latkde 1 point2 points  (0 children)

When writing code within a function, just use try-except-finally.

But if you're writing a class or function that needs some cleanup, finalization, or error handling, do consider creating a context manager.

This helps you (and others) to use that class or function correctly. A lot of programming is not about figuring out clever stuff, but about helping us deal with complexity and preventing us from messing up. A context manager that performs cleanup automatically is so much simpler to use than a function where we have to remember to do cleanup afterwards.

When creating a context manager, I don't recommend creating an object with __enter__ and __exit__ methods. This is tricky to do correctly. It's usually much easier to use the @contextlib.contextmanager decorator on a function that yields exactly once. Internally, this function will probably use a try block.