views:

199

answers:

2

I have a lot of callable objects and they all have the __doc__ string correctly filled out, but running help on them produces the help for the their class instead of help based on __doc__.

What I want to do is change it so that running help on them produces customized help that looks essentially like what you would get if they were actual functions instead of instances of a class that implements __call__.

In code, what I'd like to do is make the output of this:

class myCallable:
    def __init__(self, doc):
        self.__doc__ = doc

    def __call__(self):
        # do some stuff
        pass

myFunc = myCallable("some doco text")
help(myFunc)

Look more like the output of this

def myFunc():
    "some doco text"
    # do some stuff
    pass

help(myFunc)
+1  A: 

I'm not very clear about what your question is exactly. My understanding is that you have a class and a function defined in it and you want to know where Python gets the help text for that function from.

Python gets the help text from the doc strings provided in that class/method.

If you have a class "A" and a method "f" in that class and there are docstrings in the function "f", then the following terminal dump should help clear your question:

>>> class A:
        def __init__(self):
            self.c = 0   # some class variable
        def f(self, x):
            """this is the documentation/help text for the function "f" """
            return x+1

>>> help(A.f)
Help on method f in module __main__:

f(self, x) unbound __main__.A method
this is the documentation/help text for the function "f" 

>>> A.f.__doc__
'this is the documentation/help text for the function "f" '

Hope this helps

inspectorG4dget
+3  A: 

The help function (implemented in the pydoc module) isn't prepared to find per-instance docstrings. I took a quick look through the module to see if there was a way to provide explicit help, but there doesn't seem to be. It uses the inspect module to determine what kind of thing it is, and your myFunc doesn't look like a function, it looks like an instance. So pydoc prints help about the instance's class instead.

It'd be nice if similar to __doc__ you could add a __help__ attribute, but there's no support for that.

I hesitate to suggest it, but your best bet might be to define a new help function:

old_help = help
def help(thing):
    if hasattr(thing, '__help__'):
        print thing.__help__
    else:
        old_help(thing)

and then put a __help__ attribute on your instances:

class myCallable:
    def __init__(self, doc):
        self.__doc__ = doc
        self.__help__ = doc
Ned Batchelder
I hadn't considered that approach, that is an interesting suggestion. The particular program where I care about the help already has a custom console and completer, so custom help is not that surprising and it can be done as part of the custom console code.
tolomea