I'm learning to write user-friendly classes and methods and I'd like for users to know how to use them from a terminal. Python's standard help(MYclass)
returns eighteen lines I don't want, and that's half a screen for a small window and those just learning python will lose continuity with the previous lines disappearing from the top.
Is there any way I can override what using help(MYclass)
(or help(MYmethod)
) shows so that it only displays the (in this case) one-line docstring?
While some IDEs show the docstrings in bubbles, terminals don't cooperate. (Do the triple-quoted (docstring) messages in Python appear while typing in IDEs other than IDLE?):
So instead, I've turned to help
for help, but help
is overly helpful with all those extra lines of template.
Then I thought of redefining help:
def hhelp(x):
return x.__doc__
help = hhelp
but I decided that this is evil; like redefining the number 7, and I would like help(some builtin)
to still work normally, and the selective hijacking to occur only for MYclass
es.
There is always
def doc(x):
return x.__doc__
if I can't find anything that selectively hijacks help()
.
class A(object):
"""instantiate a = A(x), then use a.sqr() to get x**2"""
def __init__(self, x):
self.x = x
def sqr(self):
return x**2
results in nineteen lines. I'd only like my one-line docstring to show.
Help on class A in module __main__:
class A(__builtin__.object)
| instantiate a = A(x), then use a.sqr() to get x**2
|
| Methods defined here:
|
| __init__(self, x)
|
| sqr(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
You can monkeypatch the built-in help
function to show the __doc__
string for classes and to fall back on the original help
for other objects:
import inspect
import pydoc
class Helper(object):
def __init__(self):
self.help = __builtins__.help
def __call__(self, obj):
if inspect.isclass(obj):
return pydoc.pager(obj.__doc__)
else:
return self.help(obj)
__builtins__.help = Helper()
Which produces the following output:
class Foo:
"""This is the docstring."""
def foo(self):
return None
help(Foo)
# Output:
# This is the docstring.