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.

How

A class can become a context manager just by implementing these:

  • __enter__()
  • __exit__()

Example:

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()
  1. The Freezer’s door opens for you automatically
  2. You look for yummy treats…
  3. The Freezer’s door closes for you automatically

The mechanism that makes this happen: