8000 gh-102947: Improve traceback when calling `fields()` on a non-dataclass by AlexWaygood · Pull Request #102948 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-102947: Improve traceback when calling fields() on a non-dataclass #102948

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 23, 2023
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/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,7 +1248,7 @@ def fields(class_or_instance):
try:
fields = getattr(class_or_instance, _FIELDS)
except AttributeError:
raise TypeError('must be called with a dataclass type or instance')
raise TypeError('must be called with a dataclass type or instance') from None

# Exclude pseudo-fields. Note that fields is sorted by insertion
# order, so the order of the tuple is as the fields were defined.
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
from dataclasses import *

import abc
import io
import pickle
import inspect
import builtins
import types
import weakref
import traceback
import unittest
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
Expand Down Expand Up @@ -1526,6 +1528,16 @@ class C: pass
with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
fields(C())

def test_clean_traceback_from_fields_exception(self):
stdout = io.StringIO()
try:
fields(object)
except TypeError as exc:
traceback.print_exception(exc, file=stdout)
printed_traceback = stdout.getvalue()
self.assertNotIn("AttributeError", printed_traceback)
self.assertNotIn("__dataclass_fields__", printed_traceback)

def test_helper_asdict(self):
# Basic tests for asdict(), it should return a new dictionary.
@dataclass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve traceback when :func:`dataclasses.fields` is called on a
non-dataclass. Patch by Alex Waygood
0