4

I've got a system in which I constantly experiment with the contents of a function, after which I run the program. Since I often have many terminal windows open, I sometimes don't exactly know which version of the function belongs to which terminal window.

Is there a way to print the source code of a specific function to the terminal?

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • 3
    http://stackoverflow.com/questions/777371/python-reflection-can-i-use-this-to-get-the-source-code-of-a-method-definition – Hoopdady Mar 08 '13 at 15:27
  • 3
    Use iPython, then you can just do `func??` to get the source code of any class or function. – Lie Ryan Mar 08 '13 at 15:29
  • @Lie Ryan - Thanks for the suggestion. Unfortunately it is a standalone program I use, which I can't use at the interactive shell. Furthermore, since I constantly change the code I need to know what the code was at runtime ,not sometime before or after that. For this reason, the inspect.getsource() function was exactly what I needed. But thanks for your suggestion anyway! – kramer65 Mar 10 '13 at 07:57

1 Answers1

4

Alright. Thanks to Hoopdady who provided a similar question here on Stackoverflow. Just to give the solution for future readers. I needed to use the inspect module, and using its method "getsource" I can simply print the source of a method or function to the command line.

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

Thanks Hoopdady!

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • While I'd generally agree that `inspect` is a good answer, I'd disagree that you can't get the source code of objects defined in the interpreter. If you use `dill.source.getsource`, you can get the source of functions and lambdas, even if they are defined interactively. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code. See: https://github.com/uqfoundation/dill – Mike McKerns Jan 24 '14 at 18:02