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?
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.
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!
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.
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With