In Python, types are first class objects. As such, I can create a dictionary with types as the keys. For example:
mydict = {
int: "Hello!",
str: 12,
SomeClassName: "Hello again!"}
Assuming that my dictionary will be populated with arbitrary types as keys, how do I type annotate that?
I've tried:
mydict: dict[type, Any] = {
int: "Hello!",
str: 12,
SomeClassName: "Hello again!"}
and:
mydict: dict[Type[Any], Any] = {
int: "Hello!",
str: 12,
SomeClassName: "Hello again!"}
and even:
mydict: dict[Any, Any] = {
int: "Hello!",
str: 12,
SomeClassName: "Hello again!"}
But mypy
complains about the assignment for all of those. What is the proper way to type annotate a dictionary that takes any type as a key?
If I had just certain types like int
and str
, I could probably annotate it as dict[Union[Type[int], Type[str]]], Any]
but since I want to support keys of any type, that just doesn't cut it.
Without the type annotation, the syntax works fine and I can even retrieve specific values from the dictionary. For example:
mydict = {
int: "Hello!",
str: 12,
SomeClassName: "Hello again!"}
print(mydict[int])
...and it succesfully prints out Hello!
If it matters any, I'm using Python 3.9.6 and mypy 0.812.