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
addition()and notaddition(self)?inspectis not for Python 2.5 or below; where did you read that? Theinspectmodule is alive and kicking in the latest Python releases.sum()and notsum(x, y)?