Python dis.Bytecode() Examples

The following are 30 code examples of dis.Bytecode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dis , or try the search function .
Example #1
Source File: mf27.py    From pydeps with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def scan_opcodes_34(self, co):
        i = 0
        bytecode = list(dis.Bytecode(co))
        while i < len(bytecode):
            if (
                bytecode[i].opname == "LOAD_CONST" and
                bytecode[i + 1].opname == "LOAD_CONST" and
                bytecode[i + 2].opname == "IMPORT_NAME"
            ):
                level = bytecode[i].argval
                fromlist = bytecode[i + 1].argval
                import_name = bytecode[i + 2].argval
                if level == 0:
                    yield "absolute_import", (fromlist, import_name)
                else:
                    yield "relative_import", (level, fromlist, import_name)
                i += 2
            i += 1 
Example #2
Source File: async_test.py    From illustrated-python-3-course with MIT License 6 votes vote down vote up
def test_async():
    # Write a coroutine, add2, that accepts two parameters,
    # adds them, then calls ``asyncio.sleep(0)``.
    # Finally it returns the sum.
    # ************************************
    res = await add2(2, 3)
    assert res == 5
    code = dis.Bytecode(add2)
    assert 'sleep' in code.dis()

    # Write a coroutine, avg, that accepts two parameters,
    # ``coroutines`` and ``size``.
    # It loops over coroutines and
    # gets values from them. When
    # it has pulled out size values,
    # it returns the average of those
    # values.
    # (Make sure you put an await call in it)
    # ************************************

    res3 = await avg([add2(1, 3),
                     add2(1, 4),
                     add2(1, 6),
                     ], 2)
    assert res3 == 4.5 
Example #3
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_instantiation(self):
        # Test with function, method, code string and code object
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                b = dis.Bytecode(obj)
                self.assertIsInstance(b.codeobj, types.CodeType)

        self.assertRaises(TypeError, dis.Bytecode, object()) 
Example #4
Source File: injector.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def instructions(code_obj):
    # easy for python 3.4+
    if sys.version_info >= (3, 4):
        for inst in dis.Bytecode(code_obj):
            yield inst
    else:
        # otherwise we have to manually parse
        code = code_obj.co_code
        NewInstruction = namedtuple('Instruction', ('opcode', 'arg'))
        if six.PY2:
            code = map(ord, code)
        i, L = 0, len(code)
        extended_arg = 0
        while i < L:
            op = code[i]
            i+= 1
            if op < opcode.HAVE_ARGUMENT:
                yield NewInstruction(op, None)
                continue
            oparg = code[i] + (code[i+1] << 8) + extended_arg
            extended_arg = 0
            i += 2
            if op == opcode.EXTENDED_ARG:
                extended_arg = oparg << 16
                continue
            yield NewInstruction(op, oparg) 
Example #5
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_instantiation(self):
        # Test with function, method, code string and code object
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                b = dis.Bytecode(obj)
                self.assertIsInstance(b.codeobj, types.CodeType)

        self.assertRaises(TypeError, dis.Bytecode, object()) 
Example #6
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_iteration(self):
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                via_object = list(dis.Bytecode(obj))
                via_generator = list(dis.get_instructions(obj))
                self.assertEqual(via_object, via_generator) 
Example #7
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_explicit_first_line(self):
        actual = dis.Bytecode(outer, first_line=expected_outer_line)
        self.assertEqual(list(actual), expected_opinfo_outer) 
Example #8
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_source_line_in_disassembly(self):
        # Use the line in the source code
        actual = dis.Bytecode(simple).dis()[:3]
        expected = "{:>3}".format(simple.__code__.co_firstlineno)
        self.assertEqual(actual, expected)
        # Use an explicit first line number
        actual = dis.Bytecode(simple, first_line=350).dis()[:3]
        self.assertEqual(actual, "350") 
Example #9
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_info(self):
        self.maxDiff = 1000
        for x, expected in CodeInfoTests.test_pairs:
            b = dis.Bytecode(x)
            self.assertRegex(b.info(), expected) 
Example #10
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_from_traceback(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        while tb.tb_next: tb = tb.tb_next

        self.assertEqual(b.current_offset, tb.tb_lasti) 
Example #11
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_from_traceback_dis(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        self.assertEqual(b.dis(), dis_traceback) 
Example #12
Source File: injector.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def instructions(code_obj):
    # easy for python 3.4+
    if sys.version_info >= (3, 4):
        for inst in dis.Bytecode(code_obj):
            yield inst
    else:
        # otherwise we have to manually parse
        code = code_obj.co_code
        NewInstruction = namedtuple('Instruction', ('opcode', 'arg'))
        if six.PY2:
            code = map(ord, code)
        i, L = 0, len(code)
        extended_arg = 0
        while i < L:
            op = code[i]
            i += 1
            if op < opcode.HAVE_ARGUMENT:
                yield NewInstruction(op, None)
                continue
            oparg = code[i] + (code[i + 1] << 8) + extended_arg
            extended_arg = 0
            i += 2
            if op == opcode.EXTENDED_ARG:
                extended_arg = oparg << 16
                continue
            yield NewInstruction(op, oparg) 
Example #13
Source File: test_collect_bytecode_info.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def debug_test_iter_bytecode(data_regression):
    # Note: not run by default, only to help visualizing bytecode and comparing differences among versions.
    import dis

    basename = 'test_iter_bytecode.py%s%s' % (sys.version_info[:2])
    method_to_info = {}
    for key, method in sorted(dict(globals()).items()):
        if key.startswith('_method'):
            info = []

            if sys.version_info[0] < 3:
                from _pydevd_bundle.pydevd_collect_bytecode_info import _iter_as_bytecode_as_instructions_py2
                iter_in = _iter_as_bytecode_as_instructions_py2(method.__code__)
            else:
                iter_in = dis.Bytecode(method)

            for instruction in iter_in:
                info.append(_create_entry(instruction))

            msg = []
            for d in info:
                line = []
                for k, v in sorted(d.items()):
                    line.append(u'%s=%s' % (k, v))
                msg.append(u'   '.join(line))
            if isinstance(key, bytes):
                key = key.decode('utf-8')
            method_to_info[key] = msg

    data_regression.check(method_to_info, basename=basename) 
Example #14
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_iteration(self):
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                via_object = list(dis.Bytecode(obj))
                via_generator = list(dis.get_instructions(obj))
                self.assertEqual(via_object, via_generator) 
Example #15
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_explicit_first_line(self):
        actual = dis.Bytecode(outer, first_line=expected_outer_line)
        self.assertEqual(list(actual), expected_opinfo_outer) 
Example #16
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_source_line_in_disassembly(self):
        # Use the line in the source code
        actual = dis.Bytecode(simple).dis()
        actual = actual.strip().partition(" ")[0]  # extract the line no
        expected = str(simple.__code__.co_firstlineno)
        self.assertEqual(actual, expected)
        # Use an explicit first line number
        actual = dis.Bytecode(simple, first_line=350).dis()
        actual = actual.strip().partition(" ")[0]  # extract the line no
        self.assertEqual(actual, "350") 
Example #17
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_info(self):
        self.maxDiff = 1000
        for x, expected in CodeInfoTests.test_pairs:
            b = dis.Bytecode(x)
            self.assertRegex(b.info(), expected) 
Example #18
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_from_traceback(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        while tb.tb_next: tb = tb.tb_next

        self.assertEqual(b.current_offset, tb.tb_lasti) 
Example #19
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def test_from_traceback_dis(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        self.assertEqual(b.dis(), dis_traceback) 
Example #20
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_instantiation(self):
        # Test with function, method, code string and code object
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                b = dis.Bytecode(obj)
                self.assertIsInstance(b.codeobj, types.CodeType)

        self.assertRaises(TypeError, dis.Bytecode, object()) 
Example #21
Source File: pydevd_collect_bytecode_info.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def _iter_instructions(co):
    if sys.version_info[0] < 3:
        iter_in = _iter_as_bytecode_as_instructions_py2(co)
    else:
        iter_in = dis.Bytecode(co)
    iter_in = list(iter_in)

    bytecode_to_instruction = {}
    for instruction in iter_in:
        bytecode_to_instruction[instruction.offset] = instruction

    if iter_in:
        for instruction in iter_in:
            yield instruction 
Example #22
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_instantiation(self):
        # Test with function, method, code string and code object
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                b = dis.Bytecode(obj)
                self.assertIsInstance(b.codeobj, types.CodeType)

        self.assertRaises(TypeError, dis.Bytecode, object()) 
Example #23
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_iteration(self):
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                via_object = list(dis.Bytecode(obj))
                via_generator = list(dis.get_instructions(obj))
                self.assertEqual(via_object, via_generator) 
Example #24
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_explicit_first_line(self):
        actual = dis.Bytecode(outer, first_line=expected_outer_line)
        self.assertEqual(list(actual), expected_opinfo_outer) 
Example #25
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_source_line_in_disassembly(self):
        # Use the line in the source code
        actual = dis.Bytecode(simple).dis()[:3]
        expected = "{:>3}".format(simple.__code__.co_firstlineno)
        self.assertEqual(actual, expected)
        # Use an explicit first line number
        actual = dis.Bytecode(simple, first_line=350).dis()[:3]
        self.assertEqual(actual, "350") 
Example #26
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_info(self):
        self.maxDiff = 1000
        for x, expected in CodeInfoTests.test_pairs:
            b = dis.Bytecode(x)
            self.assertRegex(b.info(), expected) 
Example #27
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_from_traceback(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        while tb.tb_next: tb = tb.tb_next

        self.assertEqual(b.current_offset, tb.tb_lasti) 
Example #28
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_from_traceback_dis(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        self.assertEqual(b.dis(), dis_traceback) 
Example #29
Source File: injector.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def instructions(code_obj):
    # easy for python 3.4+
    if sys.version_info >= (3, 4):
        for inst in dis.Bytecode(code_obj):
            yield inst
    else:
        # otherwise we have to manually parse
        code = code_obj.co_code
        NewInstruction = namedtuple('Instruction', ('opcode', 'arg'))
        if six.PY2:
            code = map(ord, code)
        i, L = 0, len(code)
        extended_arg = 0
        while i < L:
            op = code[i]
            i += 1
            if op < opcode.HAVE_ARGUMENT:
                yield NewInstruction(op, None)
                continue
            oparg = code[i] + (code[i + 1] << 8) + extended_arg
            extended_arg = 0
            i += 2
            if op == opcode.EXTENDED_ARG:
                extended_arg = oparg << 16
                continue
            yield NewInstruction(op, oparg) 
Example #30
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_iteration(self):
        for obj in [_f, _C(1).__init__, "a=1", _f.__code__]:
            with self.subTest(obj=obj):
                via_object = list(dis.Bytecode(obj))
                via_generator = list(dis.get_instructions(obj))
                self.assertEqual(via_object, via_generator)