12

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 ?

Community
  • 1
  • 1
Sathya Murali
  • 149
  • 2
  • 6
  • 3
    You cannot do this. Duplicate: http://stackoverflow.com/questions/427453/how-can-i-get-the-code-of-python-function; http://stackoverflow.com/questions/334851/print-the-code-which-defined-a-lambda-function; http://stackoverflow.com/questions/399991/python-how-do-you-get-python-to-write-down-the-code-of-a-function-it-has-in-memo – S.Lott Apr 22 '09 at 14:10
  • It's Python: you already have the source. – S.Lott Apr 22 '09 at 14:12
  • 3
    I would strongly recommend asking another question with more details. I have the funniest feeling that what you really want to do might only require closures/decorators, but because all you've asked about is print source code (and try to modify it somehow) you're getting disappointing answers. – David Berger Apr 22 '09 at 14:15

4 Answers4

25

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
  • 2,809
  • 19
  • 19
  • 3
    I had to use brackets around everything ie "print(inspect.getsource(mymodule.sayHello))", I think that's a Python3 thing. – AllBecomesGood Jul 22 '19 at 13:01
5

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

Rune Kaagaard
  • 6,643
  • 2
  • 38
  • 29
3

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
  • 391,730
  • 64
  • 469
  • 606
0

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).

Jason Coon
  • 17,601
  • 10
  • 42
  • 50