Skip to main content

hook_classmethod

FunctionPrivateSource

hooked_method: Callable[P, T] = hook_classmethod[**P, _Type, T](
cls_method: Callable[P, T],
hook_before: Callable[Concatenate[_Type, P], None] | None = None,
hook_after: Callable[Concatenate[_Type, P], None] | None = None,
)

Hook a class method.

Arguments

Requires

ArgumentTypeRequired
Description
cls_method(**P) -> TA class method that is hooked. This is the bounded version of the class method, where the first argument cls has been implied and not included in the spec P.
hook_beforeNone | ((_Type, **P) -> None)The hook that will be run before this class method.
hook_afterNone | ((_Type, **P) -> None)The hook that will be run after this class method.

Returns

ArgumentType
Description
hooked_method(**P) -> TThe hooked class method, where the first argument (class) is hidden.

Examples

Hook a class with __init_subclass__ defined

hook_init_subclass.py
import flask_sqlalchemy_compat as fsc


class ExampleBase:
test_val = 0

def __init_subclass__(cls) -> None:
cls.test_val = 1


class ExampleA(ExampleBase):
pass


def hook(cls: ExampleBase) -> None:
cls.test_val = 10


ExampleBase.__init_subclass__ = fsc.utilities.hook_classmethod(
ExampleBase.__init_subclass__, hook_after=hook
)


class ExampleB(ExampleBase):
pass


if __name__ == "__main__":
print("ExampleBase.test_val:", ExampleBase.test_val)
print("ExampleA.test_val:", ExampleA.test_val)
print("ExampleB.test_val:", ExampleB.test_val)