Skip to content
Merged
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
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 @@ -683,6 +683,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``.