hbutils.reflection.clazz

Overview:

Useful functions for processing python classes and types.

This module provides utility functions for working with Python classes and types, including class wrapping decorators and common base class detection.

class_wraps

hbutils.reflection.clazz.class_wraps(wrapped: type, assigned: Tuple[str] = ('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated: Tuple[str] = ())[source]

Wrapper decorator for class.

This function creates a decorator that can be used to wrap a class while preserving its metadata (similar to functools.wraps but for classes). It updates the wrapper class with attributes from the wrapped class.

Parameters:
  • wrapped (type) – The class to be wrapped.

  • assigned (Tuple[str]) – Tuple of attribute names to be assigned from wrapped to wrapper. Defaults to CLASS_WRAPPER_ASSIGNMENTS (same as functools.WRAPPER_ASSIGNMENTS).

  • updated (Tuple[str]) – Tuple of attribute names to be updated from wrapped to wrapper. Defaults to CLASS_WRAPPER_UPDATES (empty tuple).

Returns:

A partial function that can be used as a decorator.

Return type:

functools.partial

Examples::
>>> def cls_dec(clazz):
...     @class_wraps(clazz)
...     class _NewClazz(clazz):
...         pass
...
...     return _NewClazz
>>> 
>>> class Original:
...     '''Original class docstring'''
...     pass
>>> 
>>> @cls_dec
... class Wrapped(Original):
...     pass
>>> 
>>> Wrapped.__doc__
'Original class docstring'

common_base

hbutils.reflection.clazz.common_base(cls: type, *clss: type) type[source]

Get common base class of the given classes.

This function finds the most specific common base class shared by all provided classes. Only the __base__ attribute is considered during the search, which means it follows the direct inheritance chain rather than the full MRO (Method Resolution Order).

Parameters:
  • cls (type) – The first class to find common base for.

  • clss (type) – Additional classes to find common base for.

Returns:

The most specific common base class shared by all input classes.

Return type:

type

Examples::
>>> from hbutils.reflection import common_base
>>> common_base(object)
<class 'object'>
>>> common_base(object, int, str)
<class 'object'>
>>> common_base(RuntimeError, ValueError, KeyError)
<class 'Exception'>
>>> common_base(int, float)
<class 'object'>
>>> 
>>> class A: pass
>>> class B(A): pass
>>> class C(A): pass
>>> common_base(B, C)
<class '__main__.A'>