Is it possible to output the content of a user-defined function as a string (not the enumeration, but just the function call):
Function:
def sum(x,y):
return x+y
Function content as a string:
"sum(), return x+y"
The inspect function might have worked but it seems to be for just python 2.5 and below?
The inspect
module works just fine for retrieving source code, this is not limited to older Python versions.
Provided the source is available (e.g. the function is not defined in C code or the interactive interpreter, or was imported from a module for which only the .pyc
bytecode cache is available), then you can use:
import inspect
import re
import textwrap
def function_description(f):
# remove the `def` statement.
source = inspect.getsource(f).partition(':')[-1]
first, _, rest = source.partition('\n')
if not first.strip(): # only whitespace left, so not a one-liner
source = rest
return "{}(), {}".format(
f.__name__,
textwrap.dedent(source))
Demo:
>>> print open('demo.py').read() # show source code
def sum(x, y):
return x + y
def mean(x, y): return sum(x, y) / 2
def factorial(x):
product = 1
for i in xrange(1, x + 1):
product *= i
return product
>>> from demo import sum, mean, factorial
>>> print function_description(sum)
sum(), return x + y
>>> print function_description(mean)
mean(), return sum(x, y) / 2
>>> print function_description(factorial)
factorial(), product = 1
for i in xrange(1, x + 1):
product *= i
return product