Duplicate of..
I have a method definition which is successfully running, but would like to modify it in runtime.
for eg: If i have a method
def sayHello():
print "Hello"
type(sayHello) gives me the answer 'type function'. Will I able to get the source code string of this function object. Is it considered a security issue ?
Use the inspect module:
import inspect
import mymodule
print inspect.getsource(mymodule.sayHello)
The function must be defined in a module that you import.
To get the source of a method on a class instance do:
import inspect
myobj = MyModel()
print inspect.getsource(myobj.my_method)
Read more: https://docs.python.org/2/library/inspect.html#inspect.getsource
sayHello.func_code.co_code
returns a string that I think contains the compiled code of the method. Since Python is internally compiling the code to virtual machine bytecode, this might be all that's left.
You can disassemble it, though:
import dis
def sayHello():
print "hello"
dis.dis(sayHello)
This prints:
1 0 LOAD_CONST 1 ('hello') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE
Have a look at Decompyle for a de-compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With