Skip to content

Commit 6bd3ecf

Browse files
authored
bpo-44558: Match countOf is/== treatment to c (GH-27007)
1 parent 8363c53 commit 6bd3ecf

File tree

5 files changed

+13
-6
lines changed

5 files changed

+13
-6
lines changed

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
@@ -153,6 +153,11 @@ def test_countOf(self):
153153
self.assertRaises(ZeroDivisionError, operator.countOf, BadIterable(), 1)
154154
self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 3), 1)
155155
self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 5), 0)
156+
# is but not ==
157+
nan = float("nan")
158+
self.assertEqual(operator.countOf([nan, nan, 21], nan), 2)
159+
# == but not is
160+
self.assertEqual(operator.countOf([{}, 1, {}, 2], {}), 2)
156161

157162
def test_delitem(self):
158163
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
@@ -507,12 +507,12 @@ _operator_indexOf_impl(PyObject *module, PyObject *a, PyObject *b)
507507
/*[clinic input]
508508
_operator.countOf = _operator.indexOf
509509
510-
Return the number of times b occurs in a.
510+
Return the number of items in a which are, or which equal, b.
511511
[clinic start generated code]*/
512512

513513
static Py_ssize_t
514514
_operator_countOf_impl(PyObject *module, PyObject *a, PyObject *b)
515-
/*[clinic end generated code: output=9e1623197daf3382 input=0c3a2656add252db]*/
515+
/*[clinic end generated code: output=9e1623197daf3382 input=93ea57f170f3f0bb]*/
516516
{
517517
return PySequence_Count(a, b);
518518
}

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)