1

Possible Duplicate:
Can Python print a function definition?

In Javascript, it is possible to print a function's code as a string?

Example in Javascript:

function thisFunctionPrintsItself(){
    return thisFunctionPrintsItself.toString();
}

Is it possible to do the same in Python?

Community
  • 1
  • 1
Anderson Green
  • 30,230
  • 67
  • 195
  • 328

2 Answers2

3

You can do it, but the result isn't useful since everything is compiled to bytecode first.

def printItself():
    print repr(printItself.func_code.co_code)

You can also use the dis module for disassembly, but the results aren't garuenteed to be portable.

def disassembleItself():
    print __import__('dis').dis(disassembleItself)
Antimony
  • 37,781
  • 10
  • 100
  • 107
1
def foo ():
    import inspect
    return inspect.getsource(foo)

print (foo())

Here, the inspect module reads the source files, so it won't work if they're missing (and just the .pyc or .pyo modules are being used) or the function was compiled on-the-fly, in the interactive interpreter or otherwise.

tjollans
  • 717
  • 4
  • 18