Skip to content
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

fix #214: AttributeDict does not support hasattr #269

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
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ orbeckst, jandom
* removed support for legacy Python (<= 3.7) (#259)
* fixed GROMACS TOP reader not reading angle parameters from topology
file (#261)
* fixed AttributeDict does not support hasattr (#214)


2023-09-16 0.8.5
Expand Down
11 changes: 10 additions & 1 deletion gromacs/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,19 @@ class AttributeDict(dict):
"""A dictionary with pythonic access to keys as attributes --- useful for interactive work."""

def __getattribute__(self, x):
# First try to get the attribute from the class parent (AttributeDict)
try:
return super(AttributeDict, self).__getattribute__(x)

# AttributeError is raised if the attribute doesn't exist
except AttributeError:
return self[x]
# Next try to get the attribute from self (dict)
try:
return self[x]

# If that fails, raise an AttributeError exception
except KeyError:
raise AttributeError

def __setattr__(self, name, value):
try:
Expand Down
5 changes: 5 additions & 0 deletions tests/test_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ def test_dict_set(self):
self.d["gargl"] = "blaster"
assert self.d["gargl"] == "blaster"

def test_dict_hasattr(self):
assert hasattr(self.d, "foo")
assert hasattr(self.d, "baz")
assert not hasattr(self.d, "bar")

def test_pickle(self):
try:
dump = pickle.dumps(self.d, pickle.HIGHEST_PROTOCOL)
Expand Down