Is there a way to display source code for Python function?

Peter Otten __peter__ at web.de
Fri Oct 3 09:47:31 CEST 2014


Viet Nguyen wrote:

> On Thursday, October 2, 2014 10:34:15 PM UTC-7, Viet Nguyen wrote:
>> Hi,
>> 
>> 
>> 
>> When I am debug mode, is there some command which will help display the
>> source code for a Python function of interest?  Much like you'd use "info
>> proc" to display contents of Tcl proc.
>> 
>> 
>> 
>> Thanks,
>> 
>> Viet
> 
> I tried this:
>>>> def func(a):
> ...   a = 'abcd'
> 
> 
>>>> inspect.getsource(func)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/sw/packages/python/current/lib/python2.7/inspect.py", line 701,
>   in getsource
>     lines, lnum = getsourcelines(object)
>   File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690,
>   in getsourcelines
>     lines, lnum = findsource(object)
>   File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538,
>   in findsource
>     raise IOError('could not get source code')
> IOError: could not get source code
> 
>>>> inspect.getsourcelines(func)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690,
>   in getsourcelines
>     lines, lnum = findsource(object)
>   File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538,
>   in findsource
>     raise IOError('could not get source code')
> IOError: could not get source code
> 
> What is wrong?

The source of func is compiled and immediately discarded by the interactive 
interpreter. inspect.getsource() only works if the source code is available 
(as a module):

$ cat ham.py
def spam():
    return 42
$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ham, inspect
>>> print(inspect.getsource(ham.spam))
def spam():
    return 42

>>> 

There is an alternative interactive interpreter called ipython that allows 
you to retrieve a function definition:

In [1]: def foo():
   ...:     return bar
   ...: 

In [2]: %psource foo
def foo():
    return bar

In [3]: 






More information about the Python-list mailing list