Display Function Code Body?

Fernando Perez fperez.net at gmail.com
Sun Jan 9 05:39:20 EST 2005


Haibao Tang wrote:

> 
> Hail Python pals! I played with the R (http://r-project.cran.org) last
> night to do some statistics and it has an interactive session too, and
> I found a feature that is quite useful.

[...]

> # or any shallow function code from a file
>>>> import calendar; disp(calendar.isleap)
> <function isleap at 0x00F795B0>
> def isleap(year):
> """Return 1 for leap years, 0 for non-leap years."""
> return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
> <environment: C:\Python23\Lib\calendar.py>
> 
> # surely the compiled function code cannot be displayed
>>>> disp(blabla)
> <function isleap at 0x00F79B30>
> : internal/compiled function
> <environment: C:\Python23\DLLs\_blabla.pyd>
> 
> Can someone please point out how this can be achieved nicely. I've
> tried some text searching approach, too dirty I must say.
> Oh! Thank you ...

[~/tmp]> ipython
Python 2.3.4 (#1, Oct 26 2004, 16:42:40)
Type "copyright", "credits" or "license" for more information.

IPython 0.6.7_rc1 -- An enhanced Interactive Python.
?       -> Introduction to IPython's features.
%magic  -> Information about IPython's 'magic' % functions.
help    -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import calendar

In [2]: calendar.isleap??
Type:           function
Base Class:     <type 'function'>
String Form:    <function isleap at 0x403bb6bc>
Namespace:      Interactive
File:           /usr/src/build/475206-i386/install/usr/lib/python2.3/calendar.py
Definition:     calendar.isleap(year)
Source:
def isleap(year):
    """Return 1 for leap years, 0 for non-leap years."""
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


Note that the source display won't work for interactively defined functions,
because their source is thrown away by the bytecode compiler.  There are
discussions of a PEP for adding a __source__ attribute to functions which would
solve this limitation, but that is still in the future.

Cheers,

f




More information about the Python-list mailing list