Skip to content

bpo-26915: Test identity first in membership operation #503

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,8 @@ def index(self, value, start=0, stop=None):
i = start
while stop is None or i < stop:
try:
if self[i] == value:
v = self[i]
if v is value or v == value:
return i
except IndexError:
break
Expand All @@ -917,7 +918,7 @@ def index(self, value, start=0, stop=None):

def count(self, value):
'S.count(value) -> integer -- return number of occurrences of value'
return sum(1 for v in self if v == value)
return sum(1 for v in self if v is value or v == value)

Sequence.register(tuple)
Sequence.register(str)
Expand Down
17 changes: 13 additions & 4 deletions Lib/test/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1309,20 +1309,29 @@ def test_issue26915(self):
class CustomEqualObject:
def __eq__(self, other):
return False
class CustomSequence(list):
def __contains__(self, value):
return Sequence.__contains__(self, value)
class CustomSequence(Sequence):
def __init__(self, seq):
self._seq = seq
def __getitem__(self, index):
return self._seq[index]
def __len__(self):
return len(self._seq)

nan = float('nan')
obj = CustomEqualObject()
seq = CustomSequence([nan, obj, nan])
containers = [
CustomSequence([nan, obj]),
seq,
ItemsView({1: nan, 2: obj}),
ValuesView({1: nan, 2: obj})
]
for container in containers:
for elem in container:
self.assertIn(elem, container)
self.assertEqual(seq.index(nan), 0)
self.assertEqual(seq.index(obj), 1)
self.assertEqual(seq.count(nan), 2)
self.assertEqual(seq.count(obj), 1)

def assertSameSet(self, s1, s2):
# coerce both to a real set then check equality
Expand Down
3 changes: 3 additions & 0 deletions Misc/NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,9 @@ Extension Modules
Library
-------

- bpo-26915: index() and count() methods of collections.abc.Sequence now
check identity before checking equality when do comparisons.

- bpo-28682: Added support for bytes paths in os.fwalk().

- bpo-29623: Allow use of path-like object as a single argument in
Expand Down