code object differences between 2.7 and 3.3a

Eric Snow ericsnowcurrently at
Thu Aug 11 02:38:17 CEST 2011

Specifically, I am wondering why there is a difference for co_names.
Here is a function that exercises the different code object pieces[1]:

def g(y=5):
   a = 7
   def f(x, w=y, z=4, *args, **kwargs):
      b = a
      c = global_x
   return f

f1 = g()

Here are the results for 2.7:

>>> for name in dir(f1.func_code): print("%s -> %s" % (name, getattr(f1.func_code, name)))
co_argcount -> 3
co_cellvars -> ()
co_code -> }t}dS
co_consts -> (None,)
co_filename -> <stdin>
co_firstlineno -> 3
co_flags -> 15
co_freevars -> ('a',)
co_lnotab ->
co_name -> f
co_names -> ('a', 'b', 'global_x', 'c')
co_nlocals -> 7
co_stacksize -> 1
co_varnames -> ('x', 'w', 'z', 'args', 'kwargs', 'c', 'b')

And for 3.3:

>>> for name in dir(f1.__code__): print("%s -> %s" % (name, getattr(f1.__code__, name)))
co_argcount -> 3
co_cellvars -> ()
co_code -> b'\x88\x00\x00}\x05\x00t\x00\x00}\x06\x00d\x00\x00S'
co_consts -> (None,)
co_filename -> <stdin>
co_firstlineno -> 3
co_flags -> 31
co_freevars -> ('a',)
co_kwonlyargcount -> 0
co_lnotab -> b'\x00\x01\x06\x01'
co_name -> f
co_names -> ('global_x',)
co_nlocals -> 7
co_stacksize -> 1
co_varnames -> ('x', 'w', 'z', 'args', 'kwargs', 'b', 'c')

While there are several differences, the one I care about is co_name.
For 2.7 it's what I would expect.  However, for 3.3 it's not[2][3].
It is actually nicer for my application this way, but I want to verify
the situation before I get me hopes up. :)

Before I go email-list-diving or digging through PyEval_EvalCodeEx,  I
wanted to see if anyone has any insight about this change in co_names.


[1] yes, 3.x also supports keyword-only arguments.  I tried this on
3.3 with extra kw-only arguments and it was the same outcome.
[2] The documentation for the inspect module gives an incomplete
listing of the code object attributes:
<>  The description of
co_names there ("tuple of names of local variables") seems
inconsistent with what I am seeing.  It's probably just that I am
misinterpreting that list or the doc needs an update.
[3] My guess is that co_names was seen as bloated and the superfluous
items removed, leaving only the un-closed free variables; co_freevars
is the closed free variables.  To get the same tuple as the 2.7
version, you could compose it from co_freevars, co_names, and the end
of co_varnames.

More information about the Python-list mailing list