Skip to content

Commit 1951ed1

Browse files
committed
gh-62912: return correct exception in python versions for operator.concat/iconcat
1 parent 617f4cc commit 1951ed1

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/operator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def xor(a, b):
153153

154154
def concat(a, b):
155155
"Same as a + b, for a and b sequences."
156-
if not hasattr(a, '__getitem__'):
156+
if not hasattr(type(a), '__getitem__'):
157157
msg = "'%s' object can't be concatenated" % type(a).__name__
158158
raise TypeError(msg)
159159
return a + b
@@ -356,7 +356,7 @@ def iand(a, b):
356356

357357
def iconcat(a, b):
358358
"Same as a += b, for a and b sequences."
359-
if not hasattr(a, '__getitem__'):
359+
if not hasattr(type(a), '__getitem__'):
360360
msg = "'%s' object can't be concatenated" % type(a).__name__
361361
raise TypeError(msg)
362362
a += b

Lib/test/test_operator.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,12 @@ def test_concat(self):
160160
self.assertEqual(operator.concat(Seq1([5, 6]), Seq1([7])), [5, 6, 7])
161161
self.assertEqual(operator.concat(Seq2([5, 6]), Seq2([7])), [5, 6, 7])
162162
self.assertRaises(TypeError, operator.concat, 13, 29)
163+
class A:
164+
pass
165+
a = A()
166+
a.__getitem__ = lambda: "spam"
167+
self.assertRaisesRegex(TypeError, "object can't be concatenated",
168+
operator.concat, a, a)
163169

164170
def test_countOf(self):
165171
operator = self.module
@@ -551,6 +557,13 @@ def test_iconcat_without_getitem(self):
551557
with self.assertRaisesRegex(TypeError, msg):
552558
operator.iconcat(1, 0.5)
553559

560+
class A:
561+
pass
562+
a = A()
563+
a.__getitem__ = lambda: "spam"
564+
self.assertRaisesRegex(TypeError, "object can't be concatenated",
565+
operator.iconcat, a, a)
566+
554567
def test_index(self):
555568
operator = self.module
556569
class X:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :func:`operator.concat` and :func:`operator.iconcat` to return a correct
2+
exception message, if the object class lacks the :meth:`~object.__getitem__`
3+
dunder. Patch by Sergey B Kirpichev.

0 commit comments

Comments
 (0)