Skip to content

Commit c83e14f

Browse files
author
csaba.nemes
committed
add test, raise original AttributeError if dataclass field not found
1 parent bf77ccc commit c83e14f

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

sphinx_automodapi/autodoc_enhancements.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,17 @@ def type_object_attrgetter(obj, attr, *defargs):
7070

7171
try:
7272
return getattr(obj, attr, *defargs)
73-
except AttributeError:
73+
except AttributeError as e:
7474
# for dataclasses, get the attribute from the __dataclass_fields__
7575
if dataclasses.is_dataclass(obj):
76-
return obj.__dataclass_fields__[attr].name
76+
if attr in obj.__dataclass_fields__:
77+
return obj.__dataclass_fields__[attr].name
78+
else:
79+
# raise original AttributeError
80+
raise e
81+
else:
82+
# raise original AttributeError
83+
raise e
7784

7885

7986
def setup(app):

sphinx_automodapi/tests/test_autodoc_enhancements.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,20 @@ def test_type_attrgetter():
5555

5656
assert type_object_attrgetter(MyClass, 'susy', 'default') == 'default'
5757
assert type_object_attrgetter(MyClass, '__dict__') == MyClass.__dict__
58+
59+
60+
def test_type_attrgetter_for_dataclass():
61+
"""
62+
This tests the attribute getter for non-default dataclass fields
63+
"""
64+
import dataclasses
65+
66+
@dataclasses.dataclass
67+
class MyDataclass:
68+
foo: int
69+
bar: str = "bar value"
70+
71+
with pytest.raises(AttributeError):
72+
getattr(MyDataclass, 'foo')
73+
assert type_object_attrgetter(MyDataclass, 'foo') == 'foo'
74+
assert getattr(MyDataclass, 'bar') == 'bar value'

0 commit comments

Comments
 (0)