Search code examples
pythonpython-2.xpydoc

What does 'with a twist' mean when help(help) is called in Python?


help(help) says This is a wrapper around pydoc.help (with a twist).

What is the twist?

$ python 
Python 2.7.10 (default, Jul 30 2016, 19:40:32) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(help)
Help on _Helper in module site object:

class _Helper(__builtin__.object)
 |  Define the builtin 'help'.
 |  This is a wrapper around pydoc.help (with a twist).
 |  
 |  Methods defined here:
 |  
 |  __call__(self, *args, **kwds)
 |  
 |  __repr__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Solution

  • There isn't much of a twist. The twist is that pydoc is lazily imported and the object has a __repr__ method that provides direct feedback on how to use the object:

    >>> repr(help)
    'Type help() for interactive help, or help(object) for help about object.'
    

    The __repr__ method is called whenever you echo the help object in the interactive prompt:

    >>> help
    Type help() for interactive help, or help(object) for help about object.
    

    Python 3.4 got rid of the 'twist' description altogether, replacing it with something a little more descriptive; see issue 9364. Quoting the bug reporter:

    "(with a twist)" thanks a lot. I think the comment should be either removed or explained. A reference manual should explain, not tease.

    followed by a developer's response:

    Agreed. I think the “twist” is that the import is lazy and that help has a useful repr (wow, talk about a twist!). Those details need not be alluded to, just remove the comment (“wrapper” is IMO enough to raise curiosity, the source is here to find what’s the wrapping).

    The docstring now reads:

    class _Helper(object):
        """Define the builtin 'help'.
    
        This is a wrapper around pydoc.help that provides a helpful message
        when 'help' is typed at the Python interactive prompt.
    
        Calling help() at the Python prompt starts an interactive help session.
        Calling help(thing) prints help for the python object 'thing'.
        """