Python 3.6 type hinting for a function accepting generic class type and instance type of the same generic type
But Type[T] is TypeVar, so it's not the way to go.
No, you are on the right track - TypeVar
is definitely the way to go. The problem here is rather in pykube.objects.APIObject
class being wrapped in a decorator that mypy
cannot deal with yet. Adding type stubs for pykube.objects
will resolve the issue. Create a directory _typeshed/pykube
and add minimal type stubs for pykube
:
_typeshed/pykube/__init__.pyi
:from typing import Any def __getattr__(name: str) -> Any: ... # incomplete
_typeshed/pykube/objects.pyi
:from typing import Any, ClassVar, Optional from pykube.query import Query def __getattr__(name: str) -> Any: ... # incomplete class ObjectManager: def __getattr__(self, name: str) -> Any: ... # incomplete def __call__(self, api: Any, namespace: Optional[Any] = None) -> Query: ... class APIObject: objects: ClassVar[ObjectManager] def __getattr__(self, name: str) -> Any: ... # incomplete class NamespacedAPIObject(APIObject): ...
Now running
$ MYPYPATH=_typeshed mypy pytest_helm_charts/
resolves obj_type.objects
correctly:
T = TypeVar('T', bound=NamespacedAPIObject)
def wait_for_namespaced_objects_condition(obj_type: Type[T]) -> List[T]:
reveal_type(obj_type.objects)
Output:
pytest_helm_charts/utils.py:29: note: Revealed type is 'pykube.objects.ObjectManager'