8000 gh-102947: Improve traceback when calling `fields()` on a non-datacla… · python/cpython@baf4eb0 · GitHub
[go: up one dir, main page]

Skip to content

Commit baf4eb0

Browse files
authored
gh-102947: Improve traceback when calling fields() on a non-dataclass (#102948)
1 parent 08254be commit baf4eb0

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/dataclasses.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1248,7 +1248,7 @@ def fields(class_or_instance):
12481248
try:
12491249
fields = getattr(class_or_instance, _FIELDS)
12501250
except AttributeError:
1251-
raise TypeError('must be called with a dataclass type or instance')
1251+
raise TypeError('must be called with a dataclass type or instance') from None
12521252

12531253
# Exclude pseudo-fields. Note that fields is sorted by insertion
12541254
# order, so the order of the tuple is as the fields were defined.

Lib/test/test_dataclasses.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@
55
from dataclasses import *
66

77
import abc
8+
import io
89
import pickle
910
import inspect
1011
import builtins
1112
import types
1213
import weakref
14+
import traceback
1315
import unittest
1416
from unittest.mock import Mock
1517
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
@@ -1526,6 +1528,16 @@ class C: pass
15261528
with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
15271529
fields(C())
15281530

1531+
def test_clean_traceback_from_fields_exception(self):
1532+
stdout = io.StringIO()
1533+
try:
1534+
fields(object)
1535+
except TypeError as exc:
1536+
traceback.print_exception(exc, file=stdout)
1537+
printed_traceback = stdout.getvalue()
1538+
self.assertNotIn("AttributeError", printed_traceback)
1539+
self.assertNotIn("__dataclass_fields__", printed_traceback)
1540+
15291541
def test_helper_asdict(self):
15301542
# Basic tests for asdict(), it should return a new dictionary.
15311543
@dataclass
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve traceback when :func:`dataclasses.fields` is called on a
2+
non-dataclass. Patch by Alex Waygood

0 commit comments

Comments
 (0)
0