hbutils.model.repr
- Overview:
Useful functions for building representation format of objects.
This module provides utilities to generate string representations for custom classes,
particularly useful for implementing __repr__ methods with flexible display options.
get_repr_info
- hbutils.model.repr.get_repr_info(cls: type, args: List[Tuple[str, Callable[[], Any] | Tuple[Callable[[], Any], Callable[[], bool]], Callable[[], bool]]]) str[source]
Get representation information for object.
This function generates a formatted string representation of an object based on the provided class type and argument information. It can be used in
__repr__methods to create consistent and informative object representations.- Parameters:
cls (type) – The class type of the object to represent.
args (List[Tuple]) –
A list of tuples containing argument display information. Each tuple can have:
2 elements: (name, data_func) or (name, (data_func, present_func))
3 elements: (name, data_func, present_func)
Where:
name (str): The name of the argument to display
data_func (Callable): A callable that returns the value to display
present_func (Callable): A callable that returns True if the argument should be displayed
- Returns:
A formatted representation string in the format
<ClassName arg1: value1, arg2: value2>- Return type:
str
- Raises:
ValueError – If a tuple’s length is not 2 or 3.
TypeError – If an argument item is not a tuple.
- Examples::
>>> from hbutils.model import get_repr_info >>> class Sum: ... def __init__(self, a, b): ... self.__a = a ... self.__b = b ... def __repr__(self): ... return get_repr_info( ... cls=self.__class__, ... args=[ ... ('b', lambda: self.__b, lambda: self.__b is not None), ... ('a', lambda: self.__a), ... ] ... ) ... >>> Sum(1, 2) <Sum b: 2, a: 1> >>> Sum(1, None) <Sum a: 1> >>> Sum(None, None) <Sum a: None>