From c06d3b9a6dc55891504dd5bdfd223c938b24a73f Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sun, 5 Dec 2021 22:41:58 +0200 Subject: [PATCH 1/2] bpo-45662: Fix the repr of InitVar with a type alias to the built-in class (GH-29291) For example, InitVar[list[int]]. (cherry picked from commit 1fd4de5bddbbf2a97cdbac4d298c89e1156bdc6c) Co-authored-by: Serhiy Storchaka --- Lib/dataclasses.py | 2 +- Lib/test/test_dataclasses.py | 4 ++++ .../next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index c98e74d4ff9cc2..8f1e75a7b1b672 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -207,7 +207,7 @@ def __init__(self, type): self.type = type def __repr__(self): - if isinstance(self.type, type): + if isinstance(self.type, type) and not isinstance(self.type, GenericAlias): type_name = self.type.__name__ else: # typing objects, e.g. List[int] diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py index ad981d1cc654f8..b91920258a471e 100644 --- a/Lib/test/test_dataclasses.py +++ b/Lib/test/test_dataclasses.py @@ -1124,6 +1124,10 @@ def test_init_var_preserve_type(self): self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]') self.assertEqual(repr(InitVar[List[int]]), 'dataclasses.InitVar[typing.List[int]]') + self.assertEqual(repr(InitVar[list[int]]), + 'dataclasses.InitVar[list[int]]') + self.assertEqual(repr(InitVar[int|str]), + 'dataclasses.InitVar[int | str]') def test_init_var_inheritance(self): # Note that this deliberately tests that a dataclass need not diff --git a/Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst b/Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst new file mode 100644 index 00000000000000..050b443dd7cb26 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst @@ -0,0 +1,2 @@ +Fix the repr of :data:`dataclasses.InitVar` with a type alias to the +built-in class, e.g. ``InitVar[list[int]]``. From 3d37282a80bf9a35a6a6bbfe20fa1bacec78c457 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Tue, 7 Dec 2021 14:03:01 +0200 Subject: [PATCH 2/2] Update Lib/test/test_dataclasses.py --- Lib/test/test_dataclasses.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py index b91920258a471e..016d814a59b138 100644 --- a/Lib/test/test_dataclasses.py +++ b/Lib/test/test_dataclasses.py @@ -1126,8 +1126,6 @@ def test_init_var_preserve_type(self): 'dataclasses.InitVar[typing.List[int]]') self.assertEqual(repr(InitVar[list[int]]), 'dataclasses.InitVar[list[int]]') - self.assertEqual(repr(InitVar[int|str]), - 'dataclasses.InitVar[int | str]') def test_init_var_inheritance(self): # Note that this deliberately tests that a dataclass need not