From 15ad52fbf607b6ccec44a38a8a32a5f1fad635ee Mon Sep 17 00:00:00 2001 From: Dong-hee Na Date: Sun, 17 Oct 2021 00:12:58 +0900 Subject: bpo-45489: Update ForwardRef to support | operator. (GH-28991) --- Lib/test/test_typing.py | 6 ++++++ Lib/typing.py | 6 ++++++ Misc/NEWS.d/next/Library/2021-10-16-23-46-39.bpo-45489.QB0rhG.rst | 2 ++ 3 files changed, 14 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2021-10-16-23-46-39.bpo-45489.QB0rhG.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 38397a0..032fe91 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -2903,6 +2903,12 @@ class ForwardRefTests(BaseTestCase): self.assertNotEqual(gth(Loop, globals())['attr'], Final[int]) self.assertNotEqual(gth(Loop, globals())['attr'], Final) + def test_or(self): + X = ForwardRef('X') + # __or__/__ror__ itself + self.assertEqual(X | "x", Union[X, "x"]) + self.assertEqual("x" | X, Union["x", X]) + class OverloadTests(BaseTestCase): diff --git a/Lib/typing.py b/Lib/typing.py index ada9adb..78d973d 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -719,6 +719,12 @@ class ForwardRef(_Final, _root=True): def __hash__(self): return hash(self.__forward_arg__) + def __or__(self, other): + return Union[self, other] + + def __ror__(self, other): + return Union[other, self] + def __repr__(self): return f'ForwardRef({self.__forward_arg__!r})' diff --git a/Misc/NEWS.d/next/Library/2021-10-16-23-46-39.bpo-45489.QB0rhG.rst b/Misc/NEWS.d/next/Library/2021-10-16-23-46-39.bpo-45489.QB0rhG.rst new file mode 100644 index 0000000..3921437 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-10-16-23-46-39.bpo-45489.QB0rhG.rst @@ -0,0 +1,2 @@ +Update :class:`~typing.ForwardRef` to support ``|`` operator. Patch by +Dong-hee Na. -- cgit v0.12