Added in Python 3.5, the
typing.no_type_check_decorator was introduced:
Decorator to give another decorator the
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.:
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).
computed_fielddecorator is applied to a bare function (e.g. a function without the
@cached_propertydecorator) it will wrap the function in
propertyitself. Although this is more concise, you will lose IntelliSense in your IDE, and confuse static type checkers, thus explicit use of
With this new proposal, no need to add an explicit
@property to the decorated function.
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.