loop scope

Jacek Generowicz jacek.generowicz at cern.ch
Mon Mar 15 09:32:31 EST 2004


Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:

> Is it (entirely) correct to say that class opens a new scope? I don't
> think so,

>>> class foo:
...     a = 3
...     def bar(self):
...         print a
... 
>>> f = foo()
>>> f.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in bar
NameError: global name 'a' is not defined

Bleargh! You are right. Now that you bring it up, I recall bumping up
against it before.

> since names bound within the class body become attributes of the
> class object, they are not local variables -- you can reach them
> from the outside.

That in itself does not prevent "class" from introducing a scope. It
just means that there are ways of getting at things in that scope
... just like here:

def foo():
    a = [3]
    def show():
        print a[0]
    def inc(n):
        a[0] += n
    return show, inc      

show, inc = foo()
show() # prints 3
inc(2)
show() # prints 5

"a" is definitely in the scope introduced by "foo", but you can reach
it from the outside.

> There were discussions about this in in the python dev list. The only
> proposal that stuck in my memory was an extension of the global
> keyword where you had an option of specifying the scope, something
> like:
> 
> def g(*args):
> 
>     x = None
> 
>     def f(*args):
>         global x in g

Hmmm ... the explicit naming of the scope sort of piddles all over the
elegance of nested scopes. But maybe the generality of being able to
specify *any* enclosing scope has some applications, though none come
to mind immediately.

OTOH:

   def g():
       x = None
       def g():
           x = None
           def g():
              global x in g

Just *which* g are we talking about ?

Let's just stick to finding the innermost binding of the name :-)

Of course, the name "global" is completely inappropriate, but I guess
they're trying to avoid a new keyword.



More information about the Python-list mailing list