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

Terry Reedy tjreedy at udel.edu
Fri Aug 29 21:41:30 EDT 2014


On 8/29/2014 4:40 PM, Seymore4Head wrote:
> What is the logic behind that?

You should better ask, "How does that happen?".  Attend carefully and 
you should learn much.

In expressions, python replaces names with the object the name is bound 
to. In batch mode, a bare name is equivalent to 'pass'.  In interactive 
mode, a bare "name" is equivalent to "print(repr(name))".

 >>> s = 'abc'
 >>> s
'abc'
 >>> print(str(s))
abc
 >>> print(repr(s))
'abc'

This is a handy shortcut. "repr(name)" in turn, is also a shortcut.  It 
looks for the .__repr__ attribute of type(name) or one of the 
superclasses.  If there in no override in the inheritance tree, you see 
the default from object:

 >>> object()
<object object at 0x00000000001B2C70>

You have probably seen this pattern already. Now, what is the class of 
the object bound to 'help' (and 'quit' and 'exit')?

 >>> type(help)
<class '_sitebuiltins._Helper'>
 >>> type(quit)
<class '_sitebuiltins.Quitter'>
 >>> type(exit)
<class '_sitebuiltins.Quitter'>

Each of these classes has a .__repr__ method and a .__call__ method. 
The first simply echoes a fixed string regardless of input.

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

We can play the same game with python code.

 >>> class Helper:
	def __repr__(self):
		return 'Type myhelp() for interactive help, or myhelp(object) for help 
about object.'
	def __call__(self, arg):
		help(arg)

 >>> myhelp = Helper()
 >>> myhelp
Type myhelp() for interactive help, or myhelp(object) for help about object.
 >>> myhelp(Helper)
Help on class Helper in module __main__:

class Helper(builtins.object)
  |  Methods defined here:
  |
  |  __call__(self, arg)
  |
  |  __repr__(self)
  |
  |  ----------------------------------------------------------------------
  |  Data descriptors defined here:
  |
  |  __dict__
  |      dictionary for instance variables (if defined)
  |
  |  __weakref__
  |      list of weak references to the object (if defined)


> Couldn't help do the same thing as help()?

Couldn't python stab people in the back by violating its own rules ;-?

(See the doc for what repr and hence .__repr__ are supposed to do.)

You should now understand that the interpreter has *no special 
knowledge* about help, exit, or quit.  The special behavior is built 
into their classes.  That is how Python objects work in relation to a 
few simple syntax rules, like "callable(args)" meaning 'call callable 
with args'.

 > older versions of python would allow ? as help.

If I ever knew that, I have forgotten.  The interpreter must have 
treated '?' as a special case for interactive input. I suspect help was 
changed when quit and exit were added.

-- 
Terry Jan Reedy




More information about the Python-list mailing list