Skip to main content
Cloacina Documentation
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Context

cloaca.python.context Binding

Classes

cloaca.python.context.Context

Rust Implementation: cloacina::python::context::PyContext

PyContext - Python wrapper for Rust Context<serde_json::Value>

Methods

new
new(data: Optional[dict]) -> Self

Rust Implementation: cloacina::python::context::PyContext::new

Creates a new empty context

Parameters:

Name Type Description
data Optional[dict]
Source
    pub fn new(data: Option<&Bound<'_, PyDict>>) -> PyResult<Self> {
        let mut context = crate::Context::new();

        if let Some(dict) = data {
            for (key, value) in dict.iter() {
                let key_str: String = key.extract()?;
                let json_value: serde_json::Value = depythonize(&value)?;
                context.insert(key_str, json_value).map_err(|e| {
                    PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                        "Failed to insert key: {}",
                        e
                    ))
                })?;
            }
        }

        Ok(PyContext { inner: context })
    }
get
get(key: str, default: Optional[Any]) -> Any

Rust Implementation: cloacina::python::context::PyContext::get

Gets a value from the context

Parameters:

Name Type Description
key str
default Optional[Any]
Source
    pub fn get(&self, key: &str, default: Option<&Bound<'_, PyAny>>) -> PyResult<PyObject> {
        match self.inner.get(key) {
            Some(value) => Python::with_gil(|py| Ok(pythonize(py, value)?.into())),
            None => match default {
                Some(default_value) => Ok(default_value.clone().into()),
                None => Python::with_gil(|py| Ok(py.None())),
            },
        }
    }
set
set(key: str, value: Any) -> None

Rust Implementation: cloacina::python::context::PyContext::set

Sets a value in the context (insert or update)

Parameters:

Name Type Description
key str
value Any
Source
    pub fn set(&mut self, key: &str, value: &Bound<'_, PyAny>) -> PyResult<()> {
        let json_value: serde_json::Value = depythonize(value)?;

        if self.inner.get(key).is_some() {
            self.inner.update(key, json_value)
        } else {
            self.inner.insert(key, json_value)
        }
        .map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Failed to set key '{}': {}",
                key, e
            ))
        })
    }
update
update(key: str, value: Any) -> None

Rust Implementation: cloacina::python::context::PyContext::update

Updates an existing value in the context

Parameters:

Name Type Description
key str
value Any
Source
    pub fn update(&mut self, key: &str, value: &Bound<'_, PyAny>) -> PyResult<()> {
        let json_value: serde_json::Value = depythonize(value)?;
        self.inner.update(key, json_value).map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!("Key not found: {}", e))
        })
    }
insert
insert(key: str, value: Any) -> None

Rust Implementation: cloacina::python::context::PyContext::insert

Inserts a new value into the context

Parameters:

Name Type Description
key str
value Any
Source
    pub fn insert(&mut self, key: &str, value: &Bound<'_, PyAny>) -> PyResult<()> {
        let json_value: serde_json::Value = depythonize(value)?;
        self.inner.insert(key, json_value).map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Key already exists: {}", e))
        })
    }
remove
remove(key: str) -> Optional[Any]

Rust Implementation: cloacina::python::context::PyContext::remove

Removes and returns a value from the context

Parameters:

Name Type Description
key str
Source
    pub fn remove(&mut self, key: &str) -> PyResult<Option<PyObject>> {
        match self.inner.remove(key) {
            Some(value) => Python::with_gil(|py| Ok(Some(pythonize(py, &value)?.into()))),
            None => Ok(None),
        }
    }
to_dict
to_dict() -> Any

Rust Implementation: cloacina::python::context::PyContext::to_dict

Returns the context as a Python dictionary

Source
    pub fn to_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
        Ok(pythonize(py, self.inner.data())?.into())
    }
update_from_dict
update_from_dict(data: dict) -> None

Rust Implementation: cloacina::python::context::PyContext::update_from_dict

Updates the context with values from a Python dictionary

Parameters:

Name Type Description
data dict
Source
    pub fn update_from_dict(&mut self, data: &Bound<'_, PyDict>) -> PyResult<()> {
        for (key, value) in data.iter() {
            let key_str: String = key.extract()?;
            let json_value: serde_json::Value = depythonize(&value)?;

            if self.inner.get(&key_str).is_some() {
                self.inner.update(key_str, json_value)
            } else {
                self.inner.insert(key_str, json_value)
            }
            .map_err(|e| {
                PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "Failed to update from dict: {}",
                    e
                ))
            })?;
        }
        Ok(())
    }
to_json
to_json() -> str

Rust Implementation: cloacina::python::context::PyContext::to_json

Serializes the context to a JSON string

Source
    pub fn to_json(&self) -> PyResult<String> {
        self.inner.to_json().map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Failed to serialize to JSON: {}",
                e
            ))
        })
    }
from_json
from_json(json_str: str) -> Self

Rust Implementation: cloacina::python::context::PyContext::from_json

Creates a context from a JSON string

Parameters:

Name Type Description
json_str str
Source
    pub fn from_json(json_str: &str) -> PyResult<Self> {
        let context = crate::Context::from_json(json_str.to_string()).map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Failed to deserialize from JSON: {}",
                e
            ))
        })?;
        Ok(PyContext { inner: context })
    }
__len__
__len__() -> int

Rust Implementation: cloacina::python::context::PyContext::len

Returns the number of key-value pairs in the context

Source
    pub fn __len__(&self) -> usize {
        self.inner.data().len()
    }
__contains__
__contains__(key: str) -> bool

Rust Implementation: cloacina::python::context::PyContext::contains

Checks if a key exists in the context

Parameters:

Name Type Description
key str
Source
    pub fn __contains__(&self, key: &str) -> bool {
        self.inner.get(key).is_some()
    }
__repr__
__repr__() -> str

Rust Implementation: cloacina::python::context::PyContext::repr

String representation of the context

Source
    pub fn __repr__(&self) -> String {
        match self.inner.to_json() {
            Ok(json) => format!("Context({})", json),
            Err(_) => "Context(<serialization error>)".to_string(),
        }
    }
__getitem__
__getitem__(key: str) -> Any

Rust Implementation: cloacina::python::context::PyContext::getitem

Dictionary-style item access

Parameters:

Name Type Description
key str
Source
    pub fn __getitem__(&self, key: &str) -> PyResult<PyObject> {
        let result = self.get(key, None)?;
        Python::with_gil(|py| {
            if result.is_none(py) {
                Err(PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!(
                    "Key not found: '{}'",
                    key
                )))
            } else {
                Ok(result)
            }
        })
    }
__setitem__
__setitem__(key: str, value: Any) -> None

Rust Implementation: cloacina::python::context::PyContext::setitem

Dictionary-style item assignment

Parameters:

Name Type Description
key str
value Any
Source
    pub fn __setitem__(&mut self, key: &str, value: &Bound<'_, PyAny>) -> PyResult<()> {
        self.set(key, value)
    }
__delitem__
__delitem__(key: str) -> None

Rust Implementation: cloacina::python::context::PyContext::delitem

Dictionary-style item deletion

Parameters:

Name Type Description
key str
Source
    pub fn __delitem__(&mut self, key: &str) -> PyResult<()> {
        match self.remove(key)? {
            Some(_) => Ok(()),
            None => Err(PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!(
                "Key not found: '{}'",
                key
            ))),
        }
    }