Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show source code for dynamically created ("custom") function in IPython?

In an IPython session, I usually define custom functions...problem is, sometimes I want to see the actual code for these functions. So far, I have not been able to find a way to display this. Using ? and ?? simply returns "Dynamically generated function. No source code available." Is there any way to display source code for user-defined functions?

like image 544
K Raphael Avatar asked Apr 18 '12 17:04

K Raphael


People also ask

How do I see the code of a function in Python?

We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.

How to create a function dynamically in Python?

Method 1: exec() The exec() function can take any source code as a string and run it within your script. It's the perfect way to dynamically create a function in Python!

How do you find the max value of a function in Python?

The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.


2 Answers

If you are looking for the source for an interactively-defined function, you can find the most recent definition of it in iPython's history:

[i for (i, l) in  enumerate(_ih) if l.startswith('def foo(')][-1]

Then you can edit that line:

%edit 42

It'll open up Notepad or another text editor with the function definition in it.

Or you can save to a file:

%save foo.py 42
like image 158
kindall Avatar answered Oct 15 '22 05:10

kindall


I am using python 2.7.4 and iPython 0.13.2.

I can see the source of a dynamically created function in iPython using ?? before the function name:

In [8]: ??sort_words
Type:       function
String Form:<function sort_words at 0x189b938>
File:       /tmp/ipython_edit_yc1TIo.py
Definition: sort_words(s)
Source:
def sort_words(s):
    x = re.findall(r'\W+(\w+)', s)
    x.sort()
    for i in x:
        print i

Maybe this is now available in newer versions of iPython? What version are you using?

like image 45
nonbeing Avatar answered Oct 15 '22 07:10

nonbeing