Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic generic type for python's TypedDict?

I'd like to do something like:

from typing import TypeVar, Generic, TypedDict

 T = TypeVar("T")

class Foo(Generic[T], TypedDict):
    bar: T
    ...

foo: Foo[int] = {"bar": 42}

But this yields a type error ("cannot inherit from both a TypedDict and a non-TypedDict base class").

Are there any ways to achieve this result?

like image 571
Jesse Avatar asked Dec 06 '25 09:12

Jesse


2 Answers

This is not possible at the moment. You cannot inherit from both a TypedDict and a non-TypedDict base class. But there is issue active on the cpython repository and a discussion going on to support this feature.

EDIT: As per the latest update, this feature is now available in python 3.11.

like image 133
Abdul Niyas P M Avatar answered Dec 08 '25 21:12

Abdul Niyas P M


If one can't upgrade to Python 3.11, a workaround would be to use typing-extensions module instead of built-in typings module. I use Python 3.10 and typing-extensions 4.9.0 and it works as expected.

like image 34
Pandega Abyan Avatar answered Dec 08 '25 23:12

Pandega Abyan