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

In an IPython session, I usually define custom functions ... The problem is that sometimes I want to see the actual code for these functions. So far, I have not been able to find a way to show this. Through? and?? just returns "Dynamically generated function. Source code unavailable." Is there a way to show the source code for custom functions?

+7
source share
4 answers

Try to find the story:

In [22]: for l in _ih: ....: if l.startswith('def f'): ....: print l ....: ....: def f(): a= 1 b = 2 return a*b 

although it is very simple, the best version will analyze / run the history and see if you can return the function

+2
source

If you are looking for a source for an interactively defined function, you can find the latest definition of this in iPython history:

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

Then you can edit this line:

 %edit 42 

It will open Notepad or another text editor with the definition of the function in it.

Or you can save the file:

 %save foo.py 42 
+2
source

I am using python 2.7.4 and iPython 0.13.2.

Can I 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 now it is available in newer versions of iPython? Which version are you using?

+2
source

Errors in IPython are considered dynamically generated if:

  • they are metaprogrammed - they are created by another function. in this case, ther is not source code, it simply does not exist.

  • they refer to another namespace in which they were created, and there is no information about what namespace originally was. In this case, find out where they came from and what they started? from there.

0
source

All Articles