Suppose I want to type hint a generic function in Python before 3.12, when the new parameter syntax was introduced:
def max[T](args: Iterable[T]) -> T:
...
Then I have the option of using string type hints:
def max(args: Iterable["T"]) -> "T":
...
Or typing variables:
T = TypeVar("T")
def max(args: Iterable[T]) -> T:
...
I like the latter approach more, but introducing an extra global variable is definitely a drawback. I decided to combine generic type hinting with the walrus operator, like this:
def max(args: Iterable[T := TypeVar("T")]) -> T:
...
Or
def max(args: Iterable[T := int | float]) -> T:
...
Code like this runs without errors, but some typing libraries don't recognise this syntax. What are the drawbacks to writing code like this?
Apparently it did not get into documentation for some reason, but your question is addressed in PEP484:
So, typecheckers should reject your suggested snippet.
mypydoes,Pyrightalso does, andPyredoes as well.So, the main drawback to writing code like this is the fact that such code is non-conformant and is not interpreted by typecheckers correctly.