Skip to content

Add utility __pos__ and __neg__ operators to TypeVar #538

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,17 @@ def test_no_bivariant(self):
with self.assertRaises(ValueError):
TypeVar('T', covariant=True, contravariant=True)

def test_typevar_unary_operators(self):
A = TypeVar('A')
self.assertFalse(A.__covariant__)
self.assertFalse(A.__contravariant__)
A_co = +A
self.assertTrue(A_co.__covariant__)
self.assertFalse(A_co.__contravariant__)
A_contra = -A
self.assertFalse(A_contra.__covariant__)
self.assertTrue(A_contra.__contravariant__)


class UnionTests(BaseTestCase):

Expand Down
6 changes: 6 additions & 0 deletions src/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,12 @@ def __instancecheck__(self, instance):
def __subclasscheck__(self, cls):
raise TypeError("Type variables cannot be used with issubclass().")

def __neg__(self):
return TypeVar(self.__name__, *self.__constraints__, bound=self.__bound__, covariant=False, contravariant=True)

def __pos__(self):
return TypeVar(self.__name__, *self.__constraints__, bound=self.__bound__, covariant=True, contravariant=False)


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