[issue8525] Display exceptions' subclasses in help()

Nick Coghlan report at bugs.python.org
Sat Jul 14 08:44:18 EDT 2018


Nick Coghlan <ncoghlan at gmail.com> added the comment:

Reviewing the builtins in 3.7, I get the following results for builtin objects that have defined subclasses immediately after interpreter startup:

=============
>>> for name, obj in vars(builtins).items():
...     if isinstance(obj, type) and name in str(obj):
...         subclasses = type(obj).__subclasses__(obj)
...         if subclasses:
...             print(f"{obj}: {len(subclasses)}")
... 
<class 'classmethod'>: 1
<class 'dict'>: 1
<class 'property'>: 1
<class 'int'>: 1
<class 'object'>: 132
<class 'staticmethod'>: 1
<class 'tuple'>: 16
<class 'type'>: 1
<class 'BaseException'>: 4
<class 'Exception'>: 19
<class 'ImportError'>: 2
<class 'OSError'>: 13
<class 'RuntimeError'>: 3
<class 'NameError'>: 1
<class 'SyntaxError'>: 1
<class 'IndentationError'>: 1
<class 'LookupError'>: 3
<class 'ValueError'>: 2
<class 'UnicodeError'>: 3
<class 'ArithmeticError'>: 3
<class 'SystemError'>: 1
<class 'Warning'>: 10
<class 'ConnectionError'>: 4
=============

So rather than special-casing exceptions or builtins in general, my inclination would be to include a section that lists up to 4 subclasses inline, and then adds a "... and NNN additional subclasses" trailing when there are more than 4 (or when there are less than 4 subclasses with public names, but additional private subclasses).

So in a class like "int", for example, we'd see:

    Currently imported subclasses:
        bool

While in a class like OSError we'd see:

    Currently imported subclasses:
        BlockingIOError
        ChildProcessError
        ConnectionError
        FileExistsError
        ... and 9 other subclasses

And in "help(object)" we'd see something like:

    Currently imported subclasses:
        async_generator
        BaseException
        builtin_function_or_method
        bytearray
        ... and 215 other subclasses


The initial list of subclasses to show would be restricted to public builtins: `sorted((str(cls) for cls in object.__subclasses__() if not cls.__name__.startswith("_") and cls.__module__ == "builtins"), key=str.lower)`

If that gives less then four names, then the list of names would be expanded to subclasses with public names in public modules (i.e. neither __qualname__ nor __module__ starts with "_", neither of those contains "._", and qualname doesn't contain ".<locals>.").

The full count of currently imported subclasses would ignore whether the subclass names were public or not.

----------
nosy: +ncoghlan

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue8525>
_______________________________________


More information about the Python-bugs-list mailing list