compclass (class decorator)¶
compclass(_cls=None, delegates=None, verbose=True, log_func=logger.info)
¶
Decorator that adds class attributes/methods from delegates
to _cls
object as class properties.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
_cls |
Union[Type[T], None]
|
Class to which attributes/methods should be forwarded to. |
None
|
delegates |
Union[Dict[str, Union[Iterable[str], delegatee]], None]
|
Key-value pair of delegates.
|
None
|
verbose |
bool
|
Defines the level of verbosity when setting those forwarded methods. |
True
|
log_func |
Callable[[str], None]
|
Function to use for logging, if verbose is set to True. |
logger.info
|
Raises:
Type | Description |
---|---|
ValueError
|
|
Returns:
Type | Description |
---|---|
Union[Type[T], Callable[[Type[T], Dict[str, Union[Iterable[str], delegatee]]], Type[T]]]
|
Class with added methods from delegates. |
Usage:
The function can be used as a class decorator:
class Foo:
a = 1
def __len__(self) -> int:
# custom len method
return 42
@compclass(delegates={"_foo": ("a", "__len__")})
class Bar:
def __init__(self, foo: Foo):
self._foo = foo
foo = Foo()
bar = Bar(foo)
bar.a # -> 1 (instead of bar._foo.a)
len(bar) # -> 42 (instead of len(bar._foo))