How to override the doc of an object instance.

Maric Michaud maric at aristote.info
Wed Jun 21 19:27:47 CEST 2006


Le Mercredi 21 Juin 2006 17:00, Paul McGuire a écrit :
> No need to, just assign your special docstrings to w.x.__doc__, and print
> w.x.__doc__.  Instances that have special docstrings will print their
> instance-specific versions; instances without instance-specific docstrings
> will print the class-level version.  See below.

I think this is about to make IPython find the proper docstring of properties 
without modifying existing code.

> >>> z.__doc__  = "instance-level docstring, just for z"
> >>> z.__doc__
>
> 'instance-level docstring, just for z'
>
> >>> zz = W()
> >>> print zz.__doc__
>
> Class-level docstring for W
>
> >>> print z.__doc__
>
> instance-level docstring, just for z

Won't work for properties, as z.prop.__doc__ is in fact z._prop.__doc__, so 
future assignment to prop qil lose the docstring.

Le Mercredi 21 Juin 2006 18:32, David Huard a écrit :
> I looked into the internals of IPython and I can't say I understood much...

This function wil do the job, not roughly tested but seems ok, call it at any 
moment (startup ?) in the IPython shell.

def make_pinfo() :
    """replace the standard magic_pinfo of itpython
    This one will insert __class__. before the last element
    if it is a property."""

    if not hasattr(__IPYTHON__, 'old_pinfo') :
        __IPYTHON__._old_pinfo = __IPYTHON__.magic_pinfo

        def new_pinfo(obj) :
            """obj param is the string typed in the interpreter, ie a.b.c
            it will be evaluated in magic_pinfo"""
             path = obj.split('.')
             if len(path) == 1 :
                 return __IPYTHON__._old_pinfo(obj)
             else :
                 new_eval_string = '.'.join(path[:-1])
                 # get the last attribute by the mean of the __class__ of its 
owner
                 target = __IPYTHON__.user_ns[path[0]] # user_ns is the 
globals of the interpreter
                 for attr in path[1:-1] :
                     target=getattr(target, attr)
                 target = getattr(target.__class__, path[-1], None)

                 if isinstance(target, property) :
                     new_eval_string += '.__class__'
                 return __IPYTHON__._old_pinfo(new_eval_string + '.' + 
path[-1])

        __IPYTHON__.magic_pinfo = new_pinfo

Hope this help.

regards.

-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list