with open(secret_file) as eyes_only: read_discreetly(eyes_only)
The point behind this is that if you opened a secret file, you do not need to make it 💥 explicitly.
Here’s the same implementation without a context manager:
eyes_only = open(secret_file) try: read_discreetly(eyes_only) finally: eyes_only.destroy()
Notice that here you MUST NOT forget to 💥 after reading said secret file.
A class can become a context manager just by implementing these:
with Freezer() as icebox: look_for('yummy treats')
class Freezer(): def __enter__(self) -> self: open_door() return self def __exit__(self, ex_type, ex_value, ex_traceback) -> self: close_door()
- The Freezer’s door opens for you automatically
- You look for yummy treats…
- The Freezer’s door closes for you automatically
The mechanism that makes this happen: