Skip to content

Commit d6b62a2

Browse files
committed
tests/basics/fun_code_full: Test code objects with full feature set.
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
1 parent 0732c45 commit d6b62a2

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

tests/basics/fun_code_full.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Test function.__code__ attributes not available with MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_BASIC
2+
3+
try:
4+
(lambda: 0).__code__.co_code
5+
except AttributeError:
6+
print("SKIP")
7+
raise SystemExit
8+
9+
try:
10+
import warnings
11+
warnings.simplefilter("ignore") # ignore deprecation warning about co_lnotab
12+
except ImportError:
13+
pass
14+
15+
def f(x, y):
16+
a = x + y
17+
b = x - y
18+
return a * b
19+
20+
code = f.__code__
21+
22+
print(type(code.co_code)) # both bytes (but mpy and cpy have different instruction sets)
23+
print(code.co_consts) # (not necessarily the same set, but in this function they are)
24+
print(code.co_filename.rsplit('/')[-1]) # same terminal filename but might be different paths on other ports
25+
print(type(code.co_firstlineno)) # both ints (but mpy points to first line inside, cpy points to declaration)
26+
print(code.co_name)
27+
print(iter(code.co_names) is not None) # both iterable (but mpy returns dict with names as keys, cpy only the names; and not necessarily the same set)
28+
print(type(code.co_lnotab)) # both bytes
29+
30+
co_lines = code.co_lines()
31+
32+
l = list(co_lines)
33+
first_start = l[0][0]
34+
last_end = l[-1][1]
35+
print(first_start) # co_lines should start at the start of the bytecode
36+
print(len(code.co_code) - last_end) # and end at the end of the bytecode
37+
38+
prev_end = 0
39+
for start, end, line_no in l:
40+
if end != prev_end:
41+
print("non-contiguous")
42+
break # the offset ranges should be contiguous
43+
prev_end = end
44+
else:
45+
print("contiguous")
46+
47+

0 commit comments

Comments
 (0)