Skip to content

Commit

Permalink
Optimized ListConfig.__contains__()
Browse files Browse the repository at this point in the history
Speedup from 1200x slower than standard list contains to only 68 times slower :)
  • Loading branch information
omry committed Feb 9, 2021
1 parent 479a01e commit 65f2d1b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions news/529.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ListConfig.__contains__ optimized, about 15x faster in a benchmark
13 changes: 12 additions & 1 deletion omegaconf/listconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,18 @@ def __iadd__(self, other: Iterable[Any]) -> "ListConfig":
return self

def __contains__(self, item: Any) -> bool:
for x in iter(self):
if self._is_none():
raise TypeError(
"Cannot check if an item is in a ListConfig object representing None"
)
if self._is_missing():
raise MissingMandatoryValue(
"Cannot check if an item is in missing ListConfig"
)

lst = self.__dict__["_content"]
for x in lst:
x = x._dereference_node()
if x == item:
return True
return False
Expand Down
26 changes: 26 additions & 0 deletions tests/test_basic_ops_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,32 @@ def test_in_with_interpolation() -> None:
assert 10 in c.a


@pytest.mark.parametrize(
("lst", "expected"),
[
pytest.param(
ListConfig(content=None),
pytest.raises(
TypeError,
match="Cannot check if an item is in a ListConfig object representing None",
),
id="ListConfig(None)",
),
pytest.param(
ListConfig(content="???"),
pytest.raises(
MissingMandatoryValue,
match="Cannot check if an item is in missing ListConfig",
),
id="ListConfig(???)",
),
],
)
def test_not_in_special_lists(lst: Any, expected: Any) -> None:
with expected:
"foo" not in lst


def test_list_config_with_list() -> None:
c = OmegaConf.create([])
assert isinstance(c, ListConfig)
Expand Down

0 comments on commit 65f2d1b

Please sign in to comment.