hdir — Highlight dir

hdir() is a highlighted version of the dir() function.

Dependencies

Usage

pip install hdir

Invoke hdir() without argument shows the legend:

>>> from hdir import *
>>> hdir()
abstract class {dict} exception function instance [list] module number other python() {set} 'string' (tuple) <wrapper>

hdir() does not break words and sort them alphabetically according to case. Let’s compare the classic dir() function with hdir() on the builtins module:

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>> hdir(builtins)
ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError Ellipsis EnvironmentError Exception False FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError None NotADirectoryError NotImplemented NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError True TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning WindowsError ZeroDivisionError abs all any ascii bin bool breakpoint bytearray bytes callable chr classmethod compile complex copyright credits delattr dict dir divmod enumerate eval exec exit filter float format frozenset getattr globals hasattr hash help hex id input int isinstance issubclass iter len license list locals map max memoryview min next object oct open ord pow print property quit range repr reversed round set setattr slice sorted staticmethod str sum super tuple type vars zip

type.__dict__ is a proxy <> to a dict {} whose first item is a descriptor <> to a function (cyan):

>>> hdir(type, 'a')
... <{<__dict__>}> ...

Color

Color Type
Blue int, float, bool, complex
Cyan function or method
Green string
Magenta module
Red exception
Yellow class other than exception
Style Meaning Windows [1] Mintty Linux FB GNOME, KDE
Color type [2]
Bold is real [3]
Italic is abstract    
Underline of instance  
[1] HKCU\Console\VirtualTerminalLevel = 1 enables ANSI colors except dark yellow
[2] If it is a container, first item’s color
[3] Neither abstract nor wrapped in a descriptor or proxy

Decorators

Decorators Type Recursive
'...' string  
[...] list
(...) tuple
{...} dict or set
<...> descriptor or proxy
...() user function [4]  
[4] Written in Python language, neither built-in nor C language library function

Instance variable

hdir() underlines instance variables. In this example, the msg instance variable covers the same name’s class variable:

>>> class C:
      msg = ['Hello world', 'Goodbye']
      age = {'Alice': 31, 'Bob': 39}
>>> hdir(C)
{age} ['msg']
>>> obj = C()
>>> obj.msg = obj.msg + ['Regards']
>>> obj.ready = True
>>> hdir(obj)
{age} ['msg'] ready
>>> obj.msg
['Hello world', 'Goodbye', 'Regards']
>>> C.msg
['Hello world', 'Goodbye']

Flags

hdir() hides __double __magic__ _private attributes unless 'd' 'm' 'p' flags are set:

>>> from collections import abc
>>> hdir(abc, 'm')
AsyncGenerator AsyncIterable AsyncIterator Awaitable ByteString Callable Collection Container Coroutine Generator Hashable ItemsView Iterable Iterator KeysView Mapping MappingView MutableMapping MutableSequence MutableSet Reversible Sequence Set Sized ValuesView ['__all__'] {'__builtins__'} '__cached__' __doc__ '__file__' __loader__ '__name__' '__package__' __spec__

The “all” 'a' flag equals 'dmp', though abstract items are always visible:

>>> hdir(abc.Set)
__contains__ __iter__ __len__ isdisjoint()
>>> hdir(abc.Set, 'a')
{'__abstractmethods__'} __and__() __class__ __contains__ <__delattr__> <__dir__> '__doc__' __eq__() <__format__> __ge__() <__getattribute__> __gt__() __hash__ <__init__> __init_subclass__ __iter__ __le__() __len__ __lt__() '__module__' <__ne__> __new__ __or__() __rand__() <__reduce__> <__reduce_ex__> <__repr__> __ror__() __rsub__() __rxor__() <__setattr__> <__sizeof__> (__slots__) <__str__> __sub__() __subclasshook__() __xor__() _abc_impl _from_iterable() _hash() isdisjoint()

The “no-color” 'n' flag disables ANSI colors but keeps decorators:

import re
>>> hdir(re)
A ASCII DEBUG DOTALL I IGNORECASE L LOCALE M MULTILINE Match Pattern RegexFlag S Scanner T TEMPLATE U UNICODE VERBOSE X compile() copyreg enum error escape() findall() finditer() fullmatch() functools match() purge() search() split() sre_compile sre_parse sub() subn() template()
>>> hdir(re, 'n')
A ASCII DEBUG DOTALL I IGNORECASE L LOCALE M MULTILINE Match Pattern RegexFlag S Scanner T TEMPLATE U UNICODE VERBOSE X compile() copyreg enum error escape() findall() finditer() fullmatch() functools match() purge() search() split() sre_compile sre_parse sub() subn() template()

The “raw” 'r' flag returns a vars() style’s dict to take advantage of attribute filtering:

>>> len(vars(re)), len(hdir(re, 'r'))
(58, 39)

No false positive

While dir(), vars() and inspect.getmembers() return some attributes that does not exist, hdir() tests each attribute with hasattr() to remove false positives:

>>> from inspect import getmembers
>>> attr = dir(type), vars(type), dict(getmembers(type)), hdir(type, 'ar')
>>> [len(a) for a in attr]
[43, 29, 43, 42]
>>> ['__abstractmethods__' in a for a in attr]
[True, True, True, False]
>>> type.__abstractmethods__
AttributeError: __abstractmethods__

Versions

0.5: February 16, 2019 — First beta release
0.4: February 8, 2019 — import * imports hdir() only
0.3: February 7, 2019 — Add legend, 'r' flag, wrapper support
0.2: February 5, 2019 — False positive removal
0.1: February 5, 2019 — First alpha release