'with' statement in python ?

Carlos Ribeiro cribeiro at mail.inet.com.br
Mon Jun 25 20:30:36 EDT 2001


At 21:50 25/06/01 +0000, Mark Hadfield wrote:
>From: "asgard" <asgard at hellnet.cz>
>
>
> > Hello,
> > writing self before every object's method really drives me
> > crazy. Shouldn't there be 'with' statement like in Pascal, ie.
>
>There was an extensive discussion on this recently. Perhaps you'd like to
>try a search on Google Groups. IIRC the consensus was that adding this to
>Python would not be a good idea, because when "with" blocks are nested they
>become hard to read and possibly ambiguous.

I'll repeat the same argument that I gave some time ago. Maybe it's a good 
answer for this FAQ :-)

Some languages, such as Object Pascal, Delphi, and C++, use static types. 
So it is possible to know, in a 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 snippet (it is incomplete btw, just to 
give you the idea):

def with_is_broken(a):
   with a:
     print x

The snippet above assume 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.


Carlos Ribeiro






More information about the Python-list mailing list