From 983b66c132959482a24d498485b36e1d0beff14e Mon Sep 17 00:00:00 2001 From: Casper da Costa-Luis Date: Sun, 3 Oct 2021 15:39:35 +0100 Subject: [PATCH] add efficient `__contains__` --- tests/tests_tqdm.py | 11 +++++++++++ tqdm/std.py | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/tests/tests_tqdm.py b/tests/tests_tqdm.py index 99f57077..405f5bec 100644 --- a/tests/tests_tqdm.py +++ b/tests/tests_tqdm.py @@ -1973,3 +1973,14 @@ def test_closed(): for i in trange(9, file=our_file, miniters=1, mininterval=0): if i == 5: our_file.close() + + +def test_contains(capsys): + """Test __contains__ doesn't iterate""" + with tqdm(_range(9)) as t: + assert 9 not in t + assert all(i in t for i in range(9)) + out, err = capsys.readouterr() + assert not out + assert ' 0%' in err + assert '100%' not in err diff --git a/tqdm/std.py b/tqdm/std.py index e81c8368..03d9ce5d 100644 --- a/tqdm/std.py +++ b/tqdm/std.py @@ -1131,6 +1131,10 @@ class tqdm(Comparable): else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__") else getattr(self, "total", None)) + def __contains__(self, item): + contains = getattr(self.iterable, '__contains__', None) + return contains(item) if contains is not None else item in self.__iter__() + def __enter__(self): return self