Reputation: 6144
Working with Python's typing
module, I would like to create a custom Type that checks for the type of an attribute of an argument. To be more precise, in my case the argument's type is supposed to be an instance of a certain class, and the attribute is supposed to be of a certain Type.
What I want to achieve might be clearer with a minimal example:
class Wrapper:
value: typing.Any
def f(obj: WrapperType[int]) -> None:
assert isinstance(obj, Wrapper) and type(obj.value) is int
How can I create a WrapperType
that reflects the behaviour of this assert
(in terms of typing)? I was unable to find hints for this in the documentation of the typing
module. But I am not sure whether I misunderstood something in there, or whether what I want is just not possible.
Upvotes: 1
Views: 105
Reputation: 531235
Wrapper
should inherit from Typing.Generic
.
from typing import Generic, TypeVar
T = TypeVar('T')
class Wrapper(Generic[T]):
value: T
def f(obj: Wrapper[int]) -> None:
...
Upvotes: 3