Skip to content

Commit

Permalink
add __delattr__ to DictConfig (#703)
Browse files Browse the repository at this point in the history
  • Loading branch information
jieru-hu authored May 6, 2021
1 parent e3d3bcf commit d5c1d28
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
20 changes: 20 additions & 0 deletions omegaconf/dictconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,26 @@ def __getitem__(self, key: DictKeyType) -> Any:
except Exception as e:
self._format_and_raise(key=key, value=None, cause=e)

def __delattr__(self, key: str) -> None:
"""
Allow deleting dictionary values as attributes
:param key:
:return:
"""
if self._get_flag("readonly"):
self._format_and_raise(
key=key,
value=None,
cause=ReadonlyConfigError(
"DictConfig in read-only mode does not support deletion"
),
)
try:
del self.__dict__["_content"][key]
except KeyError:
msg = "Attribute not found: '$KEY'"
self._format_and_raise(key=key, value=None, cause=ConfigAttributeError(msg))

def __delitem__(self, key: DictKeyType) -> None:
key = self._validate_and_normalize_key(key)
if self._get_flag("readonly"):
Expand Down
17 changes: 17 additions & 0 deletions tests/test_basic_ops_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ def test_getattr_dict() -> None:
assert {"b": 1} == c.a


@mark.parametrize("struct", [False, True])
@mark.parametrize(
"cfg",
[
param({"name": "alice", "age": 1}, id="dict"),
param(User(name="alice", age=1), id="structured_config"),
],
)
def test_delattr(cfg: Any, struct: bool) -> None:
cfg = OmegaConf.create(cfg)
OmegaConf.set_struct(cfg, struct)
delattr(cfg, "name")
assert cfg == {"age": 1}
with raises(ConfigAttributeError):
delattr(cfg, "c")


@mark.parametrize(
"key,match",
[
Expand Down
11 changes: 11 additions & 0 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,17 @@ def finalize(self, cfg: Any) -> None:
),
id="dict,structured:del",
),
param(
Expected(
create=lambda: create_readonly({"foo": "bar"}),
op=lambda cfg: cfg.__delattr__("foo"),
exception_type=ReadonlyConfigError,
msg="DictConfig in read-only mode does not support deletion",
key="foo",
child_node=lambda cfg: cfg.foo,
),
id="dict,readonly:delattr",
),
# creating structured config
param(
Expected(
Expand Down
6 changes: 6 additions & 0 deletions tests/test_readonly.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@
raises(ReadonlyConfigError, match="a"),
id="dict_delitem",
),
param(
{"a": 10},
lambda c: c.__delattr__("a"),
raises(ReadonlyConfigError, match="a"),
id="dict_delattr",
),
# list
param(
[],
Expand Down

0 comments on commit d5c1d28

Please sign in to comment.