3

I have been looking around for some way to convert a function or class or module object in python to a python code object.

A few people accomplish this by doing inspect.getsource() and compile(), but the problem with this is that you are reading a potentially changed file, or if it was composed in the interactive python shell, you will just get an exception on getsource.

I was wondering if anyone else may have a solution to this problem, so it can look something like this:

import dis

def func(arg):
    x = 5
    arg = 3
    return x + arg

code_obj = function_to_code_obj(func)
dis.disassemble(code_obj)

and get the code object disassembly printed out like having created it using compile() or parser.suite()...

1 Answer 1

4

For a function you can use the func_code attribute:

import dis

def func(arg):
    x = 5
    arg = 3
    return x + arg

def function_to_code_obj(func):
    return func.func_code

code_obj = function_to_code_obj(func)
dis.disassemble(code_obj)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this should be good since the module code and class code is just run once... and I can just get the members after execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.