Ejemplo n.º 1
0
 def test_show_code(self):
     self.maxDiff = 1000
     for x, expected in self.test_pairs:
         with captured_stdout() as output:
             dis.show_code(x)
         self.assertRegex(output.getvalue(), expected+"\n")
         output = io.StringIO()
         dis.show_code(x, file=output)
         self.assertRegex(output.getvalue(), expected)
Ejemplo n.º 2
0
 def test_show_code(self):
     self.maxDiff = 1000
     for x, expected in self.test_pairs:
         with captured_stdout() as output:
             dis.show_code(x)
         self.assertRegex(output.getvalue(), expected+"\n")
         output = io.StringIO()
         dis.show_code(x, file=output)
         self.assertRegex(output.getvalue(), expected)
Ejemplo n.º 3
0
def getByteCode():
    #https://docs.python.org/3.7/library/dis.html#analysis-functions
    dis.dis( test ) 
    print('-'*25)
    dis.code_info( test )
    print('-'*25)
    dis.show_code( test )
    print('-'*25)    
    # dis.disco( test )
    print('-'*25)    
    dis.get_instructions( test )
Ejemplo n.º 4
0
def show_code(code: types.CodeType, f, contains=()):
    if code in contains:
        return

    f.write('\n\n\n')
    f.write(code.co_name)
    f.write(':\n\n')
    dis.show_code(code, file=f)
    for each in code.co_consts:
        if isinstance(each, types.CodeType):
            show_code(each, f, (*contains, code))
Ejemplo n.º 5
0
	return name

print("help(method) : ")
print(str(help(method)) + "\n")

print("method.__doc__ : ")
print(method.__doc__ + "\n")

print("method.__name__ : ")
print(method.__name__ + "\n")

print("method.__code__ : ")
print(str(method.__code__) + "\n")

print("dis.show_code(method) : ")
print(str(dis.show_code(method)) + "\n")

class A(): pass

class Base(A):
	"""
	document there
	"""
	name="nick"
	__secret="123456"
	def __repr__():
		return name
	def say_hello(name):
		print("hello," + name)
	def _secret_method():
		return __secret__
Ejemplo n.º 6
0
 def test_show_code(self):
     self.maxDiff = 1000
     for x, expected in self.test_pairs:
         with captured_stdout() as output:
             dis.show_code(x)
         self.assertRegexpMatches(output.getvalue(), expected+"\n")
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'MyObject({})'.format(self.name)


def f(*args):
    nargs = len(args)
    print(nargs, args)


if __name__ == '__main__':
    from dis import dis
    from dis import show_code
    print("***dis function(f)***")
    dis(f)
    print('-' * 25)
    print("***dis function(f) show code***")
    show_code(f)
    print('-' * 25)
    print("***dis class(MyObject)***")
    dis(MyObject)
    print('-' * 25)
    print("***show code***")
    code = """
my_dict = {'a':1}
    """
    show_code(code)
Ejemplo n.º 8
0
 13          82 JUMP_ABSOLUTE           22

 14     >>   84 POP_TOP
             86 RETURN_VALUE
"""
    m = 1 << (n.bit_length() - 1)
    Fn = 0
    Fnm1 = 1
    while m:
        Fn2 = Fn * Fn
        Fn = 2 * Fnm1 * Fn + Fn2
        Fnm1 = Fnm1 * Fnm1 + Fn2
        if n & m:
            Fnm1, Fn = Fn, Fnm1 + Fn
        m >>= 1
    return Fn


fibonacci_optimized = assemble(fibonacci)

if __name__ == "__main__":
    n = int(argv[1]) if len(argv) > 1 else 12
    show_code(fibonacci_optimized)
    dis(fibonacci_optimized)

    py = timeit("f(n)", globals=dict(n=n, f=fibonacci))
    bc = timeit("f(n)", globals=dict(n=n, f=fibonacci_optimized))

    print("python =", py, "bytecode =", bc, "bytecode/python =", bc / py)
Ejemplo n.º 9
0
 def update_event(self, inp=-1):
     self.set_output_val(0, dis.show_code(self.input(0)))
Ejemplo n.º 10
0
        if _closure is None:
            _closure = ()
        new_func = FunctionType(self.code, self.global_env, _name,
                                tuple(_argdef), _closure)
        #prettyCode(self.code)
        return new_func


#help(FunctionType)
@FAST(a=1)
def func(b):
    return a + b


print(func(1))
dis.show_code(func)


@FAST(lst=list(range(995)), acc=0)
def Sum():
    if lst == []:
        return acc
    return Sum(lst=lst[1:], acc=acc + lst[0])


from types import GeneratorType


def force(g):
    while isinstance(g, GeneratorType):
        g = next(g)
Ejemplo n.º 11
0
import dis


def hello():
    print("Hello, World!")


dis.dis(hello)

dis.show_code(hello)

print(hello.__code__)

print(hello.__code__.co_code)

print(list(hello.__code__.co_code))
Ejemplo n.º 12
0
import dis

code = """ 
my_dict = {'name': 'Alex'}
"""

print('Disassembly:\n')
dis.dis(code)

print('\nCode Details:\n')
dis.show_code(code)
Ejemplo n.º 13
0
# dis_string.py

import dis

code = """
my_dict = {'a': 1}
"""

print('Disassemblato:\n')
dis.dis(code)

print('\nDettagli codice:\n')
dis.show_code(code)
Ejemplo n.º 14
0
def disassemble(obj, verbose=False):
    if verbose:
        show_code(obj)
        print("Disassembly:")
    dis(obj)
Ejemplo n.º 15
0
            op)
        for op, name in enumerate(opname)
    })

if __name__ == "__main__":
    from dis import dis, show_code

    inner = (
        CodeBuilder().load_deref("y").load_fast("z").inplace_add().store_deref(
            "y").load_deref("y").load_fast("z").binary_add().return_value())

    code = (CodeBuilder().load_fast("x").store_deref("y").load_closure(
        "y").build_tuple(1).load_const(inner.ascode(
            "inner", 1)).load_const("func.<locals>.inner").make_function(
                int(MakeFunctionFlags.CLOSURE)).store_fast("inner").load_fast(
                    "inner").return_value())

    def func(x):
        y = x

        def inner(z):
            nonlocal y
            y += z
            return y + z

        return inner

    dis(func)
    show_code(code.ascode("func", 1))
    show_code(func)
Ejemplo n.º 16
0
    print(" --------start------- ")
    for i in dir(co):
        if i.startswith('co'):
            t = getattr(co, i)
            print('  ', repr(t), '\t: (', i, ':', type(t).__name__, ')')
    print(" ---------end--------- ")


code = compile('lambda x:x', '<string>', 'exec')
lamc = code.co_consts[0]
showCodeInfo(code)
dis.dis(code)
showCodeInfo(lamc)
dis.dis(lamc)

dis.show_code(code)
dis.show_code(lamc)

# inspect.CO_OPTIMIZED             1
# inspect.CO_NEWLOCALS             2
# inspect.CO_VARARGS               4
# inspect.CO_VARKEYWORDS           8
# inspect.CO_NESTED               16
# inspect.CO_GENERATOR            32
# inspect.CO_NOFREE               64
# inspect.CO_COROUTINE           128
# inspect.CO_ITERABLE_COROUTINE  256
# inspect.CO_ASYNC_GENERATOR     512


def parseCo_Flags(num):
Ejemplo n.º 17
0
 def print(code):
     dis.show_code(code)
     for ins in dis.get_instructions(code):
         print(ins)
Ejemplo n.º 18
0
#!/usr/bin/env python3
# encoding: utf-8


def f(*args):
    nargs = len(args)
    print(nargs, args)


if __name__ == '__main__':
    import dis
    dis.show_code(f)
Ejemplo n.º 19
0
    # repeat 2nip drop
    m = 1 << (n.bit_length() - 1)
    Fn = 0
    Fnm1 = 1
    while m:
        Fn2 = Fn * Fn
        Fn = 2 * Fnm1 * Fn2 + Fn2
        Fnm1 = Fnm1 * Fnm1 + Fn2
        if n & m:
            Fnm1, Fn = Fn, Fnm1 + Fn
        m >>= 1
    return Fn


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("n", type=int, help="which Fibonacci number")
    parser.add_argument("--fast", dest="func", action="store_const",
                        const=fast_fib, default=fib)
    args = parser.parse_args()

    python = args.func
    forth = ForthCompiler().compile(python)
    show_code(forth)
    dis(forth)

    p = timeit("f(n)", globals=dict(n=args.n, f=python))
    f = timeit("f(n)", globals=dict(n=args.n, f=forth))

    print("python =", p, "forth =", f, "forth/python =", f / p)
Ejemplo n.º 20
0
#
def rec1(x):
    if x is 0:
        return 0
    return rec1(x - 1) + x


#
#
def rec2(x):
    def apply(y):
        if x is 0:
            return True, y
        return False, (x + y, scheduler((x - 1, rec2)))

    return True, apply


import dis
dis.show_code(scheduler)
dis.show_code(schd)

#
#
# print(scheduler((0, scheduler((500, rec2)))))
print(timeit('rec1(500)', globals=globals(), number=500))
print(
    timeit('scheduler((0, scheduler((500, rec2))))',
           globals=globals(),
           number=500))
Ejemplo n.º 21
0
import dis

def fib(n):
    r = [0, 1]
    if n < 2:
        return r[n]
    else:
        for i in range(2, n + 1):
            r.append(r[i-1] + r[i-2])
        return r[n]

# print(fib(3))

if __name__ == "__main__":
    dis.dis(fib)
    dis.show_code(fib)
Ejemplo n.º 22
0
Archivo: vm.py Proyecto: AAorris/codon
        loop:
            LOAD_FAST 2  # x
            LOAD_CONST 1  # 1
            INPLACE_ADD  # (x + 1)
            STORE_FAST 2  # x

            # yield slope * x + offset
            LOAD_FAST 0  # slope
            LOAD_FAST 2  # x
            BINARY_MULTIPLY  # (slope * x)
            LOAD_FAST 1  # offset
            BINARY_ADD  # (+ offset)
            YIELD_VALUE  # y = mx + b
            POP_TOP  # pop y
        JUMP_ABSOLUTE loop
    ''', {
        'name': 'line',
        'stacksize': 2,
        'argcount': 2,
        'localcount': 1,
        'varnames': ('slope', 'offset', 'x'),
        'constants': (0, 1),
        'flags': FLAGS['generator']
    })
    print(dis.dis(line))
    print(dis.show_code(line))
    path = line(2, 5)
    y = next(path)
    print(y)
Ejemplo n.º 23
0
def disassemble(obj, verbose=False):
    if verbose:
        show_code(obj)
        print("Disassembly:")
    dis(obj)
Ejemplo n.º 24
0
            self.filename,  # filename
            self.name,  # name
            self.firstlineno,  # firstlineno
            self.lnotab,  # lnotab
            self.freevars,  # freevars
            self.cellvars,  # cellvars
        )
        return code


co = Instruction()
co.consts = (2, None)
co.code = [opmap["LOAD_CONST"], 0]
co = co.build()
dis.dis(co)
dis.show_code(co)

co2 = Instruction()
co2.consts = (1, None)
co2.freevars = ('a', )
co2.stacksize = 1
co2.flags = 19
co2.code = [opmap["LOAD_DEREF"], 0]
co2 = co2.build()

co1 = Instruction()
co1.consts = (233, '<lambda>', co2)
co1.cellvars = ('a', )
co1.stacksize = 3
co1.flags = 3
co1.nlocals = 1
Ejemplo n.º 25
0
import dis


def my_gen():
    yield 1
    yield 2
    yield 3


print(my_gen())

# The use of "yield" turns a regular function into a generator function.
# When python compiles your function, it notices the "yield" and tags the function as a generator function.
# Running a "generator function" returns a "generator".

dis.show_code(my_gen)

# show_code() is a function that summarizes all the hints that python leaves for itself in the function object.

g = my_gen()

print(g)
print(iter(g))  # generator is its own iterator (manual way)
#!/usr/bin/python3
import dis
# import marshal
import hidden_4

# marshal.load(hidden_4)

# dis.dis(hidden_4)
# bytecode = dis.Bytecode(hidden_4)
# for instr in bytecode:
#     print(instr.opname)

dis.show_code(hidden_4)