python - Allow help() to work on partial function object -
i'm trying make sure running help() @ python 2.7 repl displays __doc__ function wrapped functools.partial. running help() on functools.partial 'function' displays __doc__ of functools.partial class, not wrapped function's __doc__. there way achieve this?
consider following callables:
def foo(a): """my function""" pass partial_foo = functools.partial(foo, 2) running help(foo) result in showing foo.__doc__. however, running help(partial_foo) results in __doc__ of partial object.
my first approach use functools.update_wrapper correctly replaces partial object's __doc__ foo.__doc__. however, doesn't fix 'problem' because of how pydoc.
i've investigated pydoc code, , issue seems partial_foo partial object not typical function/callable, see this question more information on detail.
by default, pydoc display __doc__ of object type, not instance if object passed determined class inspect.isclass. see render_doc function more information code itself.
so, in scenario above pydoc displaying of type, functools.partial not __doc__ of functools.partial instance.
is there anyway make alter call help() or functools.partial instance that's passed help() display __doc__ of instance, not type?
i found pretty hacky way this. wrote following function override __builtins__.help function:
def partialhelper(object=none): if isinstance(object, functools.partial): return pydoc.help(object.func) else: # preserve ability go interactive if user calls # help() no arguments. if object none: return pydoc.help() else: return pydoc.help(object) then replace in repl with:
__builtins__.help = partialhelper this works , doesn't seem have major downsides, yet. however, there isn't way above naive implementation support still showing __doc__ of some functools.partial objects. it's or nothing, attach attribute wrapped (original) function indicate whether or not original __doc__ should shown. however, in scenario never want this.
note above not work when using ipython , embed functionality. because ipython directly sets shell's namespace references 'real' __builtin__, see code , old mailing list information on why is.
so, after investigation there's way hack ipython. must override site._helper class, used ipython explicitly setup system. following code when called before ipython.embed:
import site site._helper.__call__ = lambda self, *args, **kwargs: partialhelper(*args, **kwargs) are there other downsides i'm missing here?
Comments
Post a Comment