Skip to content

Commit

Permalink
add test, raise original AttributeError if dataclass field not found
Browse files Browse the repository at this point in the history
  • Loading branch information
csaba.nemes committed Sep 23, 2020
1 parent bf77ccc commit c83e14f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
11 changes: 9 additions & 2 deletions sphinx_automodapi/autodoc_enhancements.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,17 @@ def type_object_attrgetter(obj, attr, *defargs):

try:
return getattr(obj, attr, *defargs)
except AttributeError:
except AttributeError as e:
# for dataclasses, get the attribute from the __dataclass_fields__
if dataclasses.is_dataclass(obj):
return obj.__dataclass_fields__[attr].name
if attr in obj.__dataclass_fields__:
return obj.__dataclass_fields__[attr].name
else:
# raise original AttributeError
raise e
else:
# raise original AttributeError
raise e


def setup(app):
Expand Down
17 changes: 17 additions & 0 deletions sphinx_automodapi/tests/test_autodoc_enhancements.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,20 @@ def test_type_attrgetter():

assert type_object_attrgetter(MyClass, 'susy', 'default') == 'default'
assert type_object_attrgetter(MyClass, '__dict__') == MyClass.__dict__


def test_type_attrgetter_for_dataclass():
"""
This tests the attribute getter for non-default dataclass fields
"""
import dataclasses

@dataclasses.dataclass
class MyDataclass:
foo: int
bar: str = "bar value"

with pytest.raises(AttributeError):
getattr(MyDataclass, 'foo')
assert type_object_attrgetter(MyDataclass, 'foo') == 'foo'
assert getattr(MyDataclass, 'bar') == 'bar value'

0 comments on commit c83e14f

Please sign in to comment.