Class Decorators #1898
-
Does pyright support class decorators and if so what's the right way to type annotate them. The code looks something like,
Only missing code is make_cache_key and I can include working example if needed, but ideal type is something like base_cls is a class type, return output is CachedObject that's generic over that same class type and create returns a value of that class type. I've played with typevars but have gotten stuck trying to make it work and am unsure if it's possible or not. My type attempt look like this and has multiple errors,
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Pyright doesn't support the use of dynamic arguments in a class declaration. Neither does mypy. Static type checkers need to understand a class's full inheritance hierarchy, so if you're dynamically generating that hierarchy, the type checker won't be able to reason about the resulting class. If your intent is to return a class that is effectively the same as the class it is decorating (at least from an interface perspective), then you can annotate it as follows: def make_cached_object(base_cls: Type[T]) -> Type[T]:
class CachedObject(base_cls): # type: ignore
....
return cast(Type[T], CachedObject) |
Beta Was this translation helpful? Give feedback.
Pyright doesn't support the use of dynamic arguments in a class declaration. Neither does mypy. Static type checkers need to understand a class's full inheritance hierarchy, so if you're dynamically generating that hierarchy, the type checker won't be able to reason about the resulting class.
If your intent is to return a class that is effectively the same as the class it is decorating (at least from an interface perspective), then you can annotate it as follows: