Dustin
Dustin

Reputation: 493

Typing Key, Value of a TypedDict without additional class in Python 3.8

I would like to use the Typing module in Python 3.8. Python 3.8 features a TypedDict in the Typing module. I have a function with arguments like this: from Typing import

def groupDataFrame(df: pd.DataFrame, somelist: List[str], somedict: TypedDict[str: Callable]:
    pass

But it doesn't allow me to specify the dictionary like this, throwing a TypeError: TypeError: '_TypedDictMeta' object is not subscriptable

There is a solution that utilizes an additional class, but is quite an ugly solution:

How to get key type from pythons TypedDict

Any idea how to do it without an additional class?

Upvotes: 2

Views: 2060

Answers (1)

AKX
AKX

Reputation: 169388

You can't subscript TypedDict; you're meant to instantiate or subclass one according to the docs:

Point2D = TypedDict('Point2D', x=int, y=int, label=str)
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

With that in mind, you can just inline that in your signature:

def x(a: TypedDict('A', x=int)):
  pass

Upvotes: 3

Related Questions