Module pedantic.decorators.class_decorators

Functions

def for_all_methods(decorator: Callable[..., ~ReturnType]) ‑> Callable[[Type[~C]], Type[~C]]
Expand source code
def for_all_methods(decorator: F) -> Callable[[Type[C]], Type[C]]:
    """
        Applies a decorator to all methods of a class.

        Example:

        >>> @for_all_methods(pedantic)
        ... class MyClass(object):
        ...     def m1(self): pass
        ...     def m2(self, x): pass
    """
    def decorate(cls: C) -> C:
        if not is_enabled():
            return cls

        if issubclass(cls, enum.Enum):
            raise PedanticTypeCheckException(f'Enum "{cls}" cannot be decorated with "@pedantic_class". '
                                             f'Enums are not supported yet.')

        if is_dataclass(obj=cls):
            raise PedanticTypeCheckException(f'Dataclass "{cls}" cannot be decorated with "@pedantic_class". '
                                             f'Try to write "@dataclass" over "@pedantic_class".')

        for attr in cls.__dict__:
            attr_value = getattr(cls, attr)

            if isinstance(attr_value, (types.FunctionType, types.MethodType)):
                setattr(cls, attr, decorator(attr_value))
            elif isinstance(attr_value, property):
                prop = attr_value
                wrapped_getter = _get_wrapped(prop=prop.fget, decorator=decorator)
                wrapped_setter = _get_wrapped(prop=prop.fset, decorator=decorator)
                wrapped_deleter = _get_wrapped(prop=prop.fdel, decorator=decorator)
                new_prop = property(fget=wrapped_getter, fset=wrapped_setter, fdel=wrapped_deleter)
                setattr(cls, attr, new_prop)

        _add_type_var_attr_and_method_to_class(cls=cls)
        return cls
    return decorate

Applies a decorator to all methods of a class.

Example:

>>> @for_all_methods(pedantic)
... class MyClass(object):
...     def m1(self): pass
...     def m2(self, x): pass
def pedantic_class(cls: ~C) ‑> ~C
Expand source code
def pedantic_class(cls: C) -> C:
    """ Shortcut for @for_all_methods(pedantic) """
    return for_all_methods(decorator=pedantic)(cls=cls)

Shortcut for @for_all_methods(pedantic)

def pedantic_class_require_docstring(cls: ~C) ‑> ~C
Expand source code
def pedantic_class_require_docstring(cls: C) -> C:
    """ Shortcut for @for_all_methods(pedantic_require_docstring) """
    return for_all_methods(decorator=pedantic_require_docstring)(cls=cls)

Shortcut for @for_all_methods(pedantic_require_docstring)

def timer_class(cls: ~C) ‑> ~C
Expand source code
def timer_class(cls: C) -> C:
    """ Shortcut for @for_all_methods(timer) """
    return for_all_methods(decorator=timer)(cls=cls)

Shortcut for @for_all_methods(timer)

def trace_class(cls: ~C) ‑> ~C
Expand source code
def trace_class(cls: C) -> C:
    """ Shortcut for @for_all_methods(trace) """
    return for_all_methods(decorator=trace)(cls=cls)

Shortcut for @for_all_methods(trace)