Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display function definition in interactive shell

Tags:

python

shell

I am working in the Python Interactive Shell (ActiveState ActivePython 2.6.4 under Windows XP). I created a function that does what I want. However, I've cleared the screen so I can't go back and look at the function definition. It is also a multiline function so the up arrow to redisplay lines is of minimal value. Is there anyway to return the actual code of the function? There are "code" and "func_code" attributes displayed by dir(), but I don't know if they contain what I need.

like image 828
Count Boxer Avatar asked Feb 03 '10 15:02

Count Boxer


1 Answers

It has been a pretty long time but may someone need it. getsource gives the source code:

>>> def sum(a, b, c):
...  # sum of three number
...  return a+b+c
...
>>> from dill.source import getsource
>>>
>>> getsource(sum)
'def sum(a, b, c):\n # sum of three number\n return a+b+c\n'

to install dill run pip install dill. To get it formatted:

>>> fun = getsource(sum).replace("\t", " ").split("\n")
>>> for line in fun:
...  print line
...
def sum(a, b, c):
 # sum of three number
 return a+b+c
like image 77
Mesut GUNES Avatar answered Nov 15 '22 17:11

Mesut GUNES