Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Python print a function definition?

Tags:

python

People also ask

Can you print a function in Python?

Print FunctionThe Python print() function takes in any number of parameters, and prints them out on one line of text.

How do you find the definition of a function?

To go to the definition of a function or object, select or place the cursor anywhere in the function name or object variable name, and then do one of the following: On the View menu, choose Go To Definition.

How do you find the information of a function in Python?

Python help() function is used to get the documentation of specified module, class, function, variables etc. This method is generally used with python interpreter console to get details about python objects.


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)


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


This is the way I figured out how to do it:

    import inspect as i
    import sys
    sys.stdout.write(i.getsource(MyFunction))

This takes out the new line characters and prints the function out nicely


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 from dill, 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.

>>> from dill.source import getsource
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> squared = lambda x:x**2
>>> 
>>> print getsource(add)
def add(x,y):
  return x+y

>>> print getsource(squared)
squared = lambda x:x**2

>>> 
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
... 
>>> f = Foo()
>>> 
>>> print getsource(f.bar)
def bar(self, x):
    return x*x+x

>>> 

Use help(function) to get the function description.

You can read more about help() here.