[Tutor] apihelper in dive into python

Peter Otten __peter__ at web.de
Wed Mar 19 10:28:23 CET 2014


Robert.Gutmann at dlr.de wrote:

> Hi guys,
> 
> I've got the following problem: I tried to run the example-program
> apihelper.py in chapter IV of "Dive into Python" and got the following
> error message:
> 
> Define the builtin 'help'.
>     This is a wrapper around pydoc.help (with a twist).
> 
> This is not the Output I expected, however I have no idea how to fix this.
> Anyone an idea?
> 
> I am running a Win7 and Python(x,y) 2.7.5.1
> 
> Thanks for your help!
> Robert

Do you mean the apihelper.py module from 

http://www.diveintopython.net/download/diveintopython-examples-5.4.zip

(comments etc. omitted)?

def info(object, spacing=10, collapse=1):
        """Print methods and doc strings.

        Takes module, class, list, dictionary, or string."""
        methodList = [e for e in dir(object) if callable(getattr(object, 
e))]
        processFunc = collapse and (lambda s: " ".join(s.split())) or 
(lambda s: s)
        print "\n".join(["%s %s" %
                                         (method.ljust(spacing),
                                          processFunc(str(getattr(object, 
method).__doc__)))
                                         for method in methodList])

if __name__ == "__main__":
        print help.__doc__


When you run that as a script it does not invoke the info() function, it 
just prints help.__doc__ which is what you see. However the code on 

http://www.diveintopython.net/power_of_introspection/

differs from the above as it prints info.__doc__ instead of help.__doc__. If 
that's what you expected just change the last line in apihelper.py from

        print help.__doc__

to

        print info.__doc__

With this change the script will print the docstring of the info() function:

$ python apihelper.py
Print methods and doc strings.

        Takes module, class, list, dictionary, or string.


But what apihelper is really meant for is interactive interpreter sessions:

>>> import apihelper
>>> apihelper.info(42)
__abs__    x.__abs__() <==> abs(x)
__add__    x.__add__(y) <==> x+y
__and__    x.__and__(y) <==> x&y
[snip a lot more methods]



More information about the Tutor mailing list