'with' statement in python ?

Carlos Ribeiro cribeiro at mail.inet.com.br
Tue Jun 26 09:41:31 EDT 2001


At 11:49 26/06/01 +0000, Maciej Pilichowski wrote:
>I have just started learning Python yesterday but...
>
> >def with_is_broken(a):
> >   with a:
> >     print x
> >
> >The snippet above assume that "a" must have a member attribute called "x".
>
>Nope. As you referred to Pascal -- if "a" has a member "x" it is read
>as "a.x", if not it is standalone "x".

There must be some misunderstanding here. My snippet (incomplete, as I 
pointed out) assumed that Python had a "with" keyword, just to show the 
kind of problems that arise. In Python, the compiler/interpreter has no way 
to tell beforehand if x is a member of a, a local variable, a module level 
variable, or a global variable. This ambiguity makes the use of with in 
Python impossible.

Now, let us take a look at the "with" block in Pascal:

   with a do
     writeln(x);

The compiler knows in advance everything about "a". If "a" does define a 
member called "x", then writeln() will reference "a.x". If "x" is not a 
member of "a", then the compiler will recursively search on the outer 
namespaces until it finds a definition for "x". If it does not find, it 
will stop - it is a fatal error, caught at compile time.



Carlos Ribeiro






More information about the Python-list mailing list