Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reflection - Can I use this to get the source code of a method definition

Duplicate of..

  • How can I get the code of python function?
  • print the code which defined a lambda function
  • Python: How do you get Python to write down the code of a function it has in memory?

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 ?

like image 554
Sathya Murali Avatar asked Apr 22 '09 14:04

Sathya Murali


3 Answers

Use the inspect module:

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

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

like image 159
theller Avatar answered Nov 16 '22 22:11

theller


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

like image 22
Rune Kaagaard Avatar answered Nov 16 '22 22:11

Rune Kaagaard


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.

like image 3
unwind Avatar answered Nov 16 '22 23:11

unwind