The typing
module implements type hints in Python 3.5+. However, this is not enforced, it seems to currently only exist for the benefit of static type checkers such as mypy
and PyCharm. I was hoping it would be a viable alternative to duck typing.
Question: Is there a way to turn on dynamic type checking in Python 3.7+ that I didn't find in Google search? So for example, if I define
def greeting(name: str) -> str:
return name
then this should fail at execution time:
greeting([12])
I don't mind paying the time penalty for this checking, since for my purposes I would have to implement it by hand anyway with assert
statements, and the type hints are far more concise and descriptive.
Update: A commenter below has noted that the typen package will enforce the type hints for me dynamically. So this is a positive answer which would update the answer of an older question which was scoped to Python 3.6 and answered in the negative. I have verified that the canonical typen
example works as expected:
from typen import enforce_type_hints
@enforce_type_hints
def halve_integer(a: int) -> float:
return a / 2
halve_integer(5) # 2.5
halve_integer(5.0) # ParameterTypeError
The only drawback is that every function needs to be decorated to get the behavior, rather than there being one switch to turn it on for everything.
Update 2: Answer below also notes that pydantic also solves the problem. so that's 2 positive solutions. However, pydantic
seems geared more towards data modelling, and comes with some strong caveats about their validation decorator:
The validate_arguments decorator is in beta, it has been added to pydantic in v1.5 on a provisional basis. It may change significantly in future releases and its interface will not be concrete until v2. Feedback from the community while it's still provisional would be extremely useful; either comment on #1205 or create a new issue.