5

I’m trying to get the function below to run. However I’m getting an error saying

TypeError: ‘type’ object is not subscriptable 




def dist(loc1: tuple[float], loc2: tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5
Saa17
  • 235
  • 2
  • 3
  • 8

1 Answers1

10

You need to use typing.Tuple, not the tuple class.

from typing import Tuple

def dist(loc1: Tuple[float], loc2: Tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5
dist((1,2),(2,1)) # output 1.4142135623730951
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
tomerar
  • 805
  • 5
  • 10
  • 7
    But this is not necessary in newer Python versions (at least from 3.9 onwards). – 9769953 Feb 08 '22 at 22:21
  • Nor is it true in older versions, because you could also use `from __future__ import annotations`. Or use a forward reference, by putting the hint in quotes. – Martijn Pieters Dec 13 '22 at 14:59