typeutils - Type handling¶
functools module builds several useful
utilities on top of Python’s first-class function support.
typeutils attempts to do the same for metaprogramming with types
Much like a
property, but the wrapped get function is a class method. For simplicity, only read-only properties are implemented.
Recursively finds and returns a
listof all types inherited from cls.
>>> class A(object): ... pass ... >>> class B(A): ... pass ... >>> class C(B): ... pass ... >>> class D(A): ... pass ... >>> [t.__name__ for t in get_all_subclasses(A)] ['B', 'D', 'C'] >>> [t.__name__ for t in get_all_subclasses(B)] ['C']
Just like the built-in
issubclass(), this function checks whether subclass is inherited from baseclass. Unlike the built-in function, this
issubclasswill simply return
Falseif either argument is not suitable (e.g., if subclass is not an instance of
type), instead of raising
>>> class MyObject(object): pass ... >>> issubclass(MyObject, object) # always a fun fact True >>> issubclass('hi', 'friend') False
Creates and returns a new instance of a new class, suitable for usage as a “sentinel”, a kind of singleton often used to indicate a value is missing when
Noneis a valid input.
>>> make_sentinel(var_name='_MISSING') _MISSING
The most common use cases here in boltons are as default values for optional function arguments, partly because of its less-confusing appearance in automatically generated documentation. Sentinels also function well as placeholders in queues and linked lists.
By design, additional calls to
make_sentinelwith the same values will not produce equivalent objects.
>>> make_sentinel('TEST') == make_sentinel('TEST') False >>> type(make_sentinel('TEST')) == type(make_sentinel('TEST')) False