Skip to content

Commit

Permalink
Fix SwigPtrView.__getattr__ (#2259)
Browse files Browse the repository at this point in the history
`hasattr` didn't work with SwigPtrView, because calling `__getattr__` for a missing attribute resulted in a KeyError via `__missing__`. However, hasattr expects an attribute error in that case. Fixed. Added tests.
  • Loading branch information
dweindl authored Jan 6, 2024
1 parent 9886c69 commit 30ed2f0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion python/sdist/amici/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ def __getattr__(self, item) -> Union[np.ndarray, float]:
:returns: value
"""
return self.__getitem__(item)
try:
return self.__getitem__(item)
except KeyError as e:
raise AttributeError(item) from e

def __init__(self, swigptr):
"""
Expand Down
25 changes: 25 additions & 0 deletions python/tests/test_swig_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import copy
import numbers

import pytest

import amici
import numpy as np

Expand Down Expand Up @@ -500,3 +502,26 @@ def test_model_is_deepcopyable(pysb_example_presimulation_module):
assert model1.t0() == model2.t0()
model2.setT0(100 + model2.t0())
assert model1.t0() != model2.t0()


def test_rdataview(sbml_example_presimulation_module):
"""Test some SwigPtrView functionality via ReturnDataView."""
model_module = sbml_example_presimulation_module
model = model_module.getModel()
rdata = amici.runAmiciSimulation(model, model.getSolver())
assert isinstance(rdata, amici.ReturnDataView)

# fields are accessible via dot notation and [] operator,
# __contains__ and __getattr__ are implemented correctly
with pytest.raises(AttributeError):
_ = rdata.nonexisting_attribute

with pytest.raises(KeyError):
_ = rdata["nonexisting_attribute"]

assert not hasattr(rdata, "nonexisting_attribute")
assert "x" in rdata
assert rdata.x == rdata["x"]

# field names are included by dir()
assert "x" in dir(rdata)

0 comments on commit 30ed2f0

Please sign in to comment.