lists of variables

Carl Banks pavlovevidence at gmail.com
Sun Feb 21 02:44:29 EST 2010


On Feb 20, 10:50 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sat, 20 Feb 2010 22:31:44 -0800, Carl Banks wrote:
> > The one place where Python does have references is when accessing
> > variables in an enclosing scope (not counting module-level).  
>
> What makes you say that?
>
> > But these
> > references aren't objects, so you can't store them in a list, so it
> > can't help you:
>
> I don't even understand this. Your own example clearly shows that the are
> objects and you can store them in a list, so I have no understanding of
> what you mean.
>
> > def f():
> >     s = []
> >     a = 1
> >     def g():
> >         print a
>
> a is a name bound to an object which inherits a __str__ method, hence you
> can print it.
>
> >         s.append(a)
>
> a is bound to an object you can put in a list.
>
> >     g() # prints 1
> >     a = 2
> >     g() # prints 2: g's a is a reference to f's a
> >     print s # prints [1,2] not [2,2]
>
> Yes, you are correct that lexical scoping doesn't allow the OP to embed
> references to names in lists. I'm just confused why you think that
> lexical scoping is equivalent to references that can't be put in lists,
> or why you think this behaviour is any different from lexical scoping
> everywhere else?
>
> # Instead of two scopes, f and g, use two scopes, the module (global)
> # and local scope g:
> s = []
> a = 1
> def g():
>     print a
>     s.append(a)
>
> g() # prints 1
> a = 2
> g() # prints 2: g's a is a reference to the global a
> print s # prints [1,2] not [2,2]
>
> There is no difference between lexical scoping between a function and a
> nested function, and the lexical scoping between the global namespace and
> a nested function.


http://tinyurl.com/8e7tm



Carl Banks



More information about the Python-list mailing list