Skip to content

Commit 2ca23ce

Browse files
Add utility __pos__ and __neg__ operators to TypeVar
This makes it easier to explicitly just use +/-T to make generics co/contra-variant.
1 parent fcb6f4c commit 2ca23ce

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/test_typing.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,17 @@ def test_no_bivariant(self):
236236
with self.assertRaises(ValueError):
237237
TypeVar('T', covariant=True, contravariant=True)
238238

239+
def test_typevar_unary_operators(self):
240+
A = TypeVar('A')
241+
self.assertFalse(A.__covariant__)
242+
self.assertFalse(A.__contravariant__)
243+
A_co = +A
244+
self.assertTrue(A.__covariant__)
245+
self.assertFalse(A.__contravariant__)
246+
A_contra = -A
247+
self.assertFalse(A.__covariant__)
248+
self.assertTrue(A.__contravariant__)
249+
239250

240251
class UnionTests(BaseTestCase):
241252

src/typing.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,12 @@ def __instancecheck__(self, instance):
534534
def __subclasscheck__(self, cls):
535535
raise TypeError("Type variables cannot be used with issubclass().")
536536

537+
def __neg__(self):
538+
return TypeVar(self.__name__, *self.__constraints__, bound=self.__bound__, covariant=False, contravariant=True)
539+
540+
def __pos__(self):
541+
return TypeVar(self.__name__, *self.__constraints__, bound=self.__bound__, covariant=True, contravariant=False)
542+
537543

538544
# Some unconstrained type variables. These are used by the container types.
539545
# (These are not for export.)

0 commit comments

Comments
 (0)