Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6ffeeb2

Browse files
gh-102947: Improve traceback when calling fields() on a non-dataclass (GH-102948)
(cherry picked from commit baf4eb0) Co-authored-by: Alex Waygood <[email protected]>
1 parent f79cfb6 commit 6ffeeb2

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
@@ -1234,7 +1234,7 @@ def fields(class_or_instance):
12341234
try:
12351235
fields = getattr(class_or_instance, _FIELDS)
12361236
except AttributeError:
1237-
raise TypeError('must be called with a dataclass type or instance')
1237+
raise TypeError('must be called with a dataclass type or instance') from None
12381238

12391239
# Exclude pseudo-fields. Note that fields is sorted by insertion
12401240
# 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
@@ -1500,6 +1502,16 @@ class C: pass
15001502
with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
15011503
fields(C())
15021504

1505+
def test_clean_traceback_from_fields_exception(self):
1506+
stdout = io.StringIO()
1507+
try:
1508+
fields(object)
1509+
except TypeError as exc:
1510+
traceback.print_exception(exc, file=stdout)
1511+
printed_traceback = stdout.getvalue()
1512+
self.assertNotIn("AttributeError", printed_traceback)
1513+
self.assertNotIn("__dataclass_fields__", printed_traceback)
1514+
15031515
def test_helper_asdict(self):
15041516
# Basic tests for asdict(), it should return a new dictionary.
15051517
@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)