Skip to content

Commit 2365af0

Browse files
csaba.nemeslpsinger
authored andcommitted
add test, raise original AttributeError if dataclass field not found
1 parent ccdfd2b commit 2365af0

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
@@ -62,10 +62,17 @@ def type_object_attrgetter(obj, attr, *defargs):
6262

6363
try:
6464
return getattr(obj, attr, *defargs)
65-
except AttributeError:
65+
except AttributeError as e:
6666
# for dataclasses, get the attribute from the __dataclass_fields__
6767
if dataclasses.is_dataclass(obj):
68-
return obj.__dataclass_fields__[attr].name
68+
if attr in obj.__dataclass_fields__:
69+
return obj.__dataclass_fields__[attr].name
70+
else:
71+
# raise original AttributeError
72+
raise e
73+
else:
74+
# raise original AttributeError
75+
raise e
6976

7077

7178
def setup(app):

sphinx_automodapi/tests/test_autodoc_enhancements.py

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

4242
assert type_object_attrgetter(MyClass, 'susy', 'default') == 'default'
4343
assert type_object_attrgetter(MyClass, '__dict__') == MyClass.__dict__
44+
45+
46+
def test_type_attrgetter_for_dataclass():
47+
"""
48+
This tests the attribute getter for non-default dataclass fields
49+
"""
50+
import dataclasses
51+
52+
@dataclasses.dataclass
53+
class MyDataclass:
54+
foo: int
55+
bar: str = "bar value"
56+
57+
with pytest.raises(AttributeError):
58+
getattr(MyDataclass, 'foo')
59+
assert type_object_attrgetter(MyDataclass, 'foo') == 'foo'
60+
assert getattr(MyDataclass, 'bar') == 'bar value'

0 commit comments

Comments
 (0)