views:

631

answers:

4

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 ?

A: 

You will not be able to get the source code.

This is not a security issue.

In fact, this is not reflection at all.

Yuval A
+1  A: 

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.

unwind
A: 

There is not a built-in function to get source code of a function, however, you could build you own if you have access to the source-code (it would be in your Python/lib directory).

jcoon
+3  A: 

Use the inspect module:

import inspect
import mymodule
print inspect.getsource(mymodule.sayHello)

The function must be defined in a module that you import.

theller