From 79abfb99e88ce3a78aadbcde9f6507cd78a5b2ab Mon Sep 17 00:00:00 2001 From: Dmitry Trofimov Date: Wed, 8 Jul 2015 01:26:50 +0200 Subject: [PATCH 1/2] A method for accessing dictionary items. --- src/objects/dict.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/objects/dict.rs b/src/objects/dict.rs index 0ebd71d5..b6bedc2f 100644 --- a/src/objects/dict.rs +++ b/src/objects/dict.rs @@ -19,7 +19,7 @@ use ffi; use python::{Python, ToPythonPointer, PythonObject}; use conversion::ToPyObject; -use objects::PyObject; +use objects::{PyObject, PyList}; use err::{self, PyResult, PyErr}; /// Represents a Python `dict`. @@ -77,7 +77,7 @@ impl <'p> PyDict<'p> { pub fn get_item(&self, key: K) -> Option> where K: ToPyObject<'p> { let py = self.python(); key.with_borrowed_ptr(py, |key| unsafe { - PyObject::from_borrowed_ptr_opt(py, + PyObject::from_borrowed_ptr_opt(py, ffi::PyDict_GetItem(self.as_ptr(), key)) }) } @@ -102,5 +102,14 @@ impl <'p> PyDict<'p> { ffi::PyDict_DelItem(self.as_ptr(), key)) }) } -} + // List of dict items. + // This is equivalent to the `dict.items()` method. + pub fn items(&self) -> PyList { + let py = self.python(); + unsafe { + let pyobj = PyObject::from_borrowed_ptr(py, ffi::PyDict_Items(self.as_ptr())); + pyobj.unchecked_cast_into::() + } + } +} From d495eaaa4a1c867e0bc3266954816ef526a52bf0 Mon Sep 17 00:00:00 2001 From: Dmitry Trofimov Date: Thu, 9 Jul 2015 00:51:12 +0200 Subject: [PATCH 2/2] Use err::cast_from_owned_ptr_or_panic, because PyDict_Items creates a new reference to list and can fail. --- src/objects/dict.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/objects/dict.rs b/src/objects/dict.rs index b6bedc2f..e8641434 100644 --- a/src/objects/dict.rs +++ b/src/objects/dict.rs @@ -108,8 +108,7 @@ impl <'p> PyDict<'p> { pub fn items(&self) -> PyList { let py = self.python(); unsafe { - let pyobj = PyObject::from_borrowed_ptr(py, ffi::PyDict_Items(self.as_ptr())); - pyobj.unchecked_cast_into::() + err::cast_from_owned_ptr_or_panic(py, ffi::PyDict_Items(self.as_ptr())) } } }