0

I saw part of code like this:

from typing import List
c: List[float] = [7.3, 1.2, 2.6, 9.9, 'a']

type(c[3])
type(c[4])

output: (float, str)

  1. What if the means of List[float] ?
  2. The last element in the list if not float, so why we are not getting any error ?
  3. When we should use this kind of code ?
Boom
  • 1,145
  • 18
  • 44
  • this mean object c is of type list which hold values of type float. this is just to tell the user the type of data they get in this object . since it is not mandatory to have all defined type hind data, you can add other as when but for that one need t update type hint to `LIst[float, str]` – sahasrara62 Jan 16 '22 at 07:52
  • "The last element in the list if not float, so why we are not getting any error ?" Type hints aren't enforced by the runtime. – juanpa.arrivillaga Jan 16 '22 at 15:42

2 Answers2

3
  1. it means that c is a list with float types in it.
  2. python doesn't force type hinting it's just a hint you can force it with assert.
  3. preferably every time it's just very helpful for you and others especially if you write with an IDE because then it can show you all the methods and members the object has.
yotam rec
  • 587
  • 4
  • 15
2

You're using type hints feature, but python does not enforce static typing.

A simple way to make use of your code, and get your desired behaviour (an error) is with static type checker mypy - http://mypy-lang.org/

python -m pip install mypy
mypy yourCode.py

Result:

test.py:2: error: List item 4 has incompatible type "str"; expected "float"
Found 1 error in 1 file (checked 1 source file)