Python's help() function is awesome

Steve D'Aprano steve+python at pearwood.info
Mon Apr 17 05:31:26 EDT 2017


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.

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.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list