Make namespaces comparable.

This commit is contained in:
jfh
2021-10-18 12:28:14 +03:00
parent dd482371e7
commit 809171dcf8
2 changed files with 20 additions and 4 deletions

View File

@@ -1295,8 +1295,6 @@ class SimpleNamespaceTests(unittest.TestCase):
self.assertEqual(repr(ns1), "{name}(x=1, y=2, w=3)".format(name=name))
self.assertEqual(repr(ns2), "{name}(x='spam', _y=5)".format(name=name))
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_equal(self):
ns1 = types.SimpleNamespace(x=1)
ns2 = types.SimpleNamespace()

View File

@@ -1,6 +1,9 @@
use super::PyTypeRef;
use crate::{
function::FuncArgs, types::Constructor, PyClassImpl, PyContext, PyRef, PyResult, PyValue,
builtins::PyDict,
function::FuncArgs,
types::{Comparable, Constructor, PyComparisonOp},
PyClassImpl, PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
VirtualMachine,
};
@@ -31,7 +34,7 @@ impl PyNamespace {
}
}
#[pyimpl(flags(BASETYPE, HAS_DICT), with(Constructor))]
#[pyimpl(flags(BASETYPE, HAS_DICT), with(Constructor, Comparable))]
impl PyNamespace {
#[pymethod(magic)]
fn init(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
@@ -45,6 +48,21 @@ impl PyNamespace {
}
}
impl Comparable for PyNamespace {
fn cmp(
zelf: &PyRef<Self>,
other: &PyObjectRef,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
let other = class_or_notimplemented!(Self, other);
match (zelf.as_object().dict(), other.as_object().dict()) {
(Some(d1), Some(d2)) => PyDict::cmp(&d1, d2.as_object(), op, vm),
_ => Ok(PyComparisonValue::NotImplemented),
}
}
}
pub fn init(context: &PyContext) {
PyNamespace::extend_class(context, &context.types.namespace_type);
}