tags:

views:

238

answers:

4

In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python?

(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious).

+7  A: 

If you're using iPython, you can use function_name? to get help, and function_name?? will print out the source, if it can.

Peter
+1, ipython is awesome! You could add a link to it: http://ipython.scipy.org/
orip
+10  A: 

If you are importing the function, you can use inspect.getsource:

>>> import re
>>> import inspect
>>> print inspect.getsource(re.compile)
def compile(pattern, flags=0):
    "Compile a regular expression pattern, returning a pattern object."
    return _compile(pattern, flags)

This will work in the interactive prompt, but apparently only on objects that are imported (not objects defined within the interactive prompt). And of course it will only work if Python can find the source code (so not on built-in objects, C libs, .pyc files, etc)

Triptych
Functions that are created at runtime (including the interactive prompt) don't have a file or linenumber either, which makes sense
gnibbler
That seems to be what I was looking for. Thanks!
Eddie Welker
A: 

You can use the __doc__ keyword:

#print the class description
print string.__doc__
#print function description
print open.__doc__
Am
That's the description, not the definition.
Triptych
for many builtins (as a rule, functions defined in C modules), it includes the function signature as well, but not in general.
kaizer.se
While in the interactive shell "help(object)" will display this in a more navigable way.
TK
@kaizer A function signature is not a definition either. What `__doc__` _actually_ returns is whatever the author of the code put in the doc string (the triple quoted string). Nothing more, nothing less.
Triptych
I think definition is ambiguous here. To me it could mean the docstring or the code text or both or even the code object at a stretch
gnibbler
@Am, if you put backquotes around `__doc__` it will show the underscores instead of making it bold
gnibbler
@gnibbler Python is not ambiguous about what function definitions are: http://docs.python.org/reference/compound_stmts.html#function-definitions
Triptych
to my opinion, the question was about about functional help on functions, inteli-sense kind. if @eddie asked about exact definition, then my answer is irrelevant.
Am
A: 

Take a look at help() function from pydoc module. In interactive mode it should be already imported for you, so just type help(funtion_to_describe). For more capabilities use IPython.

Denis Otkidach