From 455693aedebf4094fe1e82f26d4264a885b399fe Mon Sep 17 00:00:00 2001 From: Fangjun Kuang Date: Wed, 22 Sep 2021 16:37:20 +0800 Subject: [PATCH] Fix `hasattr` of AttributeDict. (#52) --- icefall/utils.py | 18 +++++++++++++----- test/test_utils.py | 11 +++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/icefall/utils.py b/icefall/utils.py index 2324201c3..23b4dd6c7 100644 --- a/icefall/utils.py +++ b/icefall/utils.py @@ -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( diff --git a/test/test_utils.py b/test/test_utils.py index b4c9358fd..7ac52b289 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -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}")