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?
4 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
1 Comment
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?
1 Comment
Fumctions in IPython are considered dynamically generated if:
they are metaprogrammed - they are created by another function. in this case ther is no source code, it simply does not exist.
they are referenced in a different namespace to which they were created and there is no information as to what namespace they are originally in. in this case find out where they originally were and run ?? from there.
1 Comment
?? the code of functions created inside another function (def f(): def g():… return g).
def blah(d,b): return (d >10 and b <10)(Interactively-defined would have been better, sorry)f??works on interactively defined functions.