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?

1
  • @olly_uk I have tried it in Javascript, but not in Python. Commented Aug 12, 2012 at 20:45

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

This is what I got for the first function output: 't\x00\x00t\x01\x00j\x02\x00j\x03\x00\x83\x01\x00GHd\x00\x00S'
@Anderson - exactly, it's compiled to bytecode.
Is it possible to actually print the function's source code, as in Javascript?
Wait... the other answer explains this. :)
It's possible in some cases, but only if the source is available. Also, it won't work if the definition is changed at run time.
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.

2 Comments

Is it possible to write a function that can take another function as a parameter, and then print the function's source?
That's exactly what inspect.getsource does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.