python-typing-koans
python-typing-koans copied to clipboard
103-easy-mixed-values discussion
The comments mention another way of typing the solution. My solution is as follows:
"""
Koan to learn annotating the Python list of various type of elements
"""
from typing import Union, List
# Annotate mixed type-values. There are two-ways to annotate this
nos: list[Union[int, float]] = [1, 2.0, 3.5]
# Annotate the list of int to list of better types
squares: list[Union[int, float]] = [no * no for no in nos]
I suppose this could be one way to annotate. Would just like to check what the other way is.
Here, the list contains float and int values. nos: list[float] = [1, 2.0, 3.5]
should work.
Quick Answer: when an argument is annotated as having type float, an argument of type int is acceptable. Stackoverflow thread and PEP
This also works:
from typing import Any,
nos: list[Any] = [1, 2.0, 3.5]
But it doesn't tell much about the list. I prefer
nos: list[float] = [1, 2.0, 3.5]
Yes, annotating with any
isn't highly useful. So list[float]
is better.
Advanced: You can also use protocol depending on usecase.