Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print source code of object I defined use %edit magic

Tags:

ipython

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?

like image 904
Honghe.Wu Avatar asked Dec 17 '12 06:12

Honghe.Wu


1 Answers

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.

like image 72
illya Avatar answered Sep 25 '22 17:09

illya