Die inspect
module funktioniert gut zum Abrufen von Quellcode, dies ist nicht auf ältere Python-Versionen beschränkt.
unter Angabe der Quelle zur Verfügung steht (zB die Funktion nicht in C-Code oder dem interaktiven Interpreter definiert ist, oder von einem Modul importiert, für die nur die .pyc
Bytecode Cache verfügbar ist), dann können Sie verwenden:
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
Warum 'Zusatz()' und 'nicht zusätzlich (Selbst-)'? –
'inspect' ist nicht für Python 2.5 oder niedriger; wo hast du das gelesen? Das 'inspect'-Modul ist in den neuesten Python-Versionen lebendig und tritt auf. –
Bearbeitete die Frage. – BlackHat