pub trait PyStringMethods<'py>: Sealed {
    // Required methods
    fn to_str(&self) -> PyResult<&str>;
    fn to_cow(&self) -> PyResult<Cow<'_, str>>;
    fn to_string_lossy(&self) -> Cow<'_, str>;
    fn encode_utf8(&self) -> PyResult<Bound<'py, PyBytes>>;
    unsafe fn data(&self) -> PyResult<PyStringData<'_>>;
Expand description

Implementation of functionality for PyString.

These methods are defined for the Bound<'py, PyString> smart pointer, so to use method call syntax these methods are separated into a trait, because stable Rust does not yet support arbitrary_self_types.

Required Methods§


fn to_str(&self) -> PyResult<&str>

Gets the Python string as a Rust UTF-8 string slice.

Returns a UnicodeEncodeError if the input is not valid unicode (containing unpaired surrogates).


fn to_cow(&self) -> PyResult<Cow<'_, str>>

Converts the PyString into a Rust string, avoiding copying when possible.

Returns a UnicodeEncodeError if the input is not valid unicode (containing unpaired surrogates).


fn to_string_lossy(&self) -> Cow<'_, str>

Converts the PyString into a Rust string.

Unpaired surrogates invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.


fn encode_utf8(&self) -> PyResult<Bound<'py, PyBytes>>

Encodes this string as a Python bytes object, using UTF-8 encoding.


unsafe fn data(&self) -> PyResult<PyStringData<'_>>

Obtains the raw data backing the Python string.

If the Python string object was created through legacy APIs, its internal storage format will be canonicalized before data is returned.


This function implementation relies on manually decoding a C bitfield. In practice, this works well on common little-endian architectures such as x86_64, where the bitfield has a common representation (even if it is not part of the C spec). The PyO3 CI tests this API on x86_64 platforms.

By using this API, you accept responsibility for testing that PyStringData behaves as expected on the targets where you plan to distribute your software.



impl<'py> PyStringMethods<'py> for Bound<'py, PyString>