'with' statement in python ?
dsh8290 at rit.edu
Tue Jun 26 19:45:34 CEST 2001
On Tue, Jun 26, 2001 at 10:41:31AM -0300, Carlos Ribeiro wrote:
| 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.
It's not impossible, it would just be a runtime determination.
Already for bare names python looks in locals(), then up through the
nested scopes (if enabled) and in globals() and __builtin__. It
_could_ do the same for instances in the presence of a 'with'
After stating that it _could_ be implemented, I think it is a BAD idea
because it is just some more magic and can make it really hard to
trace through how the code will act. Normally trying to access a
member of an instance that doesn't exist is an error and should raise
AttributeError. If this sort of Pascal-ish magic is used then more
obscure bugs can be introduced. It also makes it hard to tell (like
in C++ and Java) whether a variable is local, global, "static", or a
part of this instance.
| 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.
This isn't quite as bad as it would be with Python because it is a
More information about the Python-list