The following is correct in Python 3.10, but not 3.9:
from typing import Generic from typing_extensions import ParamSpec P = ParamSpec("P") class Foo(Generic[P]): pass foo: Foo[[int, str]] = Foo()
Running the above triggers a TypeError:
TypeError: Parameters to generic types must be types. Got [<class 'int'>, <class 'str'>].
What must I do to get this piece of code to run in Python 3.9?
I get it that ParamSpec is a 3.10 feature. But typing-extensions is supposed to make the code backward-compatible, right? I’m guessing that I must change the syntax of Foo[[int, str]]
to something else, but what?
Related discussion: https://github.com/python/typing/discussions/908
Advertisement
Answer
Solution is to pass a string as the type definition:
foo: "Foo[[int, str]]" = Foo()
Alternatively, the “unsightly double brackets” can be removed:
foo: "Foo[int, str]" = Foo()