Python: "with" statement

with EXPRESSION [as VARIABLE]:
    BLOCK OF CODE

The with statement always calls two methods on the EXPRESSION, regardless of what happens inside the BLOCK OF CODE:

  1. __enter__() method - before method is run
  2. __exit__() method - after method is run

 

This is useful when you want to ensure that there is a clean-up even when an exception is raised.

For example:

with open("testfile.txt", "r") as outputFile:
    outputFile.write("with example test")

In this case, the with statement automatically closes the file, even if an exception is raised.

Based on the examples given by Jesse Noller, here is an example of the usage of the "with" statement:

# Python "with" statement
class WithExample(object):
	def __init__(self):
		pass
	
	# the __enter__ method cannot accept any arguments, but can perform actions or return data
	def __enter__(self):
		print("__enter__ method")
		self.sayHello = "Hello"

	# the __exit__ method must accept the arguments type, value and traceback (agruments in "raise" statement)
	def __exit__(self, type, value, traceback):
		print("__exit__ method\n")

with WithExample():
	print("With example")
		
with WithExample():
	raise Exception

Sources:

  • Jesse Noller
  • PEP 343
  • Preshing on programming