1 """This module includes tests of the code object representation.
18 consts: ('None', '<code object g>')
20 >>> dump(f(4).func_code)
41 varnames: ('x', 'y', 'a', 'b', 'c')
53 >>> dump(attrs.func_code)
56 names: ('attr1', 'attr2', 'attr3')
64 >>> def optimize_away():
70 >>> dump(optimize_away.func_code)
79 consts: ("'doc string'", 'None')
89 """Yield a doctest-safe sequence of object reprs."""
92 if r
.startswith("<code object"):
93 yield "<code object %s>" % elt
.co_name
98 """Print out a text representation of a code object."""
99 for attr
in ["name", "argcount", "names", "varnames", "cellvars",
100 "freevars", "nlocals", "flags"]:
101 print "%s: %s" % (attr
, getattr(co
, "co_" + attr
))
102 print "consts:", tuple(consts(co
.co_consts
))
105 class CodeTest(unittest
.TestCase
):
107 def test_newempty(self
):
108 co
= _testcapi
.code_newempty("filename", "funcname", 15)
109 self
.assertEquals(co
.co_filename
, "filename")
110 self
.assertEquals(co
.co_name
, "funcname")
111 self
.assertEquals(co
.co_firstlineno
, 15)
114 class CodeWeakRefTest(unittest
.TestCase
):
116 def test_basic(self
):
117 # Create a code object in a clean environment so that we know we have
118 # the only reference to it left.
120 exec "def f(): pass" in globals(), namespace
128 # f is now the last reference to the function, and through it, the code
129 # object. While we hold it, check that we can create a weakref and
130 # deref it. Then delete it, and check that the callback gets called and
131 # the reference dies.
132 coderef
= weakref
.ref(f
.__code
__, callback
)
133 self
.assertTrue(bool(coderef()))
135 self
.assertFalse(bool(coderef()))
136 self
.assertTrue(self
.called
)
139 def test_main(verbose
=None):
140 from test
.test_support
import run_doctest
, run_unittest
141 from test
import test_code
142 run_doctest(test_code
, verbose
)
143 run_unittest(CodeTest
, CodeWeakRefTest
)
146 if __name__
== "__main__":