Python's help() function is awesome

Terry Reedy tjreedy at udel.edu
Mon Apr 17 09:03:00 EDT 2017


On 4/17/2017 5:31 AM, Steve D'Aprano wrote:
> If you're not using the help() command in the interactive interpreter,
> you're missing out on a lot.
>
> I recently discovered that help() is even cleverer than I knew. I knew it
> picked up on objects' doc strings, but what happens if the object doesn't
> have a doc string?
>
> Let's find out!
>
> Here's a tiny module with a couple of toy functions. Save this
> as "module.py":
>
> # --- cut here ✂ ----
>
> def greet(name='world'):
>     """Hello world, with optional name."""
>     print ("Hello, %s" % name)
>
> # The insult() function insults the caller.
> # Pass the number of insults to use, and an optional name.
> def insult(number, name=None):
>     if name is None or name == '':
>         name = 'Anonymous Coward'
>     print(name)
>     for i in range(number):
>         if i%2 == 0:
>             print("Your mother smells of elderberries!")
>         else:
>             print("And your father was a hamster!")
>
> def goodbye():
>     # Say goodbye.
>     print("Goodbye cruel world!")
>
> # --- ✂ ---
>
>
> Now start up the interactive interpreter and import the module:
>
> py> import module
> py> help(module)
>
>
> and you should see something like this:
>
>
> Help on module module:
>
> NAME
>     module
>
> FUNCTIONS
>     goodbye()
>
>     greet(name='world')
>         Hello world, with optional name.
>
>     insult(number, name=None)
>         # The insult() function insults the caller.
>         # Pass the number of insults to use, and an optional name.

When I ran the module instead of importing it, help(insult) printed the 
same.  The pydoc function wrapped by help must be going back to the 
source, as I believe that comments are left behind when the source is 
compiled.  I did not know this either.  A comment before the def must 
have once been standard.

> FILE
>     /home/steve/module.py
>
>
>
> Not only does it pick up the docstring for greet(), but it picks up the
> comment just prior to the function definition of insult(). Alas, as of
> Python 3.5 it doesn't recognise the comments in the goodbye() function --
> perhaps because they're conceptually part of the implementation, not the
> interface.


-- 
Terry Jan Reedy





More information about the Python-list mailing list