3

I have a dictionary like so:

d = { 'my_label': ClassInstance() }

I would like to specify type hints to indicate that keys are strings, and values are instances of ClassInstance.

Is this possible in Python 3.8?

I found TypedDict but that seems to attempt to indicate a fixed set of keys. I would to allow any string as key.

Edy Bourne
  • 5,679
  • 13
  • 53
  • 101
  • The code as shown will already infer ``d`` as desired. What else do you need? – MisterMiyagi Mar 24 '21 at 14:10
  • While a tricky question, why would you (practically) want to specify type hints?. Another way could be to serialize your class instance into a JSON string and convert it back when you want. – coderman1234 Mar 24 '21 at 14:10
  • 2
    Does this answer your question? [Type hinting a collection of a specified type](https://stackoverflow.com/questions/24853923/type-hinting-a-collection-of-a-specified-type) – MisterMiyagi Mar 24 '21 at 14:11
  • Well, I'm learning more about Python and don't know the answer to this question, so... may not be practical, but doesn't matter, right? I would appreciate if people down voting could give some info on what's wrong with it. – Edy Bourne Mar 24 '21 at 14:26

2 Answers2

7

Yes, it is possible in Python 3.8

First import dictionary type hint:

from typing import Dict

and add type hint as following:

d: Dict[str, ClassInstance] = { 'my_label': ClassInstance() }

In Python 3.9, it is possible to do this without importing Dict from typing (link to 3.9 documentation) as:

d: dict[str, ClassInstance] = { 'my_label': ClassInstance() }
Leon Markes
  • 382
  • 1
  • 7
2

Use Dict[K, V]:

from typing import Dict

d: Dict[str, ClassInstance] = { 'my_label': ClassInstance() }
AKX
  • 152,115
  • 15
  • 115
  • 172