Trait cpython::RefFromPyObject[][src]

pub trait RefFromPyObject {
    fn with_extracted<F, R>(py: Python<'_>, obj: &PyObject, f: F) -> PyResult<R>
    where
        F: FnOnce(&Self) -> R
; }

RefFromPyObject is implemented by various types that can be extracted as a reference from a Python object. Depending on the input object, the reference may point into memory owned by the Python interpreter; or into a temporary object.

let sum_of_bytes = <[u8] as RefFromPyObject>::with_extracted(py, obj,
    |data: &[u8]| data.iter().sum()
);

A lambda has to be used because the slice may refer to temporary object that exists only during the with_extracted call.

Each target type for this conversion supports a different Python objects as input. Calls with an unsupported input object will result in an exception (usually a TypeError).

This trait is also used by the py_fn! and py_class! and py_argparse! macros in order to translate from Python objects to the expected Rust parameter types. For example, the parameter x in def method(self, x: &[u8]) will use impl RefFromPyObject for [u8] to convert the input Python object into a Rust &[u8]. When these macros are used with non-reference parameters (x: i32), the trait FromPyObject is used instead.

Required methods

fn with_extracted<F, R>(py: Python<'_>, obj: &PyObject, f: F) -> PyResult<R> where
    F: FnOnce(&Self) -> R, 
[src]

Loading content...

Implementations on Foreign Types

impl RefFromPyObject for str[src]

Allows extracting strings from Python objects. Accepts Python str and unicode objects. In Python 2.7, str is expected to be UTF-8 encoded.

impl RefFromPyObject for [u8][src]

For Python bytes, returns a reference to the existing immutable string data. If the Python object is a single-dimensional buffer of format c or B (C: char or unsigned char), returns an owned copy of the data in the buffer. Otherwise, uses the sequence protocol and converts each individual element via impl FromPyObject for u8.

Loading content...

Implementors

impl<T: ?Sized> RefFromPyObject for T where
    &'a T: FromPyObject<'a>, 
[src]

Loading content...