(An Unofficial) Python FAQ Wiki

putting the community back in "maintained by the community"

Why doesn't Python have a "with" statement like some other languages?

Because such a construct would be ambiguous.

Some languages, such as Object Pascal, Delphi, and C++, use static types. So it is possible to know, in an unambiguous way, what member is being assigned in a "with" clause. This is the main point - the compiler always knows the scope of every variable at compile time.

Python uses dynamic types. It is impossible to know in advance which attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This would make it impossible to know, from a simple reading, what attribute is being referenced - a local one, a global one, or a member attribute.

For instance, take the following incomplete snippet:

def foo(a):
   with a:
      print x

The snippet assumes that "a" must have a member attribute called "x". However, there is nothing in Python that guarantees that. What should happen if "a" is, let us say, an integer? And if I have a global variable named "x", will it end up being used inside the with block? As you see, the dynamic nature of Python makes such choices much harder.

The primary benefit of "with" and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of:

function(args).dict[index][index].a = 21
function(args).dict[index][index].b = 42
function(args).dict[index][index].c = 63

write this:

ref = function(args).dict[index][index]
ref.a = 21
ref.b = 42
ref.c = 63

This also has the side-effect of increasing execution speed because name bindings are resolved at run-time in Python, and the second version only needs to perform the resolution once. If the referenced object does not have a, b and c attributes, of course, the end result is still a run-time exception.

CATEGORY: general

Comments

Note to add: The 'with' statement added in Python 2.5 is completely different from the 'with' statement in Pascal. (Add brief explanation here.)