[Doc-SIG] pydoc.py: new help feature

Ka-Ping Yee ping@lfw.org
Fri, 13 Apr 2001 06:25:56 -0700 (PDT)


As well as fixes to pydoc which i have just checked in (the
module actually got *smaller* this time!) i have also spent a
good portion of the evening rewriting the Helper class in
pydoc to try to do a better job of providing help.

I haven't yet committed a version containing this new feature
(though i was quite tempted!) as it would be irresponsible of
me to check in such a big change the day before a deadline
without at least asking first.

I know my timing is really terrible, but i would like you to
have a look at it.  I think the help utility is in fairly good
shape.  Please try it out if you have time, and consider the
possibility of allowing it into 2.1.  The fancy version is at

    http://www.lfw.org/python/pydoc.py

Aside from a big chunk of new code for the Helper class, it is
otherwise the same as the version currently in CVS.

*** In particular, i'm also looking for any suggestions about
how to make Helper.__init__ more robust at finding the docs. ***

If you really like it, we could even think about adding a few
lines to site.py:

    class Helper:
        def __repr__(self):
            import pydoc
            pydoc.help()
            return ''
        def __call__(self, *args):
            import pydoc
            pydoc.help(*args)
    __builtin__.help = Helper()

I know that's pushing it, but hey, i thought it wouldn't hurt
to ask. :)


-- ?!ng


Here follows a transcript of a session, to show you some examples.
I've inserted marks like this: ##1## to refer to commentary at the bottom.


skuld[1052]% python
Python 2.1b2 (#29, Apr 10 2001, 04:59:40) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> from pydoc import help
>>> help

Welcome to Python 2.1!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> topics                                                ##1##

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DELETION            LOOPING             SEQUENCEMETHODS2
ASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SEQUENCES
ATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SHIFTING
ATTRIBUTES          ELLIPSIS            METHODS             SLICINGS
AUGMENTEDASSIGNMENT EXCEPTIONS          MODULES             SPECIALATTRIBUTES
BACKQUOTES          EXECUTION           NAMESPACES          SPECIALIDENTIFIERS
BASICMETHODS        EXPRESSIONS         NONE                SPECIALMETHODS
BINARY              FILES               NUMBERMETHODS       STRINGMETHODS
BITWISE             FLOAT               NUMBERS             STRINGS
BOOLEAN             FORMATTING          OBJECTS             SUBSCRIPTS
CALLABLEMETHODS     FRAMEOBJECTS        OPERATORS           TRACEBACKS
CALLS               FRAMES              PACKAGES            TRUTHVALUE
CLASSES             FUNCTIONS           POWER               TUPLELITERALS
CODEOBJECTS         IDENTIFIERS         PRECEDENCE          TUPLES
COERCIONS           IMPORTING           PRINTING            TYPEOBJECTS
COMPARISON          INTEGER             PRIVATENAMES        TYPES
COMPLEX             LISTLITERALS        RETURNING           UNARY
CONDITIONAL         LISTS               SCOPING             UNICODE
CONVERSIONS         LITERALS            SEQUENCEMETHODS1    

help> LISTS                                                 ##2##
  2.1.5.4 Mutable Sequence Types
  
  List objects support additional operations that allow in-place
  modification of the object. These operations would be supported by other
  mutable sequence types (when added to the language) as well. Strings and
  tuples are immutable sequence types and such objects cannot be modified
  once created. The following operations are defined on mutable sequence
  types (where x is an arbitrary object):
  
        Operation        Result          Notes 
        s[i] = x         item i of s is replaced by x     
        s[i:j] = t       slice of s from i to j is replaced by t          
        del s[i:j]       same as s[i:j] = []      
        s.append(x)      same as s[len(s):len(s)] = [x]  (1)
        s.extend(x)      same as s[len(s):len(s)] = x    (2)
        s.count(x)       return number of i's for which s[i] == x         
        s.index(x)       return smallest i such that s[i] == x   (3)
        s.insert(i, x)   same as s[i:i] = [x] if i >= 0   
        s.pop([i])       same as x = s[i]; del s[i]; return x    (4)
        s.remove(x)      same as del s[s.index(x)]       (3)
        s.reverse()      reverses the items of s in place        (5)
        s.sort([cmpfunc])        sort the items of s in place    (5), (6)
  
  Notes:
  
  (1)
  The C implementation of Python has historically accepted multiple
  parameters and implicitly joined them into a tuple; this no longer works
  in Python 2.0. Use of this misfeature has been deprecated since Python
  1.4.
  
  (2)
  Raises an exception when x is not a list object. The extend() method is
  experimental and not supported by mutable sequence types other than
  lists.
  
  (3)
  Raises ValueError when x is not found in s.
  
  (4)
  The pop() method is only supported by the list and array types. The
  optional argument i defaults to -1, so that by default the last item is
  removed and returned.
  
  (5)
  The sort() and reverse() methods modify the list in place for economy of
  space when sorting or reversing a large list. They don't return the
  sorted or reversed list to remind you of this side effect.
  
  (6)
  The sort() method takes an optional argument specifying a comparison
  function of two arguments (list items) which should return -1, 0 or 1
  depending on whether the first argument is considered smaller than,
  equal to, or larger than the second argument. Note that this slows the
  sorting process down considerably; e.g. to sort a list in reverse order
  it is much faster to use calls to the methods sort() and reverse() than
  to use the built-in function sort() with a comparison function that
  reverses the ordering of the elements.

Related help topics: LISTLITERALS

help> LISTLITERALS                                          ##3##
  5.2.4 List displays
  
  A list display is a possibly empty series of expressions enclosed in
  square brackets:
  
  
  list_display:   "[" [listmaker] "]"
  listmaker:   expression ( list_for | ( "," expression)* [","] )
  list_iter:   list_for | list_if
  list_for:    "for" expression_list "in" testlist [list_iter]
  list_if:     "if" test [list_iter]
  
  A list display yields a new list object. Its contents are specified by
  providing either a list of expressions or a list comprehension. When a
  comma-separated list of expressions is supplied, its elements are
  evaluated from left to right and placed into the list object in that
  order. When a list comprehension is supplied, it consists of a single
  expression followed by at least one for clause and zero or more for or
  if clauses. In this case, the elements of the new list are those that
  would be produced by considering each of the for or if clauses a block,
  nesting from left to right, and evaluating the expression to produce a
  list element each time the innermost block is reached.

Related help topics: LITERALS

help> LITERALS                                              ##4##
  5.2.2 Literals
  
  Python supports string literals and various numeric literals:
  
  
  literal: stringliteral | integer | longinteger | floatnumber | imagnumber
  
  Evaluation of a literal yields an object of the given type (string,
  integer, long integer, floating point number, complex number) with the
  given value. The value may be approximated in the case of floating point
  and imaginary (complex) literals. See section 2.4[1] for details.
  
  All literals correspond to immutable data types, and hence the object's
  identity is less important than its value. Multiple evaluations of
  literals with the same value (either the same occurrence in the program
  text or a different occurrence) may obtain the same object or a
  different object with the same value.

Related help topics: STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS

help> NUMBERS
  2.4.3 Numeric literals
  
  There are four types of numeric literals: plain integers, long integers,
  floating point numbers, and imaginary numbers. There are no complex
  literals (complex numbers can be formed by adding a real number and an
  imaginary number).
  
  Note that numeric literals do not include a sign; a phrase like -1 is
  actually an expression composed of the unary operator `-' and the
  literal 1.

Related help topics: INTEGER FLOAT COMPLEX TYPES

help> keywords                                              ##5##

Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 elif                global              or
assert              else                if                  pass
break               except              import              print
class               exec                in                  raise
continue            finally             is                  return
def                 for                 lambda              try
del                 from                not                 while

help> if                                                    ##6##
  7.1 The if statement
  
  The if statement is used for conditional execution:
  
  
  if_stmt:        "if" expression ":" suite
                 ("elif" expression ":" suite)*
                 ["else" ":" suite]
  
  It selects exactly one of the suites by evaluating the expressions one
  by one until one is found to be true (see section 5.10[1] for the
  definition of true and false); then that suite is executed (and no other
  part of the if statement is executed or evaluated). If all expressions
  are false, the suite of the else clause, if present, is executed.

Related help topics: TRUTHVALUE

help> TRUTHVALUE
  2.1.1 Truth Value Testing
  
  Any object can be tested for truth value, for use in an if or while
  condition or as operand of the Boolean operations below. The following
  values are considered false:
  
  None
  
  zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  
  any empty sequence, for example, '', (), [].
  
  any empty mapping, for example, {}.
  
  instances of user-defined classes, if the class defines a __nonzero__()
  or __len__() method, when that method returns zero.2.2[1]
  
  All other values are considered true -- so objects of many types are
  always true.
  
  Operations and built-in functions that have a Boolean result always
  return 0 for false and 1 for true, unless otherwise stated. (Important
  exception: the Boolean operations "or" and "and" always return one of
  their operands.)
  
  
  ------------------------------------------------------------------------
  
  Footnotes
  
  ... zero.2.2[2]
  Additional information on these special methods may be found in the
  Python Reference Manual[3].

Related help topics: if while and or not BASICMETHODS

help> continue
  6.10 The continue statement
  
  
  continue_stmt:  "continue"
  
  continue may only occur syntactically nested in a for or while loop, but
  not nested in a function or class definition or try statement within
  that loop.6.1[1]It continues with the next cycle of the nearest
  enclosing loop.
  
  
  ------------------------------------------------------------------------
  
  Footnotes
  
  ... loop.6.1[2]
  It may occur within an except or else clause. The restriction on
  occurring in the try clause is implementor's laziness and will
  eventually be lifted.

Related help topics: while for

help> while
  7.2 The while statement
  
  The while statement is used for repeated execution as long as an
  expression is true:
  
  
  while_stmt:     "while" expression ":" suite
                 ["else" ":" suite]
  
  This repeatedly tests the expression and, if it is true, executes the
  first suite; if the expression is false (which may be the first time it
  is tested) the suite of the else clause, if present, is executed and the
  loop terminates.
  
  A break statement executed in the first suite terminates the loop
  without executing the else clause's suite. A continue statement executed
  in the first suite skips the rest of the suite and goes back to testing
  the expression.

Related help topics: break continue if TRUTHVALUE

help> modules color                                         ##7##

Here is a list of matching modules.  Enter any module name to get more help.

colorsys - Conversion functions between RGB and other color systems.
tkColorChooser 

help> modules mail

Here is a list of matching modules.  Enter any module name to get more help.

mailbox - Classes to handle Unix style, MMDF style, and MH style mailboxes.
mailcap - Mailcap file handling.  See RFC 1524.
mimify - Mimification and unmimification of mail messages.
test.test_mailbox 

help> colorsys                                              ##8##
Help on module colorsys:

NAME
    colorsys - Conversion functions between RGB and other color systems.

FILE
    /home/ping/dev/python/dist/src/Lib/colorsys.py

DESCRIPTION
    This modules provides two functions for each color system ABC:
    
      rgb_to_abc(r, g, b) --> a, b, c
      abc_to_rgb(a, b, c) --> r, g, b
    
    All inputs and outputs are triples of floats in the range [0.0...1.0].
    Inputs outside this range may cause exceptions or invalid outputs.
    
    Supported color systems:
    RGB: Red, Green, Blue components
    YIQ: used by composite video signals
    HLS: Hue, Luminance, Saturation
    HSV: Hue, Saturation, Value

CONSTANTS
    ONE_SIXTH = 0.16666666666666666
    ONE_THIRD = 0.33333333333333331
    TWO_THIRD = 0.66666666666666663
    __all__ = ['rgb_to_yiq', 'yiq_to_rgb', 'rgb_to_hls', 'hls_to_rgb', 'rg...
    __doc__ = 'Conversion functions between RGB and other color...uminance...
    __file__ = '/home/ping/dev/python/dist/src/Lib/colorsys.pyc'
    __name__ = 'colorsys'


help> modules                                               ##9##

Please wait a moment while I gather a list of all available modules...

BaseHTTPServer      delegate            multifile           sndhdr
Bastion             difflib             mutex               socket
CDROM               dircache            mytok (package)     spam
CGIHTTPServer       dirctest            neelk (package)     sps
Canvas              dis                 netrc               sre
ConfigParser        distutils (package) new                 sre_compile
Cookie              dl                  nis                 sre_constants
Dialog              doctest             nntplib             sre_parse
FCNTL               dospath             ntpath              stat
FileDialog          dumbdbm             nturl2path          statcache
FixTk               echatui             oldgnut             statvfs
IN                  eggs                operator            string
MimeWriter          encodings (package) os                  stringold
Queue               errno               parser              strop
ScrolledText        exceptions          pcre                struct
SimpleDialog        fcntl               pdb                 sunau
SimpleHTTPServer    festival            pickle              sunaudio
SocketServer        filecmp             pipes               symbol
StringIO            fileinput           popen2              symtable
TERMIOS             findcode            poplib              sys
Tix                 fnmatch             posix               syslog
Tkconstants         foo                 posixfile           tabnanny
Tkdnd               foo (package)       posixpath           telnetlib
Tkinter             formatter           ppm                 tempfile
UserDict            fpectl              pprint              termios
UserList            fpformat            pre                 test (package)
UserString          ftplib              profile             testalias
__builtin__         gc                  pstats              tester
__future__          gdbm                pty                 tester15
_codecs             getopt              pwd                 tester1c
_curses             getpass             py_compile          tester2
_curses_panel       gettext             pyclbr              thespark
_locale             glob                pydoc               thread
_socket             gnut                pydoc-ell           threading
_sre                gnutellalib         pydoc-findmod       time
_symtable           gopherlib           pydoc-help          timing
_testcapi           grp                 pydoc-nohelp        tkColorChooser
_tkinter            gviz                pyhints             tkCommonDialog
_weakref            gzip                pyscan              tkFileDialog
aifc                html                quopri              tkFont
alesis-old          htmlentitydefs      random              tkMessageBox
anydbm              htmllib             re                  tkSimpleDialog
array               http                readline            toaiff
asynchat            httpcli             reconvert           token
asyncore            httplib             regex               tokenize
atexit              icecream            regex_syntax        traceback
audiodev            ihooks              regsub              tree
audioop             imageop             repr                tty
base64              imaplib             resource            turtle
bdb                 imghdr              reverb              types
binascii            imgsize             rexec               tzparse
binhex              imp                 rfc822              unicodedata
bisect              imputil             rgbimg              unittest
blech               inspect             rlcompleter         urllib
bsddb               inspect-cvs         robotparser         urllib2
cPickle             inspect-ping        romandate           urlparse
cStringIO           keyword             rotor               user
calendar            knee                rxb                 uu
cgen                linecache           rxb14               vchtml
cgi                 linuxaudiodev       rxb15               warnings
chunk               locale              sched               watcher
cmath               logo                scopetest           watcher1
cmd                 macpath             scraper             wave
code                macurl2path         search              weakref
codecs              mailbox             select              webbot
codeop              mailcap             sequencer           webbrowser
collab              makesums            sequencer-badread   webbrowser-mine
collab2             marshal             sequencer-types     whichdb
colorsys            marshali            sgmllib             whrandom
commands            math                sha                 wiki
compileall          md5                 shelve              worker
copy                memtest             shlex               xdrlib
copy_reg            mhlib               shutil              xml (package)
coredump            mimetools           signal              xmllib
crypt               mimetypes           site                xreadlines
curses (package)    mimify              slk                 zipfile
dbhash              mmap                smtpd               zlib
dbm                 mpz                 smtplib             

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

help> md5
Help on module md5:

NAME
    md5

FILE
    /home/ping/dev/python/dist/src/build/lib.linux-i686-2.1/md5.so

DESCRIPTION
    This module implements the interface to RSA's MD5 message digest
    algorithm (see also Internet RFC 1321). Its use is quite
    straightforward: use the new() to create an md5 object. You can now
    feed this object with arbitrary strings using the update() method, and
    at any point you can ask it for the digest (a strong kind of 128-bit
    checksum, a.k.a. ``fingerprint'') of the concatenation of the strings
    fed to it so far using the digest() method.
    
    Functions:
    
    new([arg]) -- return a new md5 object, initialized with arg if provided
    md5([arg]) -- DEPRECATED, same as new, but for compatibility
    
    Special Objects:
    
    MD5Type -- type object for md5 objects

FUNCTIONS
    md5(...)
        new([arg]) -> md5 object
        
        Return a new md5 object. If arg is present, the method call update(arg)
        is made.
    
    new(...)
        new([arg]) -> md5 object
        
        Return a new md5 object. If arg is present, the method call update(arg)
        is made.

CONSTANTS
    MD5Type = <type 'md5'>
    __doc__ = "This module implements the interface to RSA's MD...Objects:...
    __file__ = '/home/ping/dev/python/dist/src/build/lib.linux-i686-2.1/md...
    __name__ = 'md5'

help> help                                                  ##10##

Welcome to Python 2.1!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> abs                                                   ##11##
Help on built-in function abs:

abs(...)
    abs(number) -> number
    
    Return the absolute value of the argument.

help> sys.getrefcount                                       ##12##
Help on built-in function getrefcount in sys:

getrefcount(...)
    getrefcount(object) -> integer
    
    Return the current reference count for the object.  This includes the
    temporary reference in the argument list, so it is at least 2.

help> asdfadsf                                              ##13##
no Python documentation found for 'asdfadsf'

help> quit                                                  ##14##

You're now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

>>> help(3)                                                 ##15##
Help on int:

3

>>> help([])
Help on list:

[]

>>> help([].append)                                         ##16##
Help on built-in function append:

append(...)
    L.append(object) -- append object to end

>>> import sys
>>> help(sys.path)                                          ##17##
Help on list:

['', '/home/ping/python', '/home/ping/dev/python/dist/src/Lib', '/home/ping/dev/
python/dist/src/Lib/plat-linux2', '/home/ping/dev/python/dist/src/Lib/lib-tk', '
/home/ping/dev/python/dist/src/Modules', '/home/ping/dev/python/dist/src/build/l
ib.linux-i686-2.1']

>>> help('sys.path')                                        ##18##
Help on list in sys:

path = ['', '/home/ping/python', '/home/ping/dev/python/dist/src/Lib', '/home/pi
ng/dev/python/dist/src/Lib/plat-linux2', '/home/ping/dev/python/dist/src/Lib/lib
-tk', '/home/ping/dev/python/dist/src/Modules', '/home/ping/dev/python/dist/src/
build/lib.linux-i686-2.1']

>>> help('array')                                           ##19##
Help on module array:

NAME
    array

FILE
    /home/ping/dev/python/dist/src/build/lib.linux-i686-2.1/array.so

DESCRIPTION
    This module defines a new object type which can efficiently represent
    an array of basic values: characters, integers, floating point
    numbers.  Arrays are sequence types and behave very much like lists,
    except that the type of objects stored in them is constrained.  The
    type is specified at object creation time by using a type code, which
    is a single character.  The following type codes are defined:
    
        Type code   C Type             Minimum size in bytes 
        'c'         character          1 
        'b'         signed integer     1 
        'B'         unsigned integer   1 
        'h'         signed integer     2 
        'H'         unsigned integer   2 
        'i'         signed integer     2 
        'I'         unsigned integer   2 
        'l'         signed integer     4 
        'L'         unsigned integer   4 
        'f'         floating point     4 
        'd'         floating point     8 
    
    Functions:
    
    array(typecode [, initializer]) -- create a new array
    
    Special Objects:
    
    ArrayType -- type object for array objects

FUNCTIONS
    array(...)
        array(typecode [, initializer]) -> array
        
        Return a new array whose items are restricted by typecode, and
        initialized from the optional initializer value, which must be a list
        or a string.

CONSTANTS
    ArrayType = <type 'array'>
    __doc__ = 'This module defines a new object type which can ...cts:\n\n...
    __file__ = '/home/ping/dev/python/dist/src/build/lib.linux-i686-2.1/ar...
    __name__ = 'array'


>>> 



##1##  Topic names are all in capital letters so that it's very
       unlikely they will collide with module or package names.
       The hope is that the user will understand they're supposed
       to enter them in capitals, as shown.

##2##  Each topic is associated with one of the HTML files in the
       library documentation.  The formatter module is used to
       turn HTML into text.  A couple of small enhancements to the
       HTML parser allow tables to be crudely displayed; columns
       are separated by tabs, so they don't always line up, but at
       least that's a lot better than having the entire table get
       mushed into one paragraph.  The generated text is displayed
       using the pager, like everything else.

##3##  Each topic can also have a number of cross-references, which
       are shown following the help docs (after the pager is done).
       The cross-references can be other topics, keywords, or modules.

##4##  You can surf through the docs by picking one of the related
       topics and typing it back in.  Yes, i know the list of related
       topics isn't word-wrapped -- that's an easy change.

##5##  A list of Python keywords is available.  It's okay for them
       to be entered by the user in lowercase -- they're reserved
       words, so there will never be modules with these names.

##6##  Each keyword is similarly associated with an HTML file and
       possibly some related topics.

##7##  Typing "modules" followed by a search key does the same thing
       as "pydoc -k" from the shell.

##8##  Typing in a module name is just like running "pydoc" from the
       shell on a module.

##9##  Typing in "modules" by itself produces a list of all the
       modules and packages.  It takes less than two seconds on
       my machine to gather the list.

##10## What happens if you type "help" in help?  You get the intro.

##11## Built-in functions are available too.

##12## You can look things up with a dotted path of arbitrary depth.

##13## What happens if there's no such module?  You get a message.

##14## "quit", "q", "QUIT", "Quit", "Q", and Ctrl-D all quit help.
       Even typing in '"quit"' with the quotation marks works, just
       to make sure beginners don't get stuck.

##15## What happens if you ask for help on a number?  Nothing too
       useful, but at least it doesn't explode.

##16## Asking for help on a built-in method is actually useful.

##17## If you ask for help on an object, it just shows you the object.

##18## If you ask for help and give the path to get to an object, it
       shows you the object and also where it came from.

##19## You can get help directly from the interpreter level by
       invoking "help()" with an argument.