Skip to content

Commit

Permalink
bpo-40389: Improve repr of typing.Optional (#19714)
Browse files Browse the repository at this point in the history
  • Loading branch information
Endilll committed Apr 30, 2020
1 parent b1e11c3 commit 138a9b9
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2028,7 +2028,7 @@ def test_docstring_one_field_with_default_none(self):
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
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1750,7 +1750,7 @@ def test_extended_generic_rules_repr(self):
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]]')

Expand Down
7 changes: 7 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,13 @@ def copy_with(self, params):
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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
``repr()`` now returns ``typing.Optional[T]`` when called for ``typing.Union`` of two types, one of which is ``NoneType``.

0 comments on commit 138a9b9

Please sign in to comment.