Skip to content

Commit

Permalink
Merge pull request #34 from nanjekyejoannah/warn_string_cmp_with_rece…
Browse files Browse the repository at this point in the history
…nt_assumptions

Warn for string cmp with new string warning assumptions
  • Loading branch information
ltratt authored Dec 30, 2023
2 parents 35e650e + 29ae1a9 commit bb5d72c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Lib/test/test_StringIO.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,23 @@ def test_unicode(self):
self.assertEqual(s, unicode('abcuvwxyz!'))
self.assertEqual(type(s), types.UnicodeType)

def test_py3k_string_cmp(self):
"abc" == 123
"abc" == object()
u"abc" == 123
u"abc" == object()
with test_support.check_py3k_warnings(("comparing unicode and byte strings has different semantics in 3.x: convert the first string to bytes.",
DeprecationWarning)):
u"test str" == "test unicode"
deprecations = []
if sys.py3kwarning:
deprecations += [
("comparing unicode and byte strings has different semantics in 3.x: convert the second string to byte.", DeprecationWarning),
("comparing unicode and byte strings has different semantics in 3.x: convert the first string to bytes.", DeprecationWarning)
]
with test_support.check_py3k_warnings(*deprecations):
"test str" == u"test unicode"

class TestcStringIO(TestGenericStringIO):
MODULE = cStringIO

Expand Down
3 changes: 3 additions & 0 deletions Objects/stringobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,9 @@ string_richcompare(PyStringObject *a, PyStringObject *b, int op)
PyObject *result;

/* Make sure both arguments are strings. */
if ((PyString_Check(a) && PyUnicode_Check(b)) && PyErr_WarnPy3k("comparing unicode and byte strings has different semantics in 3.x: convert the second string to byte.", 1) < 0) {
goto out;
}
if (!(PyString_Check(a) && PyString_Check(b))) {
result = Py_NotImplemented;
goto out;
Expand Down
4 changes: 4 additions & 0 deletions Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -6269,6 +6269,10 @@ PyObject *PyUnicode_RichCompare(PyObject *left,
{
int result;

if (PyString_Check(right) && PyErr_WarnPy3k("comparing unicode and byte strings has different semantics in 3.x: convert the first string to bytes.", 1) < 0){
goto onError;
}

result = PyUnicode_Compare(left, right);
if (result == -1 && PyErr_Occurred())
goto onError;
Expand Down

0 comments on commit bb5d72c

Please sign in to comment.