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

Skip to content

Commit 4531fd0

Browse files
authored
[3.10] gh-102947: Improve traceback when calling fields() on a non-dataclass (#102948) (#102954)
1 parent 100da7c commit 4531fd0

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
@@ -1195,7 +1195,7 @@ def fields(class_or_instance):
11951195
try:
11961196
fields = getattr(class_or_instance, _FIELDS)
11971197
except AttributeError:
1198-
raise TypeError('must be called with a dataclass type or instance')
1198+
raise TypeError('must be called with a dataclass type or instance') from None
11991199

12001200
# Exclude pseudo-fields. Note that fields is sorted by insertion
12011201
# 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,10 +5,12 @@
55
from dataclasses import *
66

77
import abc
8+
import io
89
import pickle
910
import inspect
1011
import builtins
1112
import types
13+
import traceback
1214
import unittest
1315
from unittest.mock import Mock
1416
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
@@ -1414,6 +1416,16 @@ class C: pass
14141416
with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
14151417
fields(C())
14161418

1419+
def test_clean_traceback_from_fields_exception(self):
1420+
stdout = io.StringIO()
1421+
try:
1422+
fields(object)
1423+
except TypeError as exc:
1424+
traceback.print_exception(exc, file=stdout)
1425+
printed_traceback = stdout.getvalue()
1426+
self.assertNotIn("AttributeError", printed_traceback)
1427+
self.assertNotIn("__dataclass_fields__", printed_traceback)
1428+
14171429
def test_helper_asdict(self):
14181430
# Basic tests for asdict(), it should return a new dictionary.
14191431
@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