xpilot
xpilot

Reputation: 1019

Get element types from typing.Tuple

I have a function that takes a type and recursively generates an element of that type. For example, for typing.NamedTuples I do this:

def make_type(type_):
  ...
  if issubclass(type_, typing.NamedTuple):
    return type_(**{f: make_type(t) for f, t in type_._field_types.items()})

However, I'm not sure how to handle typing.Tuples, as they don't seem to have an equivalent of _field_types. For example, if I had a Tuple[int, int] I would like to get back (int, int).

Upvotes: 1

Views: 285

Answers (1)

xpilot
xpilot

Reputation: 1019

Turns out I can just use the __args__ field of my type:

Pair = typing.Tuple[int, int]
Pair.__args__ # (int, int)

I assume that this is just the argument list passed into the Tuple type constructor. Feels a bit undocumented, but oh well.

Upvotes: 1

Related Questions