Reputation: 3726
How do I use enforce_typing
with typing.Generic
?
basic usage of enforce_typing
looks like this and works as expected,
from enforce_typing import enforce_types
@enforce_types
def bar(val : float) -> None:
print(val)
bar(3.14) # PASS
bar('3.14') # TypeError: Expected type '<class 'float'>' for attribute 'val' but received type '<class 'str'>')
I'm trying to use enfore_typing with a generic class (templated). The following code results in TypeError: isinstance() arg 2 must be a type or tuple of types
. How can I use enforce_typing with a templated class?
from enforce_typing import enforce_types
from typing import TypeVar, Generic
T = TypeVar('T')
class Foo(Generic[T]):
@enforce_types
def __init__(self, value: T) -> None:
self.value = value
@property
def val(self) -> T:
return self.value
foo = Foo[float](3.14)
Upvotes: 1
Views: 1124
Reputation: 1699
Your enforce_typing
library (source) seems outdated.
Since Python 3.5, Python supports the typing library, that allows for type hints.
Using a type checker, such as mypy, you can check if typing hints are provided in all times (using the option --strict
).
I recommend using Python version 3.5 or later, use the typing
library and a type checker such as mypy
.
Upvotes: 1