[Tutor] repr()

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jun 7 23:04:08 CEST 2005



On Tue, 7 Jun 2005, Bernard Lebel wrote:

> The real question is, then, is there a way I can print the code of a
> function as a string? Something like....
>
> 'def myFunction: print "hello"'

Hi Bernard,


Ah, ok.  You can use 'inspect':

    http://www.python.org/doc/lib/inspect-source.html

For example:

######
>>> import heapq
>>> import inspect
>>> print inspect.getsource(heapq.heappop)
def heappop(heap):
    """Pop the smallest item off the heap, maintaining the heap
invariant."""
    lastelt = heap.pop()    # raises appropriate IndexError if heap is
empty
    if heap:
        returnitem = heap[0]
        heap[0] = lastelt
        _siftup(heap, 0)
    else:
        returnitem = lastelt
    return returnitem
######


It doesn't always work: it'll work only if the function is a pure-Python
function that's defined in a file that Python can find, since functions
themselves don't carry their own textual representation around.

Functions do contain the file name as well as their corresponding line
numbers:

######
>>> heapq.__file__
'/usr/lib/python2.3/heapq.pyc'
>>> heapq.heappop.func_code.co_firstlineno
136
######

which is sorta how inspect.getsource() works.


Best of wishes!



More information about the Tutor mailing list