I want to use type hint with string as a key and different classes as a value in a dictionary like below.
JavaScript
x
6
1
configurations: Dict[str, what_class??] = {
2
"dev": Dev,
3
"product": Product,
4
"test": Test,
5
}
6
The classes Dev, Product, Test inherit from a base class “Parent”.
JavaScript
1
12
12
1
class Parent:
2
pass
3
4
class Dev(Parent):
5
pass
6
7
class Product(Parent):
8
pass
9
10
class Test(Parent):
11
pass
12
What is the best way to do the type hint for this?
Do I need to set just “Any” as their type?
Advertisement
Answer
Depends on how accurate you want your hints to be,
- Use the parent class
JavaScript
1
6
1
configurations: Dict[str, Parent] = {
2
"dev": Dev,
3
"product": Product,
4
"test": Test,
5
}
6
- Specify the classes in a union
JavaScript
1
7
1
from typing import Union
2
configurations: Dict[str, Union[Dev, Product, Test]] = {
3
"dev": Dev,
4
"product": Product,
5
"test": Test,
6
}
7
- Create a TypedDict type for this specific dict
JavaScript
1
13
13
1
from typing import TypedDict
2
3
class EnvDict(TypedDict):
4
dev: Dev
5
product: Product
6
test: Test
7
8
configurations: EnvDict = {
9
"dev": Dev,
10
"product": Product,
11
"test": Test,
12
}
13