wehnsdaefflae
wehnsdaefflae

Reputation: 906

Python 3.6 Generic Type Hints

I am trying to wrap my head around generic type hints. Reading over this section in PEP 483, I got the impression that in

SENSOR_TYPE = TypeVar("SENSOR_TYPE")
EXP_A = Tuple[SENSOR_TYPE, float]
class EXP_B(Tuple[SENSOR_TYPE, float]):
    ...

EXP_A and EXP_B should identify the same type. In PyCharm #PC-181.4203.547, however, only EXP_Bworks as expected. Upon investigation, I noticed that EXP_B features a __dict__ member while EXP_A doesn't.

That got me to wonder, are both kinds of type definition actually meant to be synonymous?

Edit: My initial goal was to design a generic class EXP of 2-tuples where the second element is always a float and the first element type is variable. I want to use instances of this generic class as follows

from typing import TypeVar, Tuple, Generic

T = TypeVar("T")


class EXP_A(Tuple[T, float]):
    ...


EXP_B = Tuple[T, float]


V = TypeVar("V")


class MyClass(Generic[V]):
    def get_value_a(self, t: EXP_A[V]) -> V:
        return t[0]

    def get_value_b(self, t: EXP_B[V]) -> V:
        return t[0]


class StrClass(MyClass[str]):
    pass


instance = "a", .5

sc = StrClass()
a: str = sc.get_value_a(instance)
b: str = sc.get_value_b(instance)

(The section on user defined generic types in PEP 484 describes this definition of EXP as equivalent to EXP_B in my original code example.)

The problem is that PyCharm complains about the type of instance as a parameter:

Expected type EXP (matched generic type EXP[V]), got Tuple[str, float] instead`.

With EXP = Tuple[T, float] instead, it says:

Expected type 'Tuple[Any]' (matched generic type Tuple[V]), got Tuple[str, float] instead.

Upvotes: 6

Views: 9991

Answers (1)

wehnsdaefflae
wehnsdaefflae

Reputation: 906

I followed @Michael0c2a's advice, headed over to the python typing gitter chat, and asked the question there. The answer was that the example is correct. From this, I follow that

  1. EXP_A and EXP_B are indeed defining the same kind of types
  2. PyCharm as of build #PC-182.4323.49 just doesn't deal with generic type annotations very well.

Upvotes: 6

Related Questions