Added in Python 3.5, the typing.no_type_check_decorator
was introduced:
Decorator to give another decorator the
no_type_check()
effect.
As it’s usage was very limited (and not implemented in mypy
), it was recently deprecated.
My proposal is to make a “generic” version of this decorator, to give any other decorator a specific effect, e.g.:
The name decorator_transform
is probably not a good one, but I can’t find any better name for now (haven’t think a lot about it). Basically, it would work this way:
@typing.decorator_transform(property) # Or maybe specifying the argument as a string: @decorator_transform("property")
def my_decorator_behaving_as_a_property(func):
"""This decorator will transform the `func` callable to a `property` if necessary."""
class A:
def __init__(self) -> None:
self.a = 1
@my_decorator_behaving_as_a_property
def b(self) -> int:
return self.a + 1
reveal_type(A().b) # Revealed type is: int
This would help type checkers understand that a specific decorator is behaving as another decorator that requires a special behavior (e.g. with classmethod()
, the type checker needs to understand the first argument will be the class object, and not the self instance).
This behavior happens in Pydantic, for example using the computed_field()
decorator:
If the
computed_field
decorator is applied to a bare function (e.g. a function without the@property
or@cached_property
decorator) it will wrap the function inproperty
itself. Although this is more concise, you will lose IntelliSense in your IDE, and confuse static type checkers, thus explicit use of@property
is recommended.
With this new proposal, no need to add an explicit @property
to the decorated function.
Pydantic also defines field_validator()
, which will transform the decorated method into a classmethod()
if necessary.
I don’t know any other library that would benefit from this proposal, but this could be relatively common.
PS: This is a quick idea that I had yesterday, there might be things I haven’t thought about that would make this impossible. There’s also a lot of room for discussion/ideas/improvements on this one.