The following is correct in Python 3.10, but not 3.9:
JavaScript
x
12
12
1
from typing import Generic
2
from typing_extensions import ParamSpec
3
4
P = ParamSpec("P")
5
6
7
class Foo(Generic[P]):
8
pass
9
10
11
foo: Foo[[int, str]] = Foo()
12
Running the above triggers a TypeError:
JavaScript
1
2
1
TypeError: Parameters to generic types must be types. Got [<class 'int'>, <class 'str'>].
2
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:
JavaScript
1
2
1
foo: "Foo[[int, str]]" = Foo()
2
Alternatively, the “unsightly double brackets” can be removed:
JavaScript
1
2
1
foo: "Foo[int, str]" = Foo()
2