blob: 52bc8948b9872cd4f664d7a2a6015fec06e25114 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001"""This module includes tests of the code object representation.
2
3>>> def f(x):
4... def g(y):
5... return x + y
6... return g
7...
8
9>>> dump(f.func_code)
10name: f
11argcount: 1
12names: ()
13varnames: ('x', 'g')
14cellvars: ('x',)
15freevars: ()
16nlocals: 2
17flags: 3
18consts: ('None', '<code object g>')
19
20>>> dump(f(4).func_code)
21name: g
22argcount: 1
23names: ()
24varnames: ('y',)
25cellvars: ()
26freevars: ('x',)
27nlocals: 1
28flags: 19
29consts: ('None',)
30
31>>> def h(x, y):
32... a = x + y
33... b = x - y
34... c = a * b
35... return c
Tim Peters536cf992005-12-25 23:18:31 +000036...
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037>>> dump(h.func_code)
38name: h
39argcount: 2
40names: ()
41varnames: ('x', 'y', 'a', 'b', 'c')
42cellvars: ()
43freevars: ()
44nlocals: 5
45flags: 67
46consts: ('None',)
47
48>>> def attrs(obj):
49... print obj.attr1
50... print obj.attr2
51... print obj.attr3
52
53>>> dump(attrs.func_code)
54name: attrs
55argcount: 1
56names: ('attr1', 'attr2', 'attr3')
57varnames: ('obj',)
58cellvars: ()
59freevars: ()
60nlocals: 1
61flags: 67
62consts: ('None',)
63
64"""
65
66def consts(t):
67 """Yield a doctest-safe sequence of object reprs."""
68 for elt in t:
69 r = repr(elt)
70 if r.startswith("<code object"):
71 yield "<code object %s>" % elt.co_name
72 else:
73 yield r
74
75def dump(co):
76 """Print out a text representation of a code object."""
77 for attr in ["name", "argcount", "names", "varnames", "cellvars",
78 "freevars", "nlocals", "flags"]:
79 print "%s: %s" % (attr, getattr(co, "co_" + attr))
80 print "consts:", tuple(consts(co.co_consts))
81
82def test_main(verbose=None):
83 from test.test_support import run_doctest
84 from test import test_code
85 run_doctest(test_code, verbose)