Search code examples
pythoninitializationtyping

Python Initializing and typing at the same time


Can I initialize an empty dictionary and typing it at the same time?

For example something like that, however I don't think this is proper.

self.groups: Dict[str, Group]
self.groups = dict()  

Solution

  • Yes, simply insert the type hint after the variable name in the assignment.

    self.groups: Dict[str, Group] = dict()