[Python-bugs-list] [ python-Bugs-505315 ] free vars sometimes show up in locals()

noreply@sourceforge.net noreply@sourceforge.net
Fri, 18 Jan 2002 05:48:02 -0800


Bugs item #505315, was opened at 2002-01-18 02:14
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=505315&group_id=5470

Category: Python Interpreter Core
Group: Python 2.2
Status: Open
Resolution: None
Priority: 5
Submitted By: Cesar Douady (douady)
>Assigned to: Jeremy Hylton (jhylton)
Summary: free vars sometimes show up in locals()

Initial Comment:
Python 2.2 under Linux.

Whether free variables are part of the local dictionary
or not is
unclear from the doc, but certainly the following
description is buggy:

> in :
>
> def foo():
>     x=1
>     def bar():
>         x
>         print locals()
>     bar()
> foo()
>
> the result is "{}", indicating that x is not in
locals(). But in :
>
> def foo():
>     x=1
>     def bar():
>         x
>         y=1
>         print locals()
>     bar()
> foo()
>
> the result is "{'y':1, 'x':1}", indicating that the
presence of y has
> made x part of locals().

The above is supported by Michael Hudson and he
suggested to assign this
bug report to Jeremy.

Also in :

def foo():
    x=1
    class bar:
        x
        y=1
    print dir(bar)
foo()

the result is "['__doc__', '__module__', 'y']", showing
that x was not
included.

This means that the local dictionary for a class (which
is supposed to
make up the class dictionary) and for a function is not
the same if free
variables are ever to be considered as part of the
local dictionary.

Looking at the interpreter code, the problem lies in
PyFrame_FastToLocals() (Objects/frameobject.c:406)
where there is a test
for (f->f_nlocals == NULL) which prevents free and cell
variables from
being transfered.
It is unclear whether this is an optimization fossile
from before nested
scopes or whether this is done on purpose to
differenciate the behavior
between functions (which almost always have locals) and
classes (for
which nlocals is 0 when PyFrame_FastToLocals is called).

In my opinion, the test should be suppressed and cell
variables should not be transfered to the local dict,
but this breaks the current test suite (in particular
test_scope).

----------------------------------------------------------------------

>Comment By: Cesar Douady (douady)
Date: 2002-01-18 05:48

Message:
Logged In: YES 
user_id=428521

I made a typo in the last paragraph.
I actually meant cell variables should always be transfered
to the local dict while free variables should not.

----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=505315&group_id=5470