Skip to content

Commit 27df1a7

Browse files
committed
Merge pull request #832 from vinzenz/bytearray-string-concat
Allow string + bytearray => bytearray. Fixes #780
2 parents 60850a5 + a8e6299 commit 27df1a7

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/runtime/str.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -342,10 +342,16 @@ extern "C" Box* strAdd(BoxedString* lhs, Box* _rhs) {
342342
}
343343

344344
if (!PyString_Check(_rhs)) {
345-
// Note: this is deliberately not returning NotImplemented, even though
346-
// that would be more usual. I assume this behavior of CPython's is
347-
// for backwards compatibility.
348-
raiseExcHelper(TypeError, "cannot concatenate 'str' and '%s' objects", getTypeName(_rhs));
345+
if (PyByteArray_Check(_rhs)) {
346+
Box* rtn = PyByteArray_Concat(lhs, _rhs);
347+
checkAndThrowCAPIException();
348+
return rtn;
349+
} else {
350+
// Note: this is deliberately not returning NotImplemented, even though
351+
// that would be more usual. I assume this behavior of CPython's is
352+
// for backwards compatibility.
353+
raiseExcHelper(TypeError, "cannot concatenate 'str' and '%s' objects", getTypeName(_rhs));
354+
}
349355
}
350356

351357
BoxedString* rhs = static_cast<BoxedString*>(_rhs);

test/tests/bytearray_str_concat.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
assert(('abc' + bytearray('def')) == bytearray('abcdef'))
2+
assert((bytearray('abc') + 'def') == bytearray('abcdef'))
3+
try:
4+
u'abc' + bytearray('def')
5+
assert(False)
6+
except TypeError:
7+
pass
8+
9+
try:
10+
bytearray('abc') + u'def'
11+
assert(False)
12+
except TypeError:
13+
pass

0 commit comments

Comments
 (0)