Fix hasattr of AttributeDict. (#52)

This commit is contained in:
Fangjun Kuang 2021-09-22 16:37:20 +08:00 committed by GitHub
parent a80e58e15d
commit 455693aede
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 5 deletions

View File

@ -146,12 +146,20 @@ def get_env_info():
}
# See
# https://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute # noqa
class AttributeDict(dict):
__slots__ = ()
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def __getattr__(self, key):
if key in self:
return self[key]
raise AttributeError(f"No such attribute '{key}'")
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
if key in self:
del self[key]
return
raise AttributeError(f"No such attribute '{key}'")
def encode_supervisions(

View File

@ -108,3 +108,14 @@ def test_attribute_dict():
assert s["b"] == 20
s.c = 100
assert s["c"] == 100
assert hasattr(s, "a")
assert hasattr(s, "b")
assert getattr(s, "a") == 10
del s.a
assert hasattr(s, "a") is False
setattr(s, "c", 100)
s.c = 100
try:
del s.a
except AttributeError as ex:
print(f"Caught exception: {ex}")