[Python-Dev] terminology for "free variables" in Python

Nick Coghlan ncoghlan at gmail.com
Fri Sep 10 00:08:44 CEST 2010

On Fri, Sep 10, 2010 at 2:43 AM, Eli Bendersky <eliben at gmail.com> wrote:
> def some_func(myparam):
>     def internalfunc():
>         return cc * myparam
> CPython infers that in 'internalfunc', while 'myparam' is free, 'cc' is
> global because 'cc' isn't bound in the enclosing scope, although according
> to the definitions stated above, both should be considered free. The
> bytecode generated for loading cc and myparam is different, of course.
> Is there a (however slight) inconsistency of terms here, or is it my
> misunderstanding?

There's a slight inconsistency. The names a code object explicitly
calls out as free variables (i.e. references to cells in outer scopes)
are only a subset of the full set of free variables (every referenced
name that isn't a local variable or an attribute).

>>> from dis import show_code
>>> def outer():
...   x, y = 1, 2
...   def inner():
...     print (x, y, a, b, c.e)
...   return inner
>>> f = outer()
>>> show_code(f)
Name:              inner
Filename:          <stdin>
Argument count:    0
Kw-only arguments: 0
Number of locals:  0
Stack size:        6
   0: None
   0: print
   1: a
   2: b
   3: c
   4: e
Free variables:
   0: y
   1: x

a, b, and c are also free variables in the more general sense, but the
code object doesn't explicitly flag them as such since it doesn't need
to do anything special with them.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list