python-typing-koans icon indicating copy to clipboard operation
python-typing-koans copied to clipboard

103-easy-mixed-values discussion

Open J0 opened this issue 3 years ago • 3 comments

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.

J0 avatar May 24 '21 14:05 J0

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

kracekumar avatar May 24 '21 14:05 kracekumar

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]

dmalves avatar Apr 02 '22 01:04 dmalves

Yes, annotating with any isn't highly useful. So list[float] is better.

Advanced: You can also use protocol depending on usecase.

kracekumar avatar Apr 19 '22 16:04 kracekumar