Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ~T mean in the runtime repr of a type?

While playing with Python's typing module I came across something curious:

>>> from typing import List, Tuple
>>> List[Tuple[int]]
typing.List<~T>[typing.Tuple[int]]

What's this Java-like syntax List<~T>? What does it mean?

like image 416
bjd2385 Avatar asked Sep 18 '25 23:09

bjd2385


1 Answers

That's not actual Python syntax, so don't try to use it in a program. That said, this is how they chose to represent a generic type's type parameters. In a generic type's repr, the declared type parameters are listed in Java-like <> angle brackets, with a +, -, or ~ before each type parameter depending on whether that parameter is covariant, contravariant, or neither.

typing.List takes a single non-covariant, non-contravariant type parameter named T, so it gets a <~T> after the name.

You'll notice that typing.Tuple doesn't have any <> stuff after its name. Tuple is a weird special case, since it takes a variable number of type parameters.

like image 100
user2357112 supports Monica Avatar answered Sep 20 '25 15:09

user2357112 supports Monica