code doesn't reference immutables?

Terry Reedy tjreedy at udel.edu
Tue Jan 8 02:40:28 CET 2008


<MartinRinehart at gmail.com> wrote in message 
news:5e6d3674-fddb-402f-9e5c-19afcd7fcc22 at i7g2000prf.googlegroups.com...
| >From the manual:
|
| "code objects are immutable and contain no references (directly or
| indirectly) to mutable objects" (3.2)
|
| I thought my code worked with both mutable and immutable objects.
| Whassup?

Consider the following:

>>> def g(): return (1,2), [1,2]

>>> dis.dis(g)
  1           0 LOAD_CONST               3 ((1, 2))
              3 LOAD_CONST               1 (1)
              6 LOAD_CONST               2 (2)
              9 BUILD_LIST               2
             12 BUILD_TUPLE              2
             15 RETURN_VALUE

>>> g.func_code.co_consts
(None, 1, 2, (1, 2))

The code object stores the immutables 1, 2, and (1,2) but not the mutable 
[1,2].  Rather it stores immutable code to create the mutable list.

I tried to see if the addition of closures violated the stipulation, using

>>> def f():
 l = []
 def _(x):
  l.append(x)
 return _

but the inner code object only knows the list by the (immutable) name 'l', 
which does not count as a reference.  Such code objects cannot be directly 
exec'ed but only executed indirectly by calling the function that wraps it 
and that has the reference to the in-this-case mutable object.  (The 
mapping from 'l' to that object appears to be hidden.)

Terry Jan Reedy






More information about the Python-list mailing list