1# Minimal tests for dis module 2 3from test.support import captured_stdout 4from test.support.bytecode_helper import BytecodeTestCase 5import unittest 6import sys 7import dis 8import io 9import re 10import types 11import contextlib 12 13def get_tb(): 14 def _error(): 15 try: 16 1 / 0 17 except Exception as e: 18 tb = e.__traceback__ 19 return tb 20 21 tb = _error() 22 while tb.tb_next: 23 tb = tb.tb_next 24 return tb 25 26TRACEBACK_CODE = get_tb().tb_frame.f_code 27 28class _C: 29 def __init__(self, x): 30 self.x = x == 1 31 32 @staticmethod 33 def sm(x): 34 x = x == 1 35 36 @classmethod 37 def cm(cls, x): 38 cls.x = x == 1 39 40dis_c_instance_method = """\ 41%3d 0 LOAD_FAST 1 (x) 42 2 LOAD_CONST 1 (1) 43 4 COMPARE_OP 2 (==) 44 6 LOAD_FAST 0 (self) 45 8 STORE_ATTR 0 (x) 46 10 LOAD_CONST 0 (None) 47 12 RETURN_VALUE 48""" % (_C.__init__.__code__.co_firstlineno + 1,) 49 50dis_c_instance_method_bytes = """\ 51 0 LOAD_FAST 1 (1) 52 2 LOAD_CONST 1 (1) 53 4 COMPARE_OP 2 (==) 54 6 LOAD_FAST 0 (0) 55 8 STORE_ATTR 0 (0) 56 10 LOAD_CONST 0 (0) 57 12 RETURN_VALUE 58""" 59 60dis_c_class_method = """\ 61%3d 0 LOAD_FAST 1 (x) 62 2 LOAD_CONST 1 (1) 63 4 COMPARE_OP 2 (==) 64 6 LOAD_FAST 0 (cls) 65 8 STORE_ATTR 0 (x) 66 10 LOAD_CONST 0 (None) 67 12 RETURN_VALUE 68""" % (_C.cm.__code__.co_firstlineno + 2,) 69 70dis_c_static_method = """\ 71%3d 0 LOAD_FAST 0 (x) 72 2 LOAD_CONST 1 (1) 73 4 COMPARE_OP 2 (==) 74 6 STORE_FAST 0 (x) 75 8 LOAD_CONST 0 (None) 76 10 RETURN_VALUE 77""" % (_C.sm.__code__.co_firstlineno + 2,) 78 79# Class disassembling info has an extra newline at end. 80dis_c = """\ 81Disassembly of %s: 82%s 83Disassembly of %s: 84%s 85Disassembly of %s: 86%s 87""" % (_C.__init__.__name__, dis_c_instance_method, 88 _C.cm.__name__, dis_c_class_method, 89 _C.sm.__name__, dis_c_static_method) 90 91def _f(a): 92 print(a) 93 return 1 94 95dis_f = """\ 96%3d 0 LOAD_GLOBAL 0 (print) 97 2 LOAD_FAST 0 (a) 98 4 CALL_FUNCTION 1 99 6 POP_TOP 100 101%3d 8 LOAD_CONST 1 (1) 102 10 RETURN_VALUE 103""" % (_f.__code__.co_firstlineno + 1, 104 _f.__code__.co_firstlineno + 2) 105 106 107dis_f_co_code = """\ 108 0 LOAD_GLOBAL 0 (0) 109 2 LOAD_FAST 0 (0) 110 4 CALL_FUNCTION 1 111 6 POP_TOP 112 8 LOAD_CONST 1 (1) 113 10 RETURN_VALUE 114""" 115 116 117def bug708901(): 118 for res in range(1, 119 10): 120 pass 121 122dis_bug708901 = """\ 123%3d 0 LOAD_GLOBAL 0 (range) 124 2 LOAD_CONST 1 (1) 125 126%3d 4 LOAD_CONST 2 (10) 127 128%3d 6 CALL_FUNCTION 2 129 8 GET_ITER 130 >> 10 FOR_ITER 4 (to 16) 131 12 STORE_FAST 0 (res) 132 133%3d 14 JUMP_ABSOLUTE 10 134 >> 16 LOAD_CONST 0 (None) 135 18 RETURN_VALUE 136""" % (bug708901.__code__.co_firstlineno + 1, 137 bug708901.__code__.co_firstlineno + 2, 138 bug708901.__code__.co_firstlineno + 1, 139 bug708901.__code__.co_firstlineno + 3) 140 141 142def bug1333982(x=[]): 143 assert 0, ([s for s in x] + 144 1) 145 pass 146 147dis_bug1333982 = """\ 148%3d 0 LOAD_CONST 1 (0) 149 2 POP_JUMP_IF_TRUE 26 150 4 LOAD_ASSERTION_ERROR 151 6 LOAD_CONST 2 (<code object <listcomp> at 0x..., file "%s", line %d>) 152 8 LOAD_CONST 3 ('bug1333982.<locals>.<listcomp>') 153 10 MAKE_FUNCTION 0 154 12 LOAD_FAST 0 (x) 155 14 GET_ITER 156 16 CALL_FUNCTION 1 157 158%3d 18 LOAD_CONST 4 (1) 159 160%3d 20 BINARY_ADD 161 22 CALL_FUNCTION 1 162 24 RAISE_VARARGS 1 163 164%3d >> 26 LOAD_CONST 0 (None) 165 28 RETURN_VALUE 166""" % (bug1333982.__code__.co_firstlineno + 1, 167 __file__, 168 bug1333982.__code__.co_firstlineno + 1, 169 bug1333982.__code__.co_firstlineno + 2, 170 bug1333982.__code__.co_firstlineno + 1, 171 bug1333982.__code__.co_firstlineno + 3) 172 173_BIG_LINENO_FORMAT = """\ 174%3d 0 LOAD_GLOBAL 0 (spam) 175 2 POP_TOP 176 4 LOAD_CONST 0 (None) 177 6 RETURN_VALUE 178""" 179 180_BIG_LINENO_FORMAT2 = """\ 181%4d 0 LOAD_GLOBAL 0 (spam) 182 2 POP_TOP 183 4 LOAD_CONST 0 (None) 184 6 RETURN_VALUE 185""" 186 187dis_module_expected_results = """\ 188Disassembly of f: 189 4 0 LOAD_CONST 0 (None) 190 2 RETURN_VALUE 191 192Disassembly of g: 193 5 0 LOAD_CONST 0 (None) 194 2 RETURN_VALUE 195 196""" 197 198expr_str = "x + 1" 199 200dis_expr_str = """\ 201 1 0 LOAD_NAME 0 (x) 202 2 LOAD_CONST 0 (1) 203 4 BINARY_ADD 204 6 RETURN_VALUE 205""" 206 207simple_stmt_str = "x = x + 1" 208 209dis_simple_stmt_str = """\ 210 1 0 LOAD_NAME 0 (x) 211 2 LOAD_CONST 0 (1) 212 4 BINARY_ADD 213 6 STORE_NAME 0 (x) 214 8 LOAD_CONST 1 (None) 215 10 RETURN_VALUE 216""" 217 218annot_stmt_str = """\ 219 220x: int = 1 221y: fun(1) 222lst[fun(0)]: int = 1 223""" 224# leading newline is for a reason (tests lineno) 225 226dis_annot_stmt_str = """\ 227 2 0 SETUP_ANNOTATIONS 228 2 LOAD_CONST 0 (1) 229 4 STORE_NAME 0 (x) 230 6 LOAD_NAME 1 (int) 231 8 LOAD_NAME 2 (__annotations__) 232 10 LOAD_CONST 1 ('x') 233 12 STORE_SUBSCR 234 235 3 14 LOAD_NAME 3 (fun) 236 16 LOAD_CONST 0 (1) 237 18 CALL_FUNCTION 1 238 20 LOAD_NAME 2 (__annotations__) 239 22 LOAD_CONST 2 ('y') 240 24 STORE_SUBSCR 241 242 4 26 LOAD_CONST 0 (1) 243 28 LOAD_NAME 4 (lst) 244 30 LOAD_NAME 3 (fun) 245 32 LOAD_CONST 3 (0) 246 34 CALL_FUNCTION 1 247 36 STORE_SUBSCR 248 38 LOAD_NAME 1 (int) 249 40 POP_TOP 250 42 LOAD_CONST 4 (None) 251 44 RETURN_VALUE 252""" 253 254compound_stmt_str = """\ 255x = 0 256while 1: 257 x += 1""" 258# Trailing newline has been deliberately omitted 259 260dis_compound_stmt_str = """\ 261 1 0 LOAD_CONST 0 (0) 262 2 STORE_NAME 0 (x) 263 264 3 >> 4 LOAD_NAME 0 (x) 265 6 LOAD_CONST 1 (1) 266 8 INPLACE_ADD 267 10 STORE_NAME 0 (x) 268 12 JUMP_ABSOLUTE 4 269 14 LOAD_CONST 2 (None) 270 16 RETURN_VALUE 271""" 272 273dis_traceback = """\ 274%3d 0 SETUP_FINALLY 12 (to 14) 275 276%3d 2 LOAD_CONST 1 (1) 277 4 LOAD_CONST 2 (0) 278 --> 6 BINARY_TRUE_DIVIDE 279 8 POP_TOP 280 10 POP_BLOCK 281 12 JUMP_FORWARD 42 (to 56) 282 283%3d >> 14 DUP_TOP 284 16 LOAD_GLOBAL 0 (Exception) 285 18 JUMP_IF_NOT_EXC_MATCH 54 286 20 POP_TOP 287 22 STORE_FAST 0 (e) 288 24 POP_TOP 289 26 SETUP_FINALLY 18 (to 46) 290 291%3d 28 LOAD_FAST 0 (e) 292 30 LOAD_ATTR 1 (__traceback__) 293 32 STORE_FAST 1 (tb) 294 34 POP_BLOCK 295 36 POP_EXCEPT 296 38 LOAD_CONST 0 (None) 297 40 STORE_FAST 0 (e) 298 42 DELETE_FAST 0 (e) 299 44 JUMP_FORWARD 10 (to 56) 300 >> 46 LOAD_CONST 0 (None) 301 48 STORE_FAST 0 (e) 302 50 DELETE_FAST 0 (e) 303 52 RERAISE 304 >> 54 RERAISE 305 306%3d >> 56 LOAD_FAST 1 (tb) 307 58 RETURN_VALUE 308""" % (TRACEBACK_CODE.co_firstlineno + 1, 309 TRACEBACK_CODE.co_firstlineno + 2, 310 TRACEBACK_CODE.co_firstlineno + 3, 311 TRACEBACK_CODE.co_firstlineno + 4, 312 TRACEBACK_CODE.co_firstlineno + 5) 313 314def _fstring(a, b, c, d): 315 return f'{a} {b:4} {c!r} {d!r:4}' 316 317dis_fstring = """\ 318%3d 0 LOAD_FAST 0 (a) 319 2 FORMAT_VALUE 0 320 4 LOAD_CONST 1 (' ') 321 6 LOAD_FAST 1 (b) 322 8 LOAD_CONST 2 ('4') 323 10 FORMAT_VALUE 4 (with format) 324 12 LOAD_CONST 1 (' ') 325 14 LOAD_FAST 2 (c) 326 16 FORMAT_VALUE 2 (repr) 327 18 LOAD_CONST 1 (' ') 328 20 LOAD_FAST 3 (d) 329 22 LOAD_CONST 2 ('4') 330 24 FORMAT_VALUE 6 (repr, with format) 331 26 BUILD_STRING 7 332 28 RETURN_VALUE 333""" % (_fstring.__code__.co_firstlineno + 1,) 334 335def _tryfinally(a, b): 336 try: 337 return a 338 finally: 339 b() 340 341def _tryfinallyconst(b): 342 try: 343 return 1 344 finally: 345 b() 346 347dis_tryfinally = """\ 348%3d 0 SETUP_FINALLY 12 (to 14) 349 350%3d 2 LOAD_FAST 0 (a) 351 4 POP_BLOCK 352 353%3d 6 LOAD_FAST 1 (b) 354 8 CALL_FUNCTION 0 355 10 POP_TOP 356 357%3d 12 RETURN_VALUE 358 359%3d >> 14 LOAD_FAST 1 (b) 360 16 CALL_FUNCTION 0 361 18 POP_TOP 362 20 RERAISE 363 22 LOAD_CONST 0 (None) 364 24 RETURN_VALUE 365""" % (_tryfinally.__code__.co_firstlineno + 1, 366 _tryfinally.__code__.co_firstlineno + 2, 367 _tryfinally.__code__.co_firstlineno + 4, 368 _tryfinally.__code__.co_firstlineno + 2, 369 _tryfinally.__code__.co_firstlineno + 4, 370 ) 371 372dis_tryfinallyconst = """\ 373%3d 0 SETUP_FINALLY 12 (to 14) 374 375%3d 2 POP_BLOCK 376 377%3d 4 LOAD_FAST 0 (b) 378 6 CALL_FUNCTION 0 379 8 POP_TOP 380 381%3d 10 LOAD_CONST 1 (1) 382 12 RETURN_VALUE 383 384%3d >> 14 LOAD_FAST 0 (b) 385 16 CALL_FUNCTION 0 386 18 POP_TOP 387 20 RERAISE 388 22 LOAD_CONST 0 (None) 389 24 RETURN_VALUE 390""" % (_tryfinallyconst.__code__.co_firstlineno + 1, 391 _tryfinallyconst.__code__.co_firstlineno + 2, 392 _tryfinallyconst.__code__.co_firstlineno + 4, 393 _tryfinallyconst.__code__.co_firstlineno + 2, 394 _tryfinallyconst.__code__.co_firstlineno + 4, 395 ) 396 397def _g(x): 398 yield x 399 400async def _ag(x): 401 yield x 402 403async def _co(x): 404 async for item in _ag(x): 405 pass 406 407def _h(y): 408 def foo(x): 409 '''funcdoc''' 410 return [x + z for z in y] 411 return foo 412 413dis_nested_0 = """\ 414%3d 0 LOAD_CLOSURE 0 (y) 415 2 BUILD_TUPLE 1 416 4 LOAD_CONST 1 (<code object foo at 0x..., file "%s", line %d>) 417 6 LOAD_CONST 2 ('_h.<locals>.foo') 418 8 MAKE_FUNCTION 8 (closure) 419 10 STORE_FAST 1 (foo) 420 421%3d 12 LOAD_FAST 1 (foo) 422 14 RETURN_VALUE 423""" % (_h.__code__.co_firstlineno + 1, 424 __file__, 425 _h.__code__.co_firstlineno + 1, 426 _h.__code__.co_firstlineno + 4, 427) 428 429dis_nested_1 = """%s 430Disassembly of <code object foo at 0x..., file "%s", line %d>: 431%3d 0 LOAD_CLOSURE 0 (x) 432 2 BUILD_TUPLE 1 433 4 LOAD_CONST 1 (<code object <listcomp> at 0x..., file "%s", line %d>) 434 6 LOAD_CONST 2 ('_h.<locals>.foo.<locals>.<listcomp>') 435 8 MAKE_FUNCTION 8 (closure) 436 10 LOAD_DEREF 1 (y) 437 12 GET_ITER 438 14 CALL_FUNCTION 1 439 16 RETURN_VALUE 440""" % (dis_nested_0, 441 __file__, 442 _h.__code__.co_firstlineno + 1, 443 _h.__code__.co_firstlineno + 3, 444 __file__, 445 _h.__code__.co_firstlineno + 3, 446) 447 448dis_nested_2 = """%s 449Disassembly of <code object <listcomp> at 0x..., file "%s", line %d>: 450%3d 0 BUILD_LIST 0 451 2 LOAD_FAST 0 (.0) 452 >> 4 FOR_ITER 12 (to 18) 453 6 STORE_FAST 1 (z) 454 8 LOAD_DEREF 0 (x) 455 10 LOAD_FAST 1 (z) 456 12 BINARY_ADD 457 14 LIST_APPEND 2 458 16 JUMP_ABSOLUTE 4 459 >> 18 RETURN_VALUE 460""" % (dis_nested_1, 461 __file__, 462 _h.__code__.co_firstlineno + 3, 463 _h.__code__.co_firstlineno + 3, 464) 465 466 467class DisTests(unittest.TestCase): 468 469 maxDiff = None 470 471 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): 472 # We want to test the default printing behaviour, not the file arg 473 output = io.StringIO() 474 with contextlib.redirect_stdout(output): 475 if wrapper: 476 dis.dis(func, **kwargs) 477 else: 478 dis.disassemble(func, lasti, **kwargs) 479 return output.getvalue() 480 481 def get_disassemble_as_string(self, func, lasti=-1): 482 return self.get_disassembly(func, lasti, False) 483 484 def strip_addresses(self, text): 485 return re.sub(r'\b0x[0-9A-Fa-f]+\b', '0x...', text) 486 487 def do_disassembly_test(self, func, expected): 488 got = self.get_disassembly(func, depth=0) 489 if got != expected: 490 got = self.strip_addresses(got) 491 self.assertEqual(got, expected) 492 493 def test_opmap(self): 494 self.assertEqual(dis.opmap["NOP"], 9) 495 self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst) 496 self.assertIn(dis.opmap["STORE_NAME"], dis.hasname) 497 498 def test_opname(self): 499 self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST") 500 501 def test_boundaries(self): 502 self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG) 503 self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT) 504 505 def test_widths(self): 506 for opcode, opname in enumerate(dis.opname): 507 if opname in ('BUILD_MAP_UNPACK_WITH_CALL', 508 'BUILD_TUPLE_UNPACK_WITH_CALL', 509 'JUMP_IF_NOT_EXC_MATCH'): 510 continue 511 with self.subTest(opname=opname): 512 width = dis._OPNAME_WIDTH 513 if opcode < dis.HAVE_ARGUMENT: 514 width += 1 + dis._OPARG_WIDTH 515 self.assertLessEqual(len(opname), width) 516 517 def test_dis(self): 518 self.do_disassembly_test(_f, dis_f) 519 520 def test_bug_708901(self): 521 self.do_disassembly_test(bug708901, dis_bug708901) 522 523 def test_bug_1333982(self): 524 # This one is checking bytecodes generated for an `assert` statement, 525 # so fails if the tests are run with -O. Skip this test then. 526 if not __debug__: 527 self.skipTest('need asserts, run without -O') 528 529 self.do_disassembly_test(bug1333982, dis_bug1333982) 530 531 def test_big_linenos(self): 532 def func(count): 533 namespace = {} 534 func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"]) 535 exec(func, namespace) 536 return namespace['foo'] 537 538 # Test all small ranges 539 for i in range(1, 300): 540 expected = _BIG_LINENO_FORMAT % (i + 2) 541 self.do_disassembly_test(func(i), expected) 542 543 # Test some larger ranges too 544 for i in range(300, 1000, 10): 545 expected = _BIG_LINENO_FORMAT % (i + 2) 546 self.do_disassembly_test(func(i), expected) 547 548 for i in range(1000, 5000, 10): 549 expected = _BIG_LINENO_FORMAT2 % (i + 2) 550 self.do_disassembly_test(func(i), expected) 551 552 from test import dis_module 553 self.do_disassembly_test(dis_module, dis_module_expected_results) 554 555 def test_big_offsets(self): 556 def func(count): 557 namespace = {} 558 func = "def foo(x):\n " + ";".join(["x = x + 1"] * count) + "\n return x" 559 exec(func, namespace) 560 return namespace['foo'] 561 562 def expected(count, w): 563 s = ['''\ 564 %*d LOAD_FAST 0 (x) 565 %*d LOAD_CONST 1 (1) 566 %*d BINARY_ADD 567 %*d STORE_FAST 0 (x) 568''' % (w, 8*i, w, 8*i + 2, w, 8*i + 4, w, 8*i + 6) 569 for i in range(count)] 570 s += ['''\ 571 572 3 %*d LOAD_FAST 0 (x) 573 %*d RETURN_VALUE 574''' % (w, 8*count, w, 8*count + 2)] 575 s[0] = ' 2' + s[0][3:] 576 return ''.join(s) 577 578 for i in range(1, 5): 579 self.do_disassembly_test(func(i), expected(i, 4)) 580 self.do_disassembly_test(func(1249), expected(1249, 4)) 581 self.do_disassembly_test(func(1250), expected(1250, 5)) 582 583 def test_disassemble_str(self): 584 self.do_disassembly_test(expr_str, dis_expr_str) 585 self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str) 586 self.do_disassembly_test(annot_stmt_str, dis_annot_stmt_str) 587 self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str) 588 589 def test_disassemble_bytes(self): 590 self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code) 591 592 def test_disassemble_class(self): 593 self.do_disassembly_test(_C, dis_c) 594 595 def test_disassemble_instance_method(self): 596 self.do_disassembly_test(_C(1).__init__, dis_c_instance_method) 597 598 def test_disassemble_instance_method_bytes(self): 599 method_bytecode = _C(1).__init__.__code__.co_code 600 self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes) 601 602 def test_disassemble_static_method(self): 603 self.do_disassembly_test(_C.sm, dis_c_static_method) 604 605 def test_disassemble_class_method(self): 606 self.do_disassembly_test(_C.cm, dis_c_class_method) 607 608 def test_disassemble_generator(self): 609 gen_func_disas = self.get_disassembly(_g) # Generator function 610 gen_disas = self.get_disassembly(_g(1)) # Generator iterator 611 self.assertEqual(gen_disas, gen_func_disas) 612 613 def test_disassemble_async_generator(self): 614 agen_func_disas = self.get_disassembly(_ag) # Async generator function 615 agen_disas = self.get_disassembly(_ag(1)) # Async generator iterator 616 self.assertEqual(agen_disas, agen_func_disas) 617 618 def test_disassemble_coroutine(self): 619 coro_func_disas = self.get_disassembly(_co) # Coroutine function 620 coro = _co(1) # Coroutine object 621 coro.close() # Avoid a RuntimeWarning (never awaited) 622 coro_disas = self.get_disassembly(coro) 623 self.assertEqual(coro_disas, coro_func_disas) 624 625 def test_disassemble_fstring(self): 626 self.do_disassembly_test(_fstring, dis_fstring) 627 628 def test_disassemble_try_finally(self): 629 self.do_disassembly_test(_tryfinally, dis_tryfinally) 630 self.do_disassembly_test(_tryfinallyconst, dis_tryfinallyconst) 631 632 def test_dis_none(self): 633 try: 634 del sys.last_traceback 635 except AttributeError: 636 pass 637 self.assertRaises(RuntimeError, dis.dis, None) 638 639 def test_dis_traceback(self): 640 try: 641 del sys.last_traceback 642 except AttributeError: 643 pass 644 645 try: 646 1/0 647 except Exception as e: 648 tb = e.__traceback__ 649 sys.last_traceback = tb 650 651 tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti) 652 self.do_disassembly_test(None, tb_dis) 653 654 def test_dis_object(self): 655 self.assertRaises(TypeError, dis.dis, object()) 656 657 def test_disassemble_recursive(self): 658 def check(expected, **kwargs): 659 dis = self.get_disassembly(_h, **kwargs) 660 dis = self.strip_addresses(dis) 661 self.assertEqual(dis, expected) 662 663 check(dis_nested_0, depth=0) 664 check(dis_nested_1, depth=1) 665 check(dis_nested_2, depth=2) 666 check(dis_nested_2, depth=3) 667 check(dis_nested_2, depth=None) 668 check(dis_nested_2) 669 670 671class DisWithFileTests(DisTests): 672 673 # Run the tests again, using the file arg instead of print 674 def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): 675 output = io.StringIO() 676 if wrapper: 677 dis.dis(func, file=output, **kwargs) 678 else: 679 dis.disassemble(func, lasti, file=output, **kwargs) 680 return output.getvalue() 681 682 683 684code_info_code_info = """\ 685Name: code_info 686Filename: (.*) 687Argument count: 1 688Positional-only arguments: 0 689Kw-only arguments: 0 690Number of locals: 1 691Stack size: 3 692Flags: OPTIMIZED, NEWLOCALS, NOFREE 693Constants: 694 0: %r 695Names: 696 0: _format_code_info 697 1: _get_code_object 698Variable names: 699 0: x""" % (('Formatted details of methods, functions, or code.',) 700 if sys.flags.optimize < 2 else (None,)) 701 702@staticmethod 703def tricky(a, b, /, x, y, z=True, *args, c, d, e=[], **kwds): 704 def f(c=c): 705 print(a, b, x, y, z, c, d, e, f) 706 yield a, b, x, y, z, c, d, e, f 707 708code_info_tricky = """\ 709Name: tricky 710Filename: (.*) 711Argument count: 5 712Positional-only arguments: 2 713Kw-only arguments: 3 714Number of locals: 10 715Stack size: 9 716Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR 717Constants: 718 0: None 719 1: <code object f at (.*), file "(.*)", line (.*)> 720 2: 'tricky.<locals>.f' 721Variable names: 722 0: a 723 1: b 724 2: x 725 3: y 726 4: z 727 5: c 728 6: d 729 7: e 730 8: args 731 9: kwds 732Cell variables: 733 0: [abedfxyz] 734 1: [abedfxyz] 735 2: [abedfxyz] 736 3: [abedfxyz] 737 4: [abedfxyz] 738 5: [abedfxyz]""" 739# NOTE: the order of the cell variables above depends on dictionary order! 740 741co_tricky_nested_f = tricky.__func__.__code__.co_consts[1] 742 743code_info_tricky_nested_f = """\ 744Filename: (.*) 745Argument count: 1 746Positional-only arguments: 0 747Kw-only arguments: 0 748Number of locals: 1 749Stack size: 10 750Flags: OPTIMIZED, NEWLOCALS, NESTED 751Constants: 752 0: None 753Names: 754 0: print 755Variable names: 756 0: c 757Free variables: 758 0: [abedfxyz] 759 1: [abedfxyz] 760 2: [abedfxyz] 761 3: [abedfxyz] 762 4: [abedfxyz] 763 5: [abedfxyz]""" 764 765code_info_expr_str = """\ 766Name: <module> 767Filename: <disassembly> 768Argument count: 0 769Positional-only arguments: 0 770Kw-only arguments: 0 771Number of locals: 0 772Stack size: 2 773Flags: NOFREE 774Constants: 775 0: 1 776Names: 777 0: x""" 778 779code_info_simple_stmt_str = """\ 780Name: <module> 781Filename: <disassembly> 782Argument count: 0 783Positional-only arguments: 0 784Kw-only arguments: 0 785Number of locals: 0 786Stack size: 2 787Flags: NOFREE 788Constants: 789 0: 1 790 1: None 791Names: 792 0: x""" 793 794code_info_compound_stmt_str = """\ 795Name: <module> 796Filename: <disassembly> 797Argument count: 0 798Positional-only arguments: 0 799Kw-only arguments: 0 800Number of locals: 0 801Stack size: 2 802Flags: NOFREE 803Constants: 804 0: 0 805 1: 1 806 2: None 807Names: 808 0: x""" 809 810 811async def async_def(): 812 await 1 813 async for a in b: pass 814 async with c as d: pass 815 816code_info_async_def = """\ 817Name: async_def 818Filename: (.*) 819Argument count: 0 820Positional-only arguments: 0 821Kw-only arguments: 0 822Number of locals: 2 823Stack size: 9 824Flags: OPTIMIZED, NEWLOCALS, NOFREE, COROUTINE 825Constants: 826 0: None 827 1: 1 828Names: 829 0: b 830 1: c 831Variable names: 832 0: a 833 1: d""" 834 835class CodeInfoTests(unittest.TestCase): 836 test_pairs = [ 837 (dis.code_info, code_info_code_info), 838 (tricky, code_info_tricky), 839 (co_tricky_nested_f, code_info_tricky_nested_f), 840 (expr_str, code_info_expr_str), 841 (simple_stmt_str, code_info_simple_stmt_str), 842 (compound_stmt_str, code_info_compound_stmt_str), 843 (async_def, code_info_async_def) 844 ] 845 846 def test_code_info(self): 847 self.maxDiff = 1000 848 for x, expected in self.test_pairs: 849 self.assertRegex(dis.code_info(x), expected) 850 851 def test_show_code(self): 852 self.maxDiff = 1000 853 for x, expected in self.test_pairs: 854 with captured_stdout() as output: 855 dis.show_code(x) 856 self.assertRegex(output.getvalue(), expected+"\n") 857 output = io.StringIO() 858 dis.show_code(x, file=output) 859 self.assertRegex(output.getvalue(), expected) 860 861 def test_code_info_object(self): 862 self.assertRaises(TypeError, dis.code_info, object()) 863 864 def test_pretty_flags_no_flags(self): 865 self.assertEqual(dis.pretty_flags(0), '0x0') 866 867 868# Fodder for instruction introspection tests 869# Editing any of these may require recalculating the expected output 870def outer(a=1, b=2): 871 def f(c=3, d=4): 872 def inner(e=5, f=6): 873 print(a, b, c, d, e, f) 874 print(a, b, c, d) 875 return inner 876 print(a, b, '', 1, [], {}, "Hello world!") 877 return f 878 879def jumpy(): 880 # This won't actually run (but that's OK, we only disassemble it) 881 for i in range(10): 882 print(i) 883 if i < 4: 884 continue 885 if i > 6: 886 break 887 else: 888 print("I can haz else clause?") 889 while i: 890 print(i) 891 i -= 1 892 if i > 6: 893 continue 894 if i < 4: 895 break 896 else: 897 print("Who let lolcatz into this test suite?") 898 try: 899 1 / 0 900 except ZeroDivisionError: 901 print("Here we go, here we go, here we go...") 902 else: 903 with i as dodgy: 904 print("Never reach this") 905 finally: 906 print("OK, now we're done") 907 908# End fodder for opinfo generation tests 909expected_outer_line = 1 910_line_offset = outer.__code__.co_firstlineno - 1 911code_object_f = outer.__code__.co_consts[3] 912expected_f_line = code_object_f.co_firstlineno - _line_offset 913code_object_inner = code_object_f.co_consts[3] 914expected_inner_line = code_object_inner.co_firstlineno - _line_offset 915expected_jumpy_line = 1 916 917# The following lines are useful to regenerate the expected results after 918# either the fodder is modified or the bytecode generation changes 919# After regeneration, update the references to code_object_f and 920# code_object_inner before rerunning the tests 921 922#_instructions = dis.get_instructions(outer, first_line=expected_outer_line) 923#print('expected_opinfo_outer = [\n ', 924 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 925#_instructions = dis.get_instructions(outer(), first_line=expected_f_line) 926#print('expected_opinfo_f = [\n ', 927 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 928#_instructions = dis.get_instructions(outer()(), first_line=expected_inner_line) 929#print('expected_opinfo_inner = [\n ', 930 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 931#_instructions = dis.get_instructions(jumpy, first_line=expected_jumpy_line) 932#print('expected_opinfo_jumpy = [\n ', 933 #',\n '.join(map(str, _instructions)), ',\n]', sep='') 934 935 936Instruction = dis.Instruction 937expected_opinfo_outer = [ 938 Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval=(3, 4), argrepr='(3, 4)', offset=0, starts_line=2, is_jump_target=False), 939 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), 940 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), 941 Instruction(opname='BUILD_TUPLE', opcode=102, arg=2, argval=2, argrepr='', offset=6, starts_line=None, is_jump_target=False), 942 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_f, argrepr=repr(code_object_f), offset=8, starts_line=None, is_jump_target=False), 943 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f', argrepr="'outer.<locals>.f'", offset=10, starts_line=None, is_jump_target=False), 944 Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='defaults, closure', offset=12, starts_line=None, is_jump_target=False), 945 Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='f', argrepr='f', offset=14, starts_line=None, is_jump_target=False), 946 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=16, starts_line=7, is_jump_target=False), 947 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=18, starts_line=None, is_jump_target=False), 948 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=20, starts_line=None, is_jump_target=False), 949 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval='', argrepr="''", offset=22, starts_line=None, is_jump_target=False), 950 Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval=1, argrepr='1', offset=24, starts_line=None, is_jump_target=False), 951 Instruction(opname='BUILD_LIST', opcode=103, arg=0, argval=0, argrepr='', offset=26, starts_line=None, is_jump_target=False), 952 Instruction(opname='BUILD_MAP', opcode=105, arg=0, argval=0, argrepr='', offset=28, starts_line=None, is_jump_target=False), 953 Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval='Hello world!', argrepr="'Hello world!'", offset=30, starts_line=None, is_jump_target=False), 954 Instruction(opname='CALL_FUNCTION', opcode=131, arg=7, argval=7, argrepr='', offset=32, starts_line=None, is_jump_target=False), 955 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=34, starts_line=None, is_jump_target=False), 956 Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='f', argrepr='f', offset=36, starts_line=8, is_jump_target=False), 957 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=38, starts_line=None, is_jump_target=False), 958] 959 960expected_opinfo_f = [ 961 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=(5, 6), argrepr='(5, 6)', offset=0, starts_line=3, is_jump_target=False), 962 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=2, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), 963 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=3, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), 964 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False), 965 Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False), 966 Instruction(opname='BUILD_TUPLE', opcode=102, arg=4, argval=4, argrepr='', offset=10, starts_line=None, is_jump_target=False), 967 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_inner, argrepr=repr(code_object_inner), offset=12, starts_line=None, is_jump_target=False), 968 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f.<locals>.inner', argrepr="'outer.<locals>.f.<locals>.inner'", offset=14, starts_line=None, is_jump_target=False), 969 Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='defaults, closure', offset=16, starts_line=None, is_jump_target=False), 970 Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='inner', argrepr='inner', offset=18, starts_line=None, is_jump_target=False), 971 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=20, starts_line=5, is_jump_target=False), 972 Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='a', argrepr='a', offset=22, starts_line=None, is_jump_target=False), 973 Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='b', argrepr='b', offset=24, starts_line=None, is_jump_target=False), 974 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='c', argrepr='c', offset=26, starts_line=None, is_jump_target=False), 975 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='d', argrepr='d', offset=28, starts_line=None, is_jump_target=False), 976 Instruction(opname='CALL_FUNCTION', opcode=131, arg=4, argval=4, argrepr='', offset=30, starts_line=None, is_jump_target=False), 977 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=32, starts_line=None, is_jump_target=False), 978 Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='inner', argrepr='inner', offset=34, starts_line=6, is_jump_target=False), 979 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=36, starts_line=None, is_jump_target=False), 980] 981 982expected_opinfo_inner = [ 983 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=0, starts_line=4, is_jump_target=False), 984 Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), 985 Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), 986 Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False), 987 Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False), 988 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='e', argrepr='e', offset=10, starts_line=None, is_jump_target=False), 989 Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='f', argrepr='f', offset=12, starts_line=None, is_jump_target=False), 990 Instruction(opname='CALL_FUNCTION', opcode=131, arg=6, argval=6, argrepr='', offset=14, starts_line=None, is_jump_target=False), 991 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False), 992 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=18, starts_line=None, is_jump_target=False), 993 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=20, starts_line=None, is_jump_target=False), 994] 995 996expected_opinfo_jumpy = [ 997 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='range', argrepr='range', offset=0, starts_line=3, is_jump_target=False), 998 Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval=10, argrepr='10', offset=2, starts_line=None, is_jump_target=False), 999 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=4, starts_line=None, is_jump_target=False), 1000 Instruction(opname='GET_ITER', opcode=68, arg=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False), 1001 Instruction(opname='FOR_ITER', opcode=93, arg=34, argval=44, argrepr='to 44', offset=8, starts_line=None, is_jump_target=True), 1002 Instruction(opname='STORE_FAST', opcode=125, arg=0, argval='i', argrepr='i', offset=10, starts_line=None, is_jump_target=False), 1003 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=12, starts_line=4, is_jump_target=False), 1004 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=14, starts_line=None, is_jump_target=False), 1005 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=16, starts_line=None, is_jump_target=False), 1006 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=18, starts_line=None, is_jump_target=False), 1007 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=20, starts_line=5, is_jump_target=False), 1008 Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=4, argrepr='4', offset=22, starts_line=None, is_jump_target=False), 1009 Instruction(opname='COMPARE_OP', opcode=107, arg=0, argval='<', argrepr='<', offset=24, starts_line=None, is_jump_target=False), 1010 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=30, argval=30, argrepr='', offset=26, starts_line=None, is_jump_target=False), 1011 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=8, argval=8, argrepr='', offset=28, starts_line=6, is_jump_target=False), 1012 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=30, starts_line=7, is_jump_target=True), 1013 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=6, argrepr='6', offset=32, starts_line=None, is_jump_target=False), 1014 Instruction(opname='COMPARE_OP', opcode=107, arg=4, argval='>', argrepr='>', offset=34, starts_line=None, is_jump_target=False), 1015 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=8, argval=8, argrepr='', offset=36, starts_line=None, is_jump_target=False), 1016 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=38, starts_line=8, is_jump_target=False), 1017 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=52, argval=52, argrepr='', offset=40, starts_line=None, is_jump_target=False), 1018 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=8, argval=8, argrepr='', offset=42, starts_line=None, is_jump_target=False), 1019 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=44, starts_line=10, is_jump_target=True), 1020 Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='I can haz else clause?', argrepr="'I can haz else clause?'", offset=46, starts_line=None, is_jump_target=False), 1021 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=48, starts_line=None, is_jump_target=False), 1022 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=50, starts_line=None, is_jump_target=False), 1023 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=52, starts_line=11, is_jump_target=True), 1024 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=94, argval=94, argrepr='', offset=54, starts_line=None, is_jump_target=False), 1025 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=56, starts_line=12, is_jump_target=False), 1026 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=58, starts_line=None, is_jump_target=False), 1027 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=60, starts_line=None, is_jump_target=False), 1028 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=62, starts_line=None, is_jump_target=False), 1029 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=64, starts_line=13, is_jump_target=False), 1030 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=1, argrepr='1', offset=66, starts_line=None, is_jump_target=False), 1031 Instruction(opname='INPLACE_SUBTRACT', opcode=56, arg=None, argval=None, argrepr='', offset=68, starts_line=None, is_jump_target=False), 1032 Instruction(opname='STORE_FAST', opcode=125, arg=0, argval='i', argrepr='i', offset=70, starts_line=None, is_jump_target=False), 1033 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=72, starts_line=14, is_jump_target=False), 1034 Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=6, argrepr='6', offset=74, starts_line=None, is_jump_target=False), 1035 Instruction(opname='COMPARE_OP', opcode=107, arg=4, argval='>', argrepr='>', offset=76, starts_line=None, is_jump_target=False), 1036 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=82, argval=82, argrepr='', offset=78, starts_line=None, is_jump_target=False), 1037 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=52, argval=52, argrepr='', offset=80, starts_line=15, is_jump_target=False), 1038 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=82, starts_line=16, is_jump_target=True), 1039 Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=4, argrepr='4', offset=84, starts_line=None, is_jump_target=False), 1040 Instruction(opname='COMPARE_OP', opcode=107, arg=0, argval='<', argrepr='<', offset=86, starts_line=None, is_jump_target=False), 1041 Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=52, argval=52, argrepr='', offset=88, starts_line=None, is_jump_target=False), 1042 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=102, argval=102, argrepr='', offset=90, starts_line=17, is_jump_target=False), 1043 Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=52, argval=52, argrepr='', offset=92, starts_line=None, is_jump_target=False), 1044 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=94, starts_line=19, is_jump_target=True), 1045 Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval='Who let lolcatz into this test suite?', argrepr="'Who let lolcatz into this test suite?'", offset=96, starts_line=None, is_jump_target=False), 1046 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=98, starts_line=None, is_jump_target=False), 1047 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=100, starts_line=None, is_jump_target=False), 1048 Instruction(opname='SETUP_FINALLY', opcode=122, arg=96, argval=200, argrepr='to 200', offset=102, starts_line=20, is_jump_target=True), 1049 Instruction(opname='SETUP_FINALLY', opcode=122, arg=12, argval=118, argrepr='to 118', offset=104, starts_line=None, is_jump_target=False), 1050 Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=1, argrepr='1', offset=106, starts_line=21, is_jump_target=False), 1051 Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval=0, argrepr='0', offset=108, starts_line=None, is_jump_target=False), 1052 Instruction(opname='BINARY_TRUE_DIVIDE', opcode=27, arg=None, argval=None, argrepr='', offset=110, starts_line=None, is_jump_target=False), 1053 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=112, starts_line=None, is_jump_target=False), 1054 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=114, starts_line=None, is_jump_target=False), 1055 Instruction(opname='JUMP_FORWARD', opcode=110, arg=26, argval=144, argrepr='to 144', offset=116, starts_line=None, is_jump_target=False), 1056 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=118, starts_line=22, is_jump_target=True), 1057 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=2, argval='ZeroDivisionError', argrepr='ZeroDivisionError', offset=120, starts_line=None, is_jump_target=False), 1058 Instruction(opname='JUMP_IF_NOT_EXC_MATCH', opcode=121, arg=142, argval=142, argrepr='', offset=122, starts_line=None, is_jump_target=False), 1059 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=124, starts_line=None, is_jump_target=False), 1060 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=126, starts_line=None, is_jump_target=False), 1061 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=128, starts_line=None, is_jump_target=False), 1062 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=130, starts_line=23, is_jump_target=False), 1063 Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval='Here we go, here we go, here we go...', argrepr="'Here we go, here we go, here we go...'", offset=132, starts_line=None, is_jump_target=False), 1064 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=134, starts_line=None, is_jump_target=False), 1065 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=136, starts_line=None, is_jump_target=False), 1066 Instruction(opname='POP_EXCEPT', opcode=89, arg=None, argval=None, argrepr='', offset=138, starts_line=None, is_jump_target=False), 1067 Instruction(opname='JUMP_FORWARD', opcode=110, arg=46, argval=188, argrepr='to 188', offset=140, starts_line=None, is_jump_target=False), 1068 Instruction(opname='RERAISE', opcode=48, arg=None, argval=None, argrepr='', offset=142, starts_line=None, is_jump_target=True), 1069 Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='i', argrepr='i', offset=144, starts_line=25, is_jump_target=True), 1070 Instruction(opname='SETUP_WITH', opcode=143, arg=24, argval=172, argrepr='to 172', offset=146, starts_line=None, is_jump_target=False), 1071 Instruction(opname='STORE_FAST', opcode=125, arg=1, argval='dodgy', argrepr='dodgy', offset=148, starts_line=None, is_jump_target=False), 1072 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=150, starts_line=26, is_jump_target=False), 1073 Instruction(opname='LOAD_CONST', opcode=100, arg=9, argval='Never reach this', argrepr="'Never reach this'", offset=152, starts_line=None, is_jump_target=False), 1074 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=154, starts_line=None, is_jump_target=False), 1075 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=156, starts_line=None, is_jump_target=False), 1076 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=158, starts_line=None, is_jump_target=False), 1077 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=160, starts_line=None, is_jump_target=False), 1078 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=162, starts_line=None, is_jump_target=False), 1079 Instruction(opname='DUP_TOP', opcode=4, arg=None, argval=None, argrepr='', offset=164, starts_line=None, is_jump_target=False), 1080 Instruction(opname='CALL_FUNCTION', opcode=131, arg=3, argval=3, argrepr='', offset=166, starts_line=None, is_jump_target=False), 1081 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=168, starts_line=None, is_jump_target=False), 1082 Instruction(opname='JUMP_FORWARD', opcode=110, arg=16, argval=188, argrepr='to 188', offset=170, starts_line=None, is_jump_target=False), 1083 Instruction(opname='WITH_EXCEPT_START', opcode=49, arg=None, argval=None, argrepr='', offset=172, starts_line=None, is_jump_target=True), 1084 Instruction(opname='POP_JUMP_IF_TRUE', opcode=115, arg=178, argval=178, argrepr='', offset=174, starts_line=None, is_jump_target=False), 1085 Instruction(opname='RERAISE', opcode=48, arg=None, argval=None, argrepr='', offset=176, starts_line=None, is_jump_target=False), 1086 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=178, starts_line=None, is_jump_target=True), 1087 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=180, starts_line=None, is_jump_target=False), 1088 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=182, starts_line=None, is_jump_target=False), 1089 Instruction(opname='POP_EXCEPT', opcode=89, arg=None, argval=None, argrepr='', offset=184, starts_line=None, is_jump_target=False), 1090 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=186, starts_line=None, is_jump_target=False), 1091 Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=188, starts_line=None, is_jump_target=True), 1092 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=190, starts_line=28, is_jump_target=False), 1093 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=192, starts_line=None, is_jump_target=False), 1094 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=194, starts_line=None, is_jump_target=False), 1095 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=196, starts_line=None, is_jump_target=False), 1096 Instruction(opname='JUMP_FORWARD', opcode=110, arg=10, argval=210, argrepr='to 210', offset=198, starts_line=None, is_jump_target=False), 1097 Instruction(opname='LOAD_GLOBAL', opcode=116, arg=1, argval='print', argrepr='print', offset=200, starts_line=None, is_jump_target=True), 1098 Instruction(opname='LOAD_CONST', opcode=100, arg=10, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=202, starts_line=None, is_jump_target=False), 1099 Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=204, starts_line=None, is_jump_target=False), 1100 Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=206, starts_line=None, is_jump_target=False), 1101 Instruction(opname='RERAISE', opcode=48, arg=None, argval=None, argrepr='', offset=208, starts_line=None, is_jump_target=False), 1102 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=210, starts_line=None, is_jump_target=True), 1103 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=212, starts_line=None, is_jump_target=False), 1104] 1105 1106# One last piece of inspect fodder to check the default line number handling 1107def simple(): pass 1108expected_opinfo_simple = [ 1109 Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=0, starts_line=simple.__code__.co_firstlineno, is_jump_target=False), 1110 Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=2, starts_line=None, is_jump_target=False) 1111] 1112 1113 1114class InstructionTests(BytecodeTestCase): 1115 1116 def __init__(self, *args): 1117 super().__init__(*args) 1118 self.maxDiff = None 1119 1120 def test_default_first_line(self): 1121 actual = dis.get_instructions(simple) 1122 self.assertEqual(list(actual), expected_opinfo_simple) 1123 1124 def test_first_line_set_to_None(self): 1125 actual = dis.get_instructions(simple, first_line=None) 1126 self.assertEqual(list(actual), expected_opinfo_simple) 1127 1128 def test_outer(self): 1129 actual = dis.get_instructions(outer, first_line=expected_outer_line) 1130 self.assertEqual(list(actual), expected_opinfo_outer) 1131 1132 def test_nested(self): 1133 with captured_stdout(): 1134 f = outer() 1135 actual = dis.get_instructions(f, first_line=expected_f_line) 1136 self.assertEqual(list(actual), expected_opinfo_f) 1137 1138 def test_doubly_nested(self): 1139 with captured_stdout(): 1140 inner = outer()() 1141 actual = dis.get_instructions(inner, first_line=expected_inner_line) 1142 self.assertEqual(list(actual), expected_opinfo_inner) 1143 1144 def test_jumpy(self): 1145 actual = dis.get_instructions(jumpy, first_line=expected_jumpy_line) 1146 self.assertEqual(list(actual), expected_opinfo_jumpy) 1147 1148# get_instructions has its own tests above, so can rely on it to validate 1149# the object oriented API 1150class BytecodeTests(unittest.TestCase): 1151 1152 def test_instantiation(self): 1153 # Test with function, method, code string and code object 1154 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]: 1155 with self.subTest(obj=obj): 1156 b = dis.Bytecode(obj) 1157 self.assertIsInstance(b.codeobj, types.CodeType) 1158 1159 self.assertRaises(TypeError, dis.Bytecode, object()) 1160 1161 def test_iteration(self): 1162 for obj in [_f, _C(1).__init__, "a=1", _f.__code__]: 1163 with self.subTest(obj=obj): 1164 via_object = list(dis.Bytecode(obj)) 1165 via_generator = list(dis.get_instructions(obj)) 1166 self.assertEqual(via_object, via_generator) 1167 1168 def test_explicit_first_line(self): 1169 actual = dis.Bytecode(outer, first_line=expected_outer_line) 1170 self.assertEqual(list(actual), expected_opinfo_outer) 1171 1172 def test_source_line_in_disassembly(self): 1173 # Use the line in the source code 1174 actual = dis.Bytecode(simple).dis() 1175 actual = actual.strip().partition(" ")[0] # extract the line no 1176 expected = str(simple.__code__.co_firstlineno) 1177 self.assertEqual(actual, expected) 1178 # Use an explicit first line number 1179 actual = dis.Bytecode(simple, first_line=350).dis() 1180 actual = actual.strip().partition(" ")[0] # extract the line no 1181 self.assertEqual(actual, "350") 1182 1183 def test_info(self): 1184 self.maxDiff = 1000 1185 for x, expected in CodeInfoTests.test_pairs: 1186 b = dis.Bytecode(x) 1187 self.assertRegex(b.info(), expected) 1188 1189 def test_disassembled(self): 1190 actual = dis.Bytecode(_f).dis() 1191 self.assertEqual(actual, dis_f) 1192 1193 def test_from_traceback(self): 1194 tb = get_tb() 1195 b = dis.Bytecode.from_traceback(tb) 1196 while tb.tb_next: tb = tb.tb_next 1197 1198 self.assertEqual(b.current_offset, tb.tb_lasti) 1199 1200 def test_from_traceback_dis(self): 1201 tb = get_tb() 1202 b = dis.Bytecode.from_traceback(tb) 1203 self.assertEqual(b.dis(), dis_traceback) 1204 1205 1206class TestDisTraceback(unittest.TestCase): 1207 def setUp(self) -> None: 1208 try: # We need to clean up existing tracebacks 1209 del sys.last_traceback 1210 except AttributeError: 1211 pass 1212 return super().setUp() 1213 1214 def get_disassembly(self, tb): 1215 output = io.StringIO() 1216 with contextlib.redirect_stdout(output): 1217 dis.distb(tb) 1218 return output.getvalue() 1219 1220 def test_distb_empty(self): 1221 with self.assertRaises(RuntimeError): 1222 dis.distb() 1223 1224 def test_distb_last_traceback(self): 1225 # We need to have an existing last traceback in `sys`: 1226 tb = get_tb() 1227 sys.last_traceback = tb 1228 1229 self.assertEqual(self.get_disassembly(None), dis_traceback) 1230 1231 def test_distb_explicit_arg(self): 1232 tb = get_tb() 1233 1234 self.assertEqual(self.get_disassembly(tb), dis_traceback) 1235 1236 1237class TestDisTracebackWithFile(TestDisTraceback): 1238 # Run the `distb` tests again, using the file arg instead of print 1239 def get_disassembly(self, tb): 1240 output = io.StringIO() 1241 with contextlib.redirect_stdout(output): 1242 dis.distb(tb, file=output) 1243 return output.getvalue() 1244 1245 1246if __name__ == "__main__": 1247 unittest.main() 1248