Update decimal test data to the most recent set from Mike Cowlishaw.
[python.git] / Lib / test / test_code.py
blob4a88e60d1d91ee054470c674a18dbb2ded242738
1 """This module includes tests of the code object representation.
3 >>> def f(x):
4 ... def g(y):
5 ... return x + y
6 ... return g
7 ...
9 >>> dump(f.func_code)
10 name: f
11 argcount: 1
12 names: ()
13 varnames: ('x', 'g')
14 cellvars: ('x',)
15 freevars: ()
16 nlocals: 2
17 flags: 3
18 consts: ('None', '<code object g>')
20 >>> dump(f(4).func_code)
21 name: g
22 argcount: 1
23 names: ()
24 varnames: ('y',)
25 cellvars: ()
26 freevars: ('x',)
27 nlocals: 1
28 flags: 19
29 consts: ('None',)
31 >>> def h(x, y):
32 ... a = x + y
33 ... b = x - y
34 ... c = a * b
35 ... return c
36 ...
37 >>> dump(h.func_code)
38 name: h
39 argcount: 2
40 names: ()
41 varnames: ('x', 'y', 'a', 'b', 'c')
42 cellvars: ()
43 freevars: ()
44 nlocals: 5
45 flags: 67
46 consts: ('None',)
48 >>> def attrs(obj):
49 ... print obj.attr1
50 ... print obj.attr2
51 ... print obj.attr3
53 >>> dump(attrs.func_code)
54 name: attrs
55 argcount: 1
56 names: ('attr1', 'attr2', 'attr3')
57 varnames: ('obj',)
58 cellvars: ()
59 freevars: ()
60 nlocals: 1
61 flags: 67
62 consts: ('None',)
64 >>> def optimize_away():
65 ... 'doc string'
66 ... 'not a docstring'
67 ... 53
68 ... 53L
70 >>> dump(optimize_away.func_code)
71 name: optimize_away
72 argcount: 0
73 names: ()
74 varnames: ()
75 cellvars: ()
76 freevars: ()
77 nlocals: 0
78 flags: 67
79 consts: ("'doc string'", 'None')
81 """
83 import unittest
84 import _testcapi
86 def consts(t):
87 """Yield a doctest-safe sequence of object reprs."""
88 for elt in t:
89 r = repr(elt)
90 if r.startswith("<code object"):
91 yield "<code object %s>" % elt.co_name
92 else:
93 yield r
95 def dump(co):
96 """Print out a text representation of a code object."""
97 for attr in ["name", "argcount", "names", "varnames", "cellvars",
98 "freevars", "nlocals", "flags"]:
99 print "%s: %s" % (attr, getattr(co, "co_" + attr))
100 print "consts:", tuple(consts(co.co_consts))
103 class CodeTest(unittest.TestCase):
105 def test_newempty(self):
106 co = _testcapi.code_newempty("filename", "funcname", 15)
107 self.assertEquals(co.co_filename, "filename")
108 self.assertEquals(co.co_name, "funcname")
109 self.assertEquals(co.co_firstlineno, 15)
112 def test_main(verbose=None):
113 from test.test_support import run_doctest, run_unittest
114 from test import test_code
115 run_doctest(test_code, verbose)
116 run_unittest(CodeTest)
119 if __name__ == '__main__':
120 test_main()