Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import unittest.mock
import weakref
import typing
import re

c_types = import_fresh_module('types', fresh=['_types'])
py_types = import_fresh_module('types', blocked=['_types'])
Expand Down Expand Up @@ -2009,6 +2010,24 @@ def test_equal(self):
self.assertEqual(ns1, ns2)
self.assertNotEqual(ns2, types.SimpleNamespace())

def test_richcompare(self):
ns1 = types.SimpleNamespace(x=1)
ns2 = types.SimpleNamespace(y=2)

msg = re.escape(
"not supported between instances of "
"'types.SimpleNamespace' and 'types.SimpleNamespace'"
)

with self.assertRaisesRegex(TypeError, msg):
ns1 > ns2
with self.assertRaisesRegex(TypeError, msg):
ns1 >= ns2
with self.assertRaisesRegex(TypeError, msg):
ns1 < ns2
with self.assertRaisesRegex(TypeError, msg):
ns1 <= ns2

def test_nested(self):
ns1 = types.SimpleNamespace(a=1, b=2)
ns2 = types.SimpleNamespace()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve :exc:`TypeError` error message, when richcomparing two
:class:`types.SimpleNamespace` objects.
8 changes: 6 additions & 2 deletions Objects/namespaceobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,14 @@ namespace_clear(PyObject *op)
static PyObject *
namespace_richcompare(PyObject *self, PyObject *other, int op)
{
if (PyObject_TypeCheck(self, &_PyNamespace_Type) &&
PyObject_TypeCheck(other, &_PyNamespace_Type))
if (
(op == Py_EQ || op == Py_NE) &&
PyObject_TypeCheck(self, &_PyNamespace_Type) &&
PyObject_TypeCheck(other, &_PyNamespace_Type)
) {
return PyObject_RichCompare(((_PyNamespaceObject *)self)->ns_dict,
((_PyNamespaceObject *)other)->ns_dict, op);
}
Py_RETURN_NOTIMPLEMENTED;
}

Expand Down
Loading