add efficient `__contains__`

This commit is contained in:
Casper da Costa-Luis 2021-10-03 15:39:35 +01:00
parent fc69d5dcf5
commit 983b66c132
No known key found for this signature in database
GPG Key ID: F5126E5FBD2512AD
2 changed files with 15 additions and 0 deletions

View File

@ -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

View File

@ -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