python: ‘with’ statement

With python2.5 comes ‘with’ statement.

To use it, first you need to import it: ‘from __future__ import with_statement’

It’s usage is pretty simple:
with “expr” as “myname”:
do something

– “myname” is a variable name in which the result of “expr”.__enter__() will be stored
– “expr” must be a context expression, i.e. an object which implements both __enter__() and __exit__() method

‘With’ statement has primarily being developped to reduce overhead of length try-except-else-finally statements.
If an exception is raised within the ‘with’ loop, then __exit__() method is called with corresponding (type, msg, traceback) objects.
=> instead of repeatedly writing the same try-except… code, simply wrap it into a class (more precisely into __exit__() method of this class) and use the with statement. If __exit__() return True, then exception is considered handled.

[Example reading a file content]

since python2.5, file objects implement such methods and therefore can be used with a ‘with’ statement:
ex from :

[whithout ‘with’]

fileIN = open(sys.argv[1], “r”)
line = fileIN.readline()
while line:
[some bit of analysis here]
line = fileIN.readline()

[with ‘with’]

from __future__ import with_statement
with open(sys.argv[1], “r”) as fileIN:
for line in fileIN:
[some bit of analysis here]


  • describe usage of ‘with’ regarding exceptions management

Post a Comment

Your email is never published nor shared. You're allow to say what you want...