how to print source code of object I defined use

2020-08-12 18:17发布

问题:

Ipython 0.13.1 can print the source of an object from python library,
such as, os.path.abspath??
But I can't print the source code of any object I defined through %ed magic in ipython,
Is anything wrong I did?
such as, I define a class Name through %ed magic:

%ed  

then

class Name(object):
    """docstring for Name"""
    name = 'hong'
    def __init__(self, arg):
        super(Name, self).__init__()
        self.arg = arg
    def pri():
        print 'class Name'

when back to ipython, I can't see the source code of class Name:

In [59]: Name??
Type:       type
String Form:<class '__main__.Name'>
Docstring:  docstring for Name
Constructor information:
Definition:Name(self, arg)

Is this the bug of IPython?

回答1:

--Edits after OP mentioned this is seen in ipython iteself.

Is there any error message you get after typying %ed myfunc? Pasting that might help others find the issue.

---update:

I also get a short version of the source code when I try Name??, but Name.pri?? gives me the full source code of the pri() member function of the Name class. So ipython may have some convention to not give full source code of classes.

Here is my interaction:

    In [2]: Name??
    Type:       type
    String Form:<class '__main__.Name'>
    Docstring:  docstring for Name
    Constructor information:
     Definition:Name(self, arg)

    In [3]: Name.pri??
    Type:       instancemethod
    String Form:<unbound method Name.pri>
    File:       /tmp/ipython_edit_8YOfN9.py
    Definition: Name.pri()
    Source:
        def pri():
            print 'class Name'

    In [4]:


回答2:

Recent versions of IPython (not sure of the exact version number) actually do show the source:

IPython 0.13 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: %ed
IPython will make a temporary file named: /var/folders/88/zgy_z51x1fn2mp_7vmkj3phm0000gn/T/ipython_edit_g9xYY4.py
Editing... done. Executing edited code...
Out[1]: 'def f(a):\n\treturn a + 3\n'

In [2]: f(4)
Out[2]: 7

In [3]: f??
Type:       function
String Form:<function f at 0x18ddb30>
File:       /var/folders/88/zgy_z51x1fn2mp_7vmkj3phm0000gn/T/ipython_edit_g9xYY4.py
Definition: f(a)
Source:
def f(a):
        return a + 3

There are two other ways to get the source. One is if you can go back to the line where you called %ed, the return value should be the source code (here, this is Out[1], so you could do print Out[1]). Another is to call %ed f — this is supposed to load up the current definition of f into the editor, and allow you to edit the definition.



标签: ipython