I have some properties on a class telling me if the instance is of the right type.
For example:
class Object:
@property
def is_module(self):
return isinstance(self, Module)
@property
def is_class(self):
return isinstance(self, Class)
class Module(Object): ...
class Class(Object): ...
I would like to annotate these properties as type guards, but it does not seem to be supported by the specification (PEP 647):
@property
def is_module(self) -> TypeGuard[Module]:
return isinstance(self, Module)
…gives error: TypeGuard functions must have a positional argument [valid-type]
.
PEP 647 says this:
A concern was raised that there may be cases where it is desired to apply the narrowing logic on
self
andcls
. This is an unusual use case, and accommodating it would significantly complicate the implementation of user-defined type guards. It was therefore decided that no special provision would be made for it. If narrowing ofself
orcls
is required, the value can be passed as an explicit argument to a type guard function.
Is there any other way ?