[Python-checkins] bpo-43772: Fix TypeVar.__ror__ (GH-25339)

gvanrossum webhook-mailer at python.org
Sat Apr 10 23:00:09 EDT 2021


https://github.com/python/cpython/commit/9045919bfa820379a66ea67219f79ef6d9ecab49
commit: 9045919bfa820379a66ea67219f79ef6d9ecab49
branch: master
author: Jelle Zijlstra <jelle.zijlstra at gmail.com>
committer: gvanrossum <gvanrossum at gmail.com>
date: 2021-04-10T20:00:05-07:00
summary:

bpo-43772: Fix TypeVar.__ror__ (GH-25339)

files:
A Misc/NEWS.d/next/Library/2021-04-10-19-14-49.bpo-43772.Bxq0zQ.rst
M Lib/test/test_typing.py
M Lib/typing.py

diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index 7183686a6dcde..82c517a4e6002 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -186,6 +186,16 @@ def test_union_unique(self):
         self.assertEqual(Union[X, int].__parameters__, (X,))
         self.assertIs(Union[X, int].__origin__, Union)
 
+    def test_or(self):
+        X = TypeVar('X')
+        # use a string because str doesn't implement
+        # __or__/__ror__ itself
+        self.assertEqual(X | "x", Union[X, "x"])
+        self.assertEqual("x" | X, Union["x", X])
+        # make sure the order is correct
+        self.assertEqual(get_args(X | "x"), (X, ForwardRef("x")))
+        self.assertEqual(get_args("x" | X), (ForwardRef("x"), X))
+
     def test_union_constrained(self):
         A = TypeVar('A', str, bytes)
         self.assertNotEqual(Union[A, str], Union[A])
diff --git a/Lib/typing.py b/Lib/typing.py
index 6461ba23dd7e2..a24c01f0e3b9e 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -648,8 +648,8 @@ def __init__(self, bound, covariant, contravariant):
     def __or__(self, right):
         return Union[self, right]
 
-    def __ror__(self, right):
-        return Union[self, right]
+    def __ror__(self, left):
+        return Union[left, self]
 
     def __repr__(self):
         if self.__covariant__:
diff --git a/Misc/NEWS.d/next/Library/2021-04-10-19-14-49.bpo-43772.Bxq0zQ.rst b/Misc/NEWS.d/next/Library/2021-04-10-19-14-49.bpo-43772.Bxq0zQ.rst
new file mode 100644
index 0000000000000..648357b3faa74
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-04-10-19-14-49.bpo-43772.Bxq0zQ.rst
@@ -0,0 +1 @@
+Fixed the return value of ``TypeVar.__ror__``. Patch by Jelle Zijlstra.



More information about the Python-checkins mailing list