Typing help brings up a screen that says type help()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 30 00:46:54 EDT 2014


Seymore4Head wrote:

> What is the logic behind that?
> Couldn't help do the same thing as help()?

Not without being annoyingly, obnoxiously "too clever by half".

In Python, all values are objects, so apart from a handful of statements
(such as "if blah blah:", "for x in blah:" etc.) everything you type in
Python is an object. That includes functions like len() and help() itself.

In the interactive interpreter, hitting Enter with an object on the command
line displays that object. That's the expected behaviour, and so
conveniently the help object is designed to display: 

    Type help() for interactive help ...

It does this by having __repr__ and __str__ methods which return the message
we want to be displayed.

Now, it is *technically* possible to have those __repr__ and __str__ methods
automatically call the help object, as if you had typed help() with the
round brackets. But that would be Just Plain Wrong. Python makes a
fundamental distinction between displaying a function or method, and
calling it:

py> from random import random
py> random
<built-in method random of Random object at 0x90f6ca4>
py> random()
0.016599200602883224

and it would be surprising to break that distinction for the help object. It
would lead to deeply disturbing behaviour. E.g. suppose you ended up
somehow with a list or dict containing the help object, which is quite easy
to do when exploring interactively. For example, in Python 2:

py> import __builtin__
py> print __builtin__.__dict__

or in Python 3:

py> import builtins
py> print(builtins.__dict__)

Or even something like this:

py> stuff = [len, help, dict]
py> print(stuff)

You wouldn't expect those simple commands to launch the help system, would
you? And if they did, it would probably make it difficult to debug exactly
how and why that was happening, since you couldn't print the dict or list
to see what was in it without launching the help system.


> But the reason I ask is that I see (from a video of Getting Started
> with Python) that older versions of python would allow ? as help.  I
> get syntax error when I try ?

Regular Python has never accepted ? however the custom IPython interactive
interpreter does.



-- 
Steven




More information about the Python-list mailing list