Skip to content

Implemented __reduce__ method for types.SimpleNamespace #4975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 0 additions & 2 deletions Lib/test/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1793,8 +1793,6 @@ class Spam(types.SimpleNamespace):
self.assertIs(type(spam), Spam)
self.assertEqual(vars(spam), {'ham': 8, 'eggs': 9})

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_pickle(self):
ns = types.SimpleNamespace(breakfast="spam", lunch="spam")

Expand Down
20 changes: 16 additions & 4 deletions vm/src/builtins/namespace.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use super::{PyType, PyTypeRef};
use super::{tuple::IntoPyTuple, PyTupleRef, PyType, PyTypeRef};
use crate::{
builtins::PyDict,
class::PyClassImpl,
function::{FuncArgs, PyComparisonValue},
recursion::ReprGuard,
types::{Comparable, Constructor, Initializer, PyComparisonOp, Representable},
AsObject, Context, Py, PyObject, PyPayload, PyRef, PyResult, VirtualMachine,
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
};

/// A simple attribute-based namespace.
///
/// SimpleNamespace(**kwargs)
#[pyclass(module = false, name = "SimpleNamespace")]
#[pyclass(module = "types", name = "SimpleNamespace")]
#[derive(Debug)]
pub struct PyNamespace {}

Expand Down Expand Up @@ -43,7 +43,19 @@ impl PyNamespace {
flags(BASETYPE, HAS_DICT),
with(Constructor, Initializer, Comparable, Representable)
)]
impl PyNamespace {}
impl PyNamespace {
#[pymethod(magic)]
fn reduce(zelf: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef {
let dict = zelf.as_object().dict().unwrap();
let obj = zelf.as_object().to_owned();
let result: (PyObjectRef, PyObjectRef, PyObjectRef) = (
obj.class().to_owned().into(),
vm.new_tuple(()).into(),
dict.into(),
);
result.into_pytuple(vm)
}
}

impl Initializer for PyNamespace {
type Args = FuncArgs;
Expand Down