]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-40389: Improve repr of typing.Optional (#19714)
authorVlad Serebrennikov <brainvlad@gmail.com>
Thu, 30 Apr 2020 01:06:39 +0000 (04:06 +0300)
committerGitHub <noreply@github.com>
Thu, 30 Apr 2020 01:06:39 +0000 (18:06 -0700)
Lib/test/test_dataclasses.py
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2020-04-25-20-00-58.bpo-40389.FPA6f0.rst [new file with mode: 0644]

index e8fe455fc19b42ab7a7c3616feb51014cdff8c63..b20103bdce51cb78d904a97007ee98b8a6853a00 100644 (file)
@@ -2028,7 +2028,7 @@ class TestDocString(unittest.TestCase):
         class C:
             x: Union[int, type(None)] = None
 
-        self.assertDocStrEqual(C.__doc__, "C(x:Union[int, NoneType]=None)")
+        self.assertDocStrEqual(C.__doc__, "C(x:Optional[int]=None)")
 
     def test_docstring_list_field(self):
         @dataclass
index cab8de0f5efb27636310dbc3e45b0f2404f9ff83..21bc7c81f2a30ed9f2b80c856547b732ebe1bc06 100644 (file)
@@ -1750,7 +1750,7 @@ class GenericTests(BaseTestCase):
         self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''),
                          'Union[Tuple, Tuple[int]]')
         self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''),
-                         'Callable[..., Union[int, NoneType]]')
+                         'Callable[..., Optional[int]]')
         self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''),
                          'Callable[[], List[int]]')
 
index c82989861927dad7de6e9eb0e36605db11f169de..f3cd280a09e27180a7cb453c102429e50e6286be 100644 (file)
@@ -691,6 +691,13 @@ class _GenericAlias(_Final, _root=True):
         return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
 
     def __repr__(self):
+        if (self.__origin__ == Union and len(self.__args__) == 2
+                and type(None) in self.__args__):
+            if self.__args__[0] is not type(None):
+                arg = self.__args__[0]
+            else:
+                arg = self.__args__[1]
+            return (f'typing.Optional[{_type_repr(arg)}]')
         if (self._name != 'Callable' or
                 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
             if self._name:
diff --git a/Misc/NEWS.d/next/Library/2020-04-25-20-00-58.bpo-40389.FPA6f0.rst b/Misc/NEWS.d/next/Library/2020-04-25-20-00-58.bpo-40389.FPA6f0.rst
new file mode 100644 (file)
index 0000000..e7a60a8
--- /dev/null
@@ -0,0 +1 @@
+``repr()`` now returns ``typing.Optional[T]`` when called for ``typing.Union`` of two types, one of which is ``NoneType``.
\ No newline at end of file