typeutils
- Type handling¶
Python’s built-in 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
and instances.
-
class
boltons.typeutils.
classproperty
(fn)[source]¶ Much like a
property
, but the wrapped get function is a class method. For simplicity, only read-only properties are implemented.
-
boltons.typeutils.
get_all_subclasses
(cls)[source]¶ Recursively finds and returns a
list
of 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']
-
boltons.typeutils.
issubclass
(subclass, baseclass)[source]¶ Just like the built-in
issubclass()
, this function checks whether subclass is inherited from baseclass. Unlike the built-in function, thisissubclass
will simply returnFalse
if either argument is not suitable (e.g., if subclass is not an instance oftype
), instead of raisingTypeError
.Parameters: >>> class MyObject(object): pass ... >>> issubclass(MyObject, object) # always a fun fact True >>> issubclass('hi', 'friend') False
-
boltons.typeutils.
make_sentinel
(name='_MISSING', var_name=None)[source]¶ 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
None
is a valid input.Parameters: >>> 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.
Note
By design, additional calls to
make_sentinel
with the same values will not produce equivalent objects.>>> make_sentinel('TEST') == make_sentinel('TEST') False >>> type(make_sentinel('TEST')) == type(make_sentinel('TEST')) False