When declaring a dictionary as a literal, is there a way to type-hint what value I am expecting for a specific key?
And then, for discussion: are there guiding principles around dictionary typing in Python? I'm wondering whether it is considered bad practice to mix types in dictionaries.
Here's an example:
Consider the declaration of a dictionary in a class's __init__
:
(Disclaimer: I realize in the example, some of the .elements
entries would probably be more appropriate as class attributes, but it's for the sake of the example.)
class Rectangle:
def __init__(self, corners: Tuple[Tuple[float, float]], **kwargs):
self.x, self.z = corners[0][0], corners[0][1]
self.elements = {
'front': Line(corners[0], corners[1]),
'left': Line(corners[0], corners[2]),
'right': Line(corners[1], corners[3]),
'rear': Line(corners[3], corners[2]),
'cog': calc_cog(corners),
'area': calc_area(corners),
'pins': None
}
class Line:
def __init__(self, p1: Tuple[float, float], p2: Tuple[float, float]):
self.p1, self.p2 = p1, p2
self.vertical = p1[0] == p2[0]
self.horizontal = p1[1] == p2[1]
When I type type the following,
rec1 = Rectangle(rec1_corners, show=True, name='Nr1')
rec1.sides['f...
Pycharm will suggest 'front'
for me. Better still, when I do
rec1.sides['front'].ver...
Pycharm will suggest .vertical
So Pycharm remembers the keys from the dictionary literal declaration in the class's __init__
, and also their values' expected types. Or rather: it expects any value to have any one of the types that are in the literal declaration - probably the same as if I had done a self.elements = {} # type: Union[type1, type2]
would do. Either way, I find it super helpful.
If your functions have their outputs type-hinted, then Pycharm will also take that into account.
So assuming that in the Rectangle
example above, I wanted to indicate that pins
is a list of Pin
objects... if pins
was a normal class attribute, it would be:
self.pins = None # type: List[Pin]
(provided the necessary imports were done)
Is there a way to give the same type hint in the dictionary literal declaration?
The following does not achieve what I am looking for:
Add a Union[...]
type hint at the end of the literal declaration?
'area': calc_area(corners),
'pins': None
} # type: Union[Line, Tuple[float, float], float, List[Pin]]
Adding a type-hint to every line:
'area': calc_area(corners), # type: float
'pins': None # type: List[Pin]
}
Is there a best practice for this kind of thing?
Some more background:
I work with Python in PyCharm and I make extensive use of typing, since it helps me to predict and validate my work as I go along. When I create new classes, I also sometimes throw some less frequently used properties into a dictionary to avoid cluttering the object with too many attributes (this is helpful in debug mode).
See Question&Answers more detail:
os