Skip to content

Commit 9761abf

Browse files
authored
[3.9] bpo-44558: Match countOf is/== treatment to c (GH-27007). (GH-27055)
1 parent 324b932 commit 9761abf

5 files changed

Lines changed: 13 additions & 6 deletions

File tree

Lib/operator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,10 @@ def contains(a, b):
155155
return b in a
156156

157157
def countOf(a, b):
158-
"Return the number of times b occurs in a."
158+
"Return the number of items in a which are, or which equal, b."
159159
count = 0
160160
for i in a:
161-
if i == b:
161+
if i is b or i == b:
162162
count += 1
163163
return count
164164

Lib/test/test_operator.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,11 @@ def test_countOf(self):
149149
self.assertRaises(ZeroDivisionError, operator.countOf, BadIterable(), 1)
150150
self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 3), 1)
151151
self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 5), 0)
152+
# is but not ==
153+
nan = float("nan")
154+
self.assertEqual(operator.countOf([nan, nan, 21], nan), 2)
155+
# == but not is
156+
self.assertEqual(operator.countOf([{}, 1, {}, 2], {}), 2)
152157

153158
def test_delitem(self):
154159
operator = self.module
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Match the docstring and python implementation of :func:`~operator.countOf` to the behavior
2+
of its c implementation.

Modules/_operator.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -494,12 +494,12 @@ _operator_indexOf_impl(PyObject *module, PyObject *a, PyObject *b)
494494
/*[clinic input]
495495
_operator.countOf = _operator.indexOf
496496
497-
Return the number of times b occurs in a.
497+
Return the number of items in a which are, or which equal, b.
498498
[clinic start generated code]*/
499499

500500
static Py_ssize_t
501501
_operator_countOf_impl(PyObject *module, PyObject *a, PyObject *b)
502-
/*[clinic end generated code: output=9e1623197daf3382 input=0c3a2656add252db]*/
502+
/*[clinic end generated code: output=9e1623197daf3382 input=93ea57f170f3f0bb]*/
503503
{
504504
return PySequence_Count(a, b);
505505
}

Modules/clinic/_operator.c.h

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)