11# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables
22
3- from typing import TypeVar , Generic , Iterable , TypeAlias , assert_type
3+ from typing import TypeVar , Generic , Iterable , TypeAlias , assert_type , Literal
44
55# > A type variable used in a generic function could be inferred to represent
66# > different types in the same code block.
@@ -11,8 +11,13 @@ def fun_1(x: T) -> T: # T here
1111def fun_2 (x : T ) -> T : # and here could be different
1212 return x
1313
14- assert_type (fun_1 (1 ), int )
15- assert_type (fun_2 ('a' ), str )
14+ # One of these two should pass; either is acceptable:
15+ assert_type (fun_1 (1 ), int ) # E[fun1-int]
16+ assert_type (fun_1 (1 ), Literal [1 ]) # E[fun1-int]
17+
18+ # One of these two should pass; either is acceptable:
19+ assert_type (fun_1 ("a" ), str ) # E[fun1-str]
20+ assert_type (fun_1 ("a" ), Literal ["a" ]) # E[fun1-str]
1621
1722# > A type variable used in a method of a generic class that coincides
1823# > with one of the variables that parameterize this class is always bound
@@ -39,8 +44,14 @@ def method(self, x: T, y: S) -> S:
3944 return y
4045
4146x : Foo [int ] = Foo ()
42- assert_type (x .method (0 , "abc" ), str )
43- assert_type (x .method (0 , b"abc" ), bytes )
47+
48+ # Either of these is acceptable; one of the two should pass:
49+ assert_type (x .method (0 , "abc" ), str ) # E[method-str]
50+ assert_type (x .method (0 , "abc" ), Literal ["abc" ]) # E[method-str]
51+
52+ # Either of these is acceptable; one of the two should pass:
53+ assert_type (x .method (0 , b"abc" ), bytes ) # E[method-bytes]
54+ assert_type (x .method (0 , b"abc" ), Literal [b"abc" ]) # E[method-bytes]
4455
4556# > Unbound type variables should not appear in the bodies of generic functions,
4657# > or in the class bodies apart from method definitions.
0 commit comments