index int64 0 0 | repo_id stringclasses 596 values | file_path stringlengths 31 168 | content stringlengths 1 6.2M |
|---|---|---|---|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pymodule.rs | //! Implementation details of `#[pymodule]` which need to be accessible from proc-macro generated code.
use std::{cell::UnsafeCell, ffi::CStr, marker::PhantomData};
#[cfg(all(
not(any(PyPy, GraalPy)),
Py_3_9,
not(all(windows, Py_LIMITED_API, not(Py_3_10))),
not(target_has_atomic = "64"),
))]
use portable_atomic::AtomicI64;
#[cfg(all(
not(any(PyPy, GraalPy)),
Py_3_9,
not(all(windows, Py_LIMITED_API, not(Py_3_10))),
target_has_atomic = "64",
))]
use std::sync::atomic::AtomicI64;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(any(PyPy, GraalPy)))]
use crate::exceptions::PyImportError;
#[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))]
use crate::PyErr;
use crate::{
ffi,
impl_::pymethods::PyMethodDef,
sync::GILOnceCell,
types::{PyCFunction, PyModule, PyModuleMethods},
Bound, Py, PyClass, PyResult, PyTypeInfo, Python,
};
/// `Sync` wrapper of `ffi::PyModuleDef`.
pub struct ModuleDef {
// wrapped in UnsafeCell so that Rust compiler treats this as interior mutability
ffi_def: UnsafeCell<ffi::PyModuleDef>,
initializer: ModuleInitializer,
/// Interpreter ID where module was initialized (not applicable on PyPy).
#[cfg(all(
not(any(PyPy, GraalPy)),
Py_3_9,
not(all(windows, Py_LIMITED_API, not(Py_3_10)))
))]
interpreter: AtomicI64,
/// Initialized module object, cached to avoid reinitialization.
module: GILOnceCell<Py<PyModule>>,
/// Whether or not the module supports running without the GIL
gil_used: AtomicBool,
}
/// Wrapper to enable initializer to be used in const fns.
pub struct ModuleInitializer(pub for<'py> fn(&Bound<'py, PyModule>) -> PyResult<()>);
unsafe impl Sync for ModuleDef {}
impl ModuleDef {
/// Make new module definition with given module name.
pub const unsafe fn new(
name: &'static CStr,
doc: &'static CStr,
initializer: ModuleInitializer,
) -> Self {
#[allow(clippy::declare_interior_mutable_const)]
const INIT: ffi::PyModuleDef = ffi::PyModuleDef {
m_base: ffi::PyModuleDef_HEAD_INIT,
m_name: std::ptr::null(),
m_doc: std::ptr::null(),
m_size: 0,
m_methods: std::ptr::null_mut(),
m_slots: std::ptr::null_mut(),
m_traverse: None,
m_clear: None,
m_free: None,
};
let ffi_def = UnsafeCell::new(ffi::PyModuleDef {
m_name: name.as_ptr(),
m_doc: doc.as_ptr(),
..INIT
});
ModuleDef {
ffi_def,
initializer,
// -1 is never expected to be a valid interpreter ID
#[cfg(all(
not(any(PyPy, GraalPy)),
Py_3_9,
not(all(windows, Py_LIMITED_API, not(Py_3_10)))
))]
interpreter: AtomicI64::new(-1),
module: GILOnceCell::new(),
gil_used: AtomicBool::new(true),
}
}
/// Builds a module using user given initializer. Used for [`#[pymodule]`][crate::pymodule].
#[cfg_attr(any(Py_LIMITED_API, not(Py_GIL_DISABLED)), allow(unused_variables))]
pub fn make_module(&'static self, py: Python<'_>, gil_used: bool) -> PyResult<Py<PyModule>> {
// Check the interpreter ID has not changed, since we currently have no way to guarantee
// that static data is not reused across interpreters.
//
// PyPy does not have subinterpreters, so no need to check interpreter ID.
#[cfg(not(any(PyPy, GraalPy)))]
{
// PyInterpreterState_Get is only available on 3.9 and later, but is missing
// from python3.dll for Windows stable API on 3.9
#[cfg(all(Py_3_9, not(all(windows, Py_LIMITED_API, not(Py_3_10)))))]
{
let current_interpreter =
unsafe { ffi::PyInterpreterState_GetID(ffi::PyInterpreterState_Get()) };
crate::err::error_on_minusone(py, current_interpreter)?;
if let Err(initialized_interpreter) = self.interpreter.compare_exchange(
-1,
current_interpreter,
Ordering::SeqCst,
Ordering::SeqCst,
) {
if initialized_interpreter != current_interpreter {
return Err(PyImportError::new_err(
"PyO3 modules do not yet support subinterpreters, see https://github.com/PyO3/pyo3/issues/576",
));
}
}
}
#[cfg(not(all(Py_3_9, not(all(windows, Py_LIMITED_API, not(Py_3_10))))))]
{
// CPython before 3.9 does not have APIs to check the interpreter ID, so best that can be
// done to guard against subinterpreters is fail if the module is initialized twice
if self.module.get(py).is_some() {
return Err(PyImportError::new_err(
"PyO3 modules compiled for CPython 3.8 or older may only be initialized once per interpreter process"
));
}
}
}
self.module
.get_or_try_init(py, || {
let module = unsafe {
Py::<PyModule>::from_owned_ptr_or_err(
py,
ffi::PyModule_Create(self.ffi_def.get()),
)?
};
#[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))]
{
let gil_used_ptr = {
if gil_used {
ffi::Py_MOD_GIL_USED
} else {
ffi::Py_MOD_GIL_NOT_USED
}
};
if unsafe { ffi::PyUnstable_Module_SetGIL(module.as_ptr(), gil_used_ptr) } < 0 {
return Err(PyErr::fetch(py));
}
}
self.initializer.0(module.bind(py))?;
Ok(module)
})
.map(|py_module| py_module.clone_ref(py))
}
}
/// Trait to add an element (class, function...) to a module.
///
/// Currently only implemented for classes.
pub trait PyAddToModule: crate::sealed::Sealed {
fn add_to_module(&'static self, module: &Bound<'_, PyModule>) -> PyResult<()>;
}
/// For adding native types (non-pyclass) to a module.
pub struct AddTypeToModule<T>(PhantomData<T>);
impl<T> AddTypeToModule<T> {
#[allow(clippy::new_without_default)]
pub const fn new() -> Self {
AddTypeToModule(PhantomData)
}
}
impl<T: PyTypeInfo> PyAddToModule for AddTypeToModule<T> {
fn add_to_module(&'static self, module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add(T::NAME, T::type_object(module.py()))
}
}
/// For adding a class to a module.
pub struct AddClassToModule<T>(PhantomData<T>);
impl<T> AddClassToModule<T> {
#[allow(clippy::new_without_default)]
pub const fn new() -> Self {
AddClassToModule(PhantomData)
}
}
impl<T: PyClass> PyAddToModule for AddClassToModule<T> {
fn add_to_module(&'static self, module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_class::<T>()
}
}
/// For adding a function to a module.
impl PyAddToModule for PyMethodDef {
fn add_to_module(&'static self, module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(PyCFunction::internal_new(module.py(), self, Some(module))?)
}
}
/// For adding a module to a module.
impl PyAddToModule for ModuleDef {
fn add_to_module(&'static self, module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_submodule(
self.make_module(module.py(), self.gil_used.load(Ordering::Relaxed))?
.bind(module.py()),
)
}
}
#[cfg(test)]
mod tests {
use std::{
borrow::Cow,
ffi::CStr,
sync::atomic::{AtomicBool, Ordering},
};
use crate::{
ffi,
types::{any::PyAnyMethods, module::PyModuleMethods, PyModule},
Bound, PyResult, Python,
};
use super::{ModuleDef, ModuleInitializer};
#[test]
fn module_init() {
static MODULE_DEF: ModuleDef = unsafe {
ModuleDef::new(
ffi::c_str!("test_module"),
ffi::c_str!("some doc"),
ModuleInitializer(|m| {
m.add("SOME_CONSTANT", 42)?;
Ok(())
}),
)
};
Python::with_gil(|py| {
let module = MODULE_DEF.make_module(py, false).unwrap().into_bound(py);
assert_eq!(
module
.getattr("__name__")
.unwrap()
.extract::<Cow<'_, str>>()
.unwrap(),
"test_module",
);
assert_eq!(
module
.getattr("__doc__")
.unwrap()
.extract::<Cow<'_, str>>()
.unwrap(),
"some doc",
);
assert_eq!(
module
.getattr("SOME_CONSTANT")
.unwrap()
.extract::<u8>()
.unwrap(),
42,
);
})
}
#[test]
fn module_def_new() {
// To get coverage for ModuleDef::new() need to create a non-static ModuleDef, however init
// etc require static ModuleDef, so this test needs to be separated out.
static NAME: &CStr = ffi::c_str!("test_module");
static DOC: &CStr = ffi::c_str!("some doc");
static INIT_CALLED: AtomicBool = AtomicBool::new(false);
#[allow(clippy::unnecessary_wraps)]
fn init(_: &Bound<'_, PyModule>) -> PyResult<()> {
INIT_CALLED.store(true, Ordering::SeqCst);
Ok(())
}
unsafe {
let module_def: ModuleDef = ModuleDef::new(NAME, DOC, ModuleInitializer(init));
assert_eq!((*module_def.ffi_def.get()).m_name, NAME.as_ptr() as _);
assert_eq!((*module_def.ffi_def.get()).m_doc, DOC.as_ptr() as _);
Python::with_gil(|py| {
module_def.initializer.0(&py.import("builtins").unwrap()).unwrap();
assert!(INIT_CALLED.load(Ordering::SeqCst));
})
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/extract_argument.rs | use crate::{
conversion::FromPyObjectBound,
exceptions::PyTypeError,
ffi,
pyclass::boolean_struct::False,
types::{any::PyAnyMethods, dict::PyDictMethods, tuple::PyTupleMethods, PyDict, PyTuple},
Borrowed, Bound, PyAny, PyClass, PyErr, PyRef, PyRefMut, PyResult, PyTypeCheck, Python,
};
/// Helper type used to keep implementation more concise.
///
/// (Function argument extraction borrows input arguments.)
type PyArg<'py> = Borrowed<'py, 'py, PyAny>;
/// A trait which is used to help PyO3 macros extract function arguments.
///
/// `#[pyclass]` structs need to extract as `PyRef<T>` and `PyRefMut<T>`
/// wrappers rather than extracting `&T` and `&mut T` directly. The `Holder` type is used
/// to hold these temporary wrappers - the way the macro is constructed, these wrappers
/// will be dropped as soon as the pyfunction call ends.
///
/// There exists a trivial blanket implementation for `T: FromPyObject` with `Holder = ()`.
pub trait PyFunctionArgument<'a, 'py>: Sized + 'a {
type Holder: FunctionArgumentHolder;
fn extract(obj: &'a Bound<'py, PyAny>, holder: &'a mut Self::Holder) -> PyResult<Self>;
}
impl<'a, 'py, T> PyFunctionArgument<'a, 'py> for T
where
T: FromPyObjectBound<'a, 'py> + 'a,
{
type Holder = ();
#[inline]
fn extract(obj: &'a Bound<'py, PyAny>, _: &'a mut ()) -> PyResult<Self> {
obj.extract()
}
}
impl<'a, 'py, T: 'py> PyFunctionArgument<'a, 'py> for &'a Bound<'py, T>
where
T: PyTypeCheck,
{
type Holder = Option<()>;
#[inline]
fn extract(obj: &'a Bound<'py, PyAny>, _: &'a mut Option<()>) -> PyResult<Self> {
obj.downcast().map_err(Into::into)
}
}
impl<'a, 'py, T: 'py> PyFunctionArgument<'a, 'py> for Option<&'a Bound<'py, T>>
where
T: PyTypeCheck,
{
type Holder = ();
#[inline]
fn extract(obj: &'a Bound<'py, PyAny>, _: &'a mut ()) -> PyResult<Self> {
if obj.is_none() {
Ok(None)
} else {
Ok(Some(obj.downcast()?))
}
}
}
#[cfg(all(Py_LIMITED_API, not(Py_3_10)))]
impl<'a> PyFunctionArgument<'a, '_> for &'a str {
type Holder = Option<std::borrow::Cow<'a, str>>;
#[inline]
fn extract(
obj: &'a Bound<'_, PyAny>,
holder: &'a mut Option<std::borrow::Cow<'a, str>>,
) -> PyResult<Self> {
Ok(holder.insert(obj.extract()?))
}
}
/// Trait for types which can be a function argument holder - they should
/// to be able to const-initialize to an empty value.
pub trait FunctionArgumentHolder: Sized {
const INIT: Self;
}
impl FunctionArgumentHolder for () {
const INIT: Self = ();
}
impl<T> FunctionArgumentHolder for Option<T> {
const INIT: Self = None;
}
#[inline]
pub fn extract_pyclass_ref<'a, 'py: 'a, T: PyClass>(
obj: &'a Bound<'py, PyAny>,
holder: &'a mut Option<PyRef<'py, T>>,
) -> PyResult<&'a T> {
Ok(&*holder.insert(obj.extract()?))
}
#[inline]
pub fn extract_pyclass_ref_mut<'a, 'py: 'a, T: PyClass<Frozen = False>>(
obj: &'a Bound<'py, PyAny>,
holder: &'a mut Option<PyRefMut<'py, T>>,
) -> PyResult<&'a mut T> {
Ok(&mut *holder.insert(obj.extract()?))
}
/// The standard implementation of how PyO3 extracts a `#[pyfunction]` or `#[pymethod]` function argument.
#[doc(hidden)]
pub fn extract_argument<'a, 'py, T>(
obj: &'a Bound<'py, PyAny>,
holder: &'a mut T::Holder,
arg_name: &str,
) -> PyResult<T>
where
T: PyFunctionArgument<'a, 'py>,
{
match PyFunctionArgument::extract(obj, holder) {
Ok(value) => Ok(value),
Err(e) => Err(argument_extraction_error(obj.py(), arg_name, e)),
}
}
/// Alternative to [`extract_argument`] used for `Option<T>` arguments. This is necessary because Option<&T>
/// does not implement `PyFunctionArgument` for `T: PyClass`.
#[doc(hidden)]
pub fn extract_optional_argument<'a, 'py, T>(
obj: Option<&'a Bound<'py, PyAny>>,
holder: &'a mut T::Holder,
arg_name: &str,
default: fn() -> Option<T>,
) -> PyResult<Option<T>>
where
T: PyFunctionArgument<'a, 'py>,
{
match obj {
Some(obj) => {
if obj.is_none() {
// Explicit `None` will result in None being used as the function argument
Ok(None)
} else {
extract_argument(obj, holder, arg_name).map(Some)
}
}
_ => Ok(default()),
}
}
/// Alternative to [`extract_argument`] used when the argument has a default value provided by an annotation.
#[doc(hidden)]
pub fn extract_argument_with_default<'a, 'py, T>(
obj: Option<&'a Bound<'py, PyAny>>,
holder: &'a mut T::Holder,
arg_name: &str,
default: fn() -> T,
) -> PyResult<T>
where
T: PyFunctionArgument<'a, 'py>,
{
match obj {
Some(obj) => extract_argument(obj, holder, arg_name),
None => Ok(default()),
}
}
/// Alternative to [`extract_argument`] used when the argument has a `#[pyo3(from_py_with)]` annotation.
#[doc(hidden)]
pub fn from_py_with<'a, 'py, T>(
obj: &'a Bound<'py, PyAny>,
arg_name: &str,
extractor: fn(&'a Bound<'py, PyAny>) -> PyResult<T>,
) -> PyResult<T> {
match extractor(obj) {
Ok(value) => Ok(value),
Err(e) => Err(argument_extraction_error(obj.py(), arg_name, e)),
}
}
/// Alternative to [`extract_argument`] used when the argument has a `#[pyo3(from_py_with)]` annotation and also a default value.
#[doc(hidden)]
pub fn from_py_with_with_default<'a, 'py, T>(
obj: Option<&'a Bound<'py, PyAny>>,
arg_name: &str,
extractor: fn(&'a Bound<'py, PyAny>) -> PyResult<T>,
default: fn() -> T,
) -> PyResult<T> {
match obj {
Some(obj) => from_py_with(obj, arg_name, extractor),
None => Ok(default()),
}
}
/// Adds the argument name to the error message of an error which occurred during argument extraction.
///
/// Only modifies TypeError. (Cannot guarantee all exceptions have constructors from
/// single string.)
#[doc(hidden)]
#[cold]
pub fn argument_extraction_error(py: Python<'_>, arg_name: &str, error: PyErr) -> PyErr {
if error.get_type(py).is(&py.get_type::<PyTypeError>()) {
let remapped_error =
PyTypeError::new_err(format!("argument '{}': {}", arg_name, error.value(py)));
remapped_error.set_cause(py, error.cause(py));
remapped_error
} else {
error
}
}
/// Unwraps the Option<&PyAny> produced by the FunctionDescription `extract_arguments_` methods.
/// They check if required methods are all provided.
///
/// # Safety
/// `argument` must not be `None`
#[doc(hidden)]
#[inline]
pub unsafe fn unwrap_required_argument<'a, 'py>(
argument: Option<&'a Bound<'py, PyAny>>,
) -> &'a Bound<'py, PyAny> {
match argument {
Some(value) => value,
#[cfg(debug_assertions)]
None => unreachable!("required method argument was not extracted"),
#[cfg(not(debug_assertions))]
None => std::hint::unreachable_unchecked(),
}
}
pub struct KeywordOnlyParameterDescription {
pub name: &'static str,
pub required: bool,
}
/// Function argument specification for a `#[pyfunction]` or `#[pymethod]`.
pub struct FunctionDescription {
pub cls_name: Option<&'static str>,
pub func_name: &'static str,
pub positional_parameter_names: &'static [&'static str],
pub positional_only_parameters: usize,
pub required_positional_parameters: usize,
pub keyword_only_parameters: &'static [KeywordOnlyParameterDescription],
}
impl FunctionDescription {
fn full_name(&self) -> String {
if let Some(cls_name) = self.cls_name {
format!("{}.{}()", cls_name, self.func_name)
} else {
format!("{}()", self.func_name)
}
}
/// Equivalent of `extract_arguments_tuple_dict` which uses the Python C-API "fastcall" convention.
///
/// # Safety
/// - `args` must be a pointer to a C-style array of valid `ffi::PyObject` pointers, or NULL.
/// - `kwnames` must be a pointer to a PyTuple, or NULL.
/// - `nargs + kwnames.len()` is the total length of the `args` array.
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
pub unsafe fn extract_arguments_fastcall<'py, V, K>(
&self,
py: Python<'py>,
args: *const *mut ffi::PyObject,
nargs: ffi::Py_ssize_t,
kwnames: *mut ffi::PyObject,
output: &mut [Option<PyArg<'py>>],
) -> PyResult<(V::Varargs, K::Varkeywords)>
where
V: VarargsHandler<'py>,
K: VarkeywordsHandler<'py>,
{
let num_positional_parameters = self.positional_parameter_names.len();
debug_assert!(nargs >= 0);
debug_assert!(self.positional_only_parameters <= num_positional_parameters);
debug_assert!(self.required_positional_parameters <= num_positional_parameters);
debug_assert_eq!(
output.len(),
num_positional_parameters + self.keyword_only_parameters.len()
);
// Handle positional arguments
// Safety:
// - Option<PyArg> has the same memory layout as `*mut ffi::PyObject`
// - we both have the GIL and can borrow these input references for the `'py` lifetime.
let args: *const Option<PyArg<'py>> = args.cast();
let positional_args_provided = nargs as usize;
let remaining_positional_args = if args.is_null() {
debug_assert_eq!(positional_args_provided, 0);
&[]
} else {
// Can consume at most the number of positional parameters in the function definition,
// the rest are varargs.
let positional_args_to_consume =
num_positional_parameters.min(positional_args_provided);
let (positional_parameters, remaining) =
std::slice::from_raw_parts(args, positional_args_provided)
.split_at(positional_args_to_consume);
output[..positional_args_to_consume].copy_from_slice(positional_parameters);
remaining
};
let varargs = V::handle_varargs_fastcall(py, remaining_positional_args, self)?;
// Handle keyword arguments
let mut varkeywords = K::Varkeywords::default();
// Safety: kwnames is known to be a pointer to a tuple, or null
// - we both have the GIL and can borrow this input reference for the `'py` lifetime.
let kwnames: Option<Borrowed<'_, '_, PyTuple>> =
Borrowed::from_ptr_or_opt(py, kwnames).map(|kwnames| kwnames.downcast_unchecked());
if let Some(kwnames) = kwnames {
let kwargs = ::std::slice::from_raw_parts(
// Safety: PyArg has the same memory layout as `*mut ffi::PyObject`
args.offset(nargs).cast::<PyArg<'py>>(),
kwnames.len(),
);
self.handle_kwargs::<K, _>(
kwnames.iter_borrowed().zip(kwargs.iter().copied()),
&mut varkeywords,
num_positional_parameters,
output,
)?
}
// Once all inputs have been processed, check that all required arguments have been provided.
self.ensure_no_missing_required_positional_arguments(output, positional_args_provided)?;
self.ensure_no_missing_required_keyword_arguments(output)?;
Ok((varargs, varkeywords))
}
/// Extracts the `args` and `kwargs` provided into `output`, according to this function
/// definition.
///
/// `output` must have the same length as this function has positional and keyword-only
/// parameters (as per the `positional_parameter_names` and `keyword_only_parameters`
/// respectively).
///
/// Unexpected, duplicate or invalid arguments will cause this function to return `TypeError`.
///
/// # Safety
/// - `args` must be a pointer to a PyTuple.
/// - `kwargs` must be a pointer to a PyDict, or NULL.
pub unsafe fn extract_arguments_tuple_dict<'py, V, K>(
&self,
py: Python<'py>,
args: *mut ffi::PyObject,
kwargs: *mut ffi::PyObject,
output: &mut [Option<PyArg<'py>>],
) -> PyResult<(V::Varargs, K::Varkeywords)>
where
V: VarargsHandler<'py>,
K: VarkeywordsHandler<'py>,
{
// Safety:
// - `args` is known to be a tuple
// - `kwargs` is known to be a dict or null
// - we both have the GIL and can borrow these input references for the `'py` lifetime.
let args: Borrowed<'py, 'py, PyTuple> =
Borrowed::from_ptr(py, args).downcast_unchecked::<PyTuple>();
let kwargs: Option<Borrowed<'py, 'py, PyDict>> =
Borrowed::from_ptr_or_opt(py, kwargs).map(|kwargs| kwargs.downcast_unchecked());
let num_positional_parameters = self.positional_parameter_names.len();
debug_assert!(self.positional_only_parameters <= num_positional_parameters);
debug_assert!(self.required_positional_parameters <= num_positional_parameters);
debug_assert_eq!(
output.len(),
num_positional_parameters + self.keyword_only_parameters.len()
);
// Copy positional arguments into output
for (i, arg) in args
.iter_borrowed()
.take(num_positional_parameters)
.enumerate()
{
output[i] = Some(arg);
}
// If any arguments remain, push them to varargs (if possible) or error
let varargs = V::handle_varargs_tuple(&args, self)?;
// Handle keyword arguments
let mut varkeywords = K::Varkeywords::default();
if let Some(kwargs) = kwargs {
self.handle_kwargs::<K, _>(
kwargs.iter_borrowed(),
&mut varkeywords,
num_positional_parameters,
output,
)?
}
// Once all inputs have been processed, check that all required arguments have been provided.
self.ensure_no_missing_required_positional_arguments(output, args.len())?;
self.ensure_no_missing_required_keyword_arguments(output)?;
Ok((varargs, varkeywords))
}
#[inline]
fn handle_kwargs<'py, K, I>(
&self,
kwargs: I,
varkeywords: &mut K::Varkeywords,
num_positional_parameters: usize,
output: &mut [Option<PyArg<'py>>],
) -> PyResult<()>
where
K: VarkeywordsHandler<'py>,
I: IntoIterator<Item = (PyArg<'py>, PyArg<'py>)>,
{
debug_assert_eq!(
num_positional_parameters,
self.positional_parameter_names.len()
);
debug_assert_eq!(
output.len(),
num_positional_parameters + self.keyword_only_parameters.len()
);
let mut positional_only_keyword_arguments = Vec::new();
for (kwarg_name_py, value) in kwargs {
// Safety: All keyword arguments should be UTF-8 strings, but if it's not, `.to_str()`
// will return an error anyway.
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
let kwarg_name =
unsafe { kwarg_name_py.downcast_unchecked::<crate::types::PyString>() }.to_str();
#[cfg(all(not(Py_3_10), Py_LIMITED_API))]
let kwarg_name = kwarg_name_py.extract::<crate::pybacked::PyBackedStr>();
if let Ok(kwarg_name_owned) = kwarg_name {
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
let kwarg_name = kwarg_name_owned;
#[cfg(all(not(Py_3_10), Py_LIMITED_API))]
let kwarg_name: &str = &kwarg_name_owned;
// Try to place parameter in keyword only parameters
if let Some(i) = self.find_keyword_parameter_in_keyword_only(kwarg_name) {
if output[i + num_positional_parameters]
.replace(value)
.is_some()
{
return Err(self.multiple_values_for_argument(kwarg_name));
}
continue;
}
// Repeat for positional parameters
if let Some(i) = self.find_keyword_parameter_in_positional(kwarg_name) {
if i < self.positional_only_parameters {
// If accepting **kwargs, then it's allowed for the name of the
// kwarg to conflict with a postional-only argument - the value
// will go into **kwargs anyway.
if K::handle_varkeyword(varkeywords, kwarg_name_py, value, self).is_err() {
positional_only_keyword_arguments.push(kwarg_name_owned);
}
} else if output[i].replace(value).is_some() {
return Err(self.multiple_values_for_argument(kwarg_name));
}
continue;
}
};
K::handle_varkeyword(varkeywords, kwarg_name_py, value, self)?
}
if !positional_only_keyword_arguments.is_empty() {
#[cfg(all(not(Py_3_10), Py_LIMITED_API))]
let positional_only_keyword_arguments: Vec<_> = positional_only_keyword_arguments
.iter()
.map(std::ops::Deref::deref)
.collect();
return Err(self.positional_only_keyword_arguments(&positional_only_keyword_arguments));
}
Ok(())
}
#[inline]
fn find_keyword_parameter_in_positional(&self, kwarg_name: &str) -> Option<usize> {
self.positional_parameter_names
.iter()
.position(|¶m_name| param_name == kwarg_name)
}
#[inline]
fn find_keyword_parameter_in_keyword_only(&self, kwarg_name: &str) -> Option<usize> {
// Compare the keyword name against each parameter in turn. This is exactly the same method
// which CPython uses to map keyword names. Although it's O(num_parameters), the number of
// parameters is expected to be small so it's not worth constructing a mapping.
self.keyword_only_parameters
.iter()
.position(|param_desc| param_desc.name == kwarg_name)
}
#[inline]
fn ensure_no_missing_required_positional_arguments(
&self,
output: &[Option<PyArg<'_>>],
positional_args_provided: usize,
) -> PyResult<()> {
if positional_args_provided < self.required_positional_parameters {
for out in &output[positional_args_provided..self.required_positional_parameters] {
if out.is_none() {
return Err(self.missing_required_positional_arguments(output));
}
}
}
Ok(())
}
#[inline]
fn ensure_no_missing_required_keyword_arguments(
&self,
output: &[Option<PyArg<'_>>],
) -> PyResult<()> {
let keyword_output = &output[self.positional_parameter_names.len()..];
for (param, out) in self.keyword_only_parameters.iter().zip(keyword_output) {
if param.required && out.is_none() {
return Err(self.missing_required_keyword_arguments(keyword_output));
}
}
Ok(())
}
#[cold]
fn too_many_positional_arguments(&self, args_provided: usize) -> PyErr {
let was = if args_provided == 1 { "was" } else { "were" };
let msg = if self.required_positional_parameters != self.positional_parameter_names.len() {
format!(
"{} takes from {} to {} positional arguments but {} {} given",
self.full_name(),
self.required_positional_parameters,
self.positional_parameter_names.len(),
args_provided,
was
)
} else {
format!(
"{} takes {} positional arguments but {} {} given",
self.full_name(),
self.positional_parameter_names.len(),
args_provided,
was
)
};
PyTypeError::new_err(msg)
}
#[cold]
fn multiple_values_for_argument(&self, argument: &str) -> PyErr {
PyTypeError::new_err(format!(
"{} got multiple values for argument '{}'",
self.full_name(),
argument
))
}
#[cold]
fn unexpected_keyword_argument(&self, argument: PyArg<'_>) -> PyErr {
PyTypeError::new_err(format!(
"{} got an unexpected keyword argument '{}'",
self.full_name(),
argument.as_any()
))
}
#[cold]
fn positional_only_keyword_arguments(&self, parameter_names: &[&str]) -> PyErr {
let mut msg = format!(
"{} got some positional-only arguments passed as keyword arguments: ",
self.full_name()
);
push_parameter_list(&mut msg, parameter_names);
PyTypeError::new_err(msg)
}
#[cold]
fn missing_required_arguments(&self, argument_type: &str, parameter_names: &[&str]) -> PyErr {
let arguments = if parameter_names.len() == 1 {
"argument"
} else {
"arguments"
};
let mut msg = format!(
"{} missing {} required {} {}: ",
self.full_name(),
parameter_names.len(),
argument_type,
arguments,
);
push_parameter_list(&mut msg, parameter_names);
PyTypeError::new_err(msg)
}
#[cold]
fn missing_required_keyword_arguments(&self, keyword_outputs: &[Option<PyArg<'_>>]) -> PyErr {
debug_assert_eq!(self.keyword_only_parameters.len(), keyword_outputs.len());
let missing_keyword_only_arguments: Vec<_> = self
.keyword_only_parameters
.iter()
.zip(keyword_outputs)
.filter_map(|(keyword_desc, out)| {
if keyword_desc.required && out.is_none() {
Some(keyword_desc.name)
} else {
None
}
})
.collect();
debug_assert!(!missing_keyword_only_arguments.is_empty());
self.missing_required_arguments("keyword", &missing_keyword_only_arguments)
}
#[cold]
fn missing_required_positional_arguments(&self, output: &[Option<PyArg<'_>>]) -> PyErr {
let missing_positional_arguments: Vec<_> = self
.positional_parameter_names
.iter()
.take(self.required_positional_parameters)
.zip(output)
.filter_map(|(param, out)| if out.is_none() { Some(*param) } else { None })
.collect();
debug_assert!(!missing_positional_arguments.is_empty());
self.missing_required_arguments("positional", &missing_positional_arguments)
}
}
/// A trait used to control whether to accept varargs in FunctionDescription::extract_argument_(method) functions.
pub trait VarargsHandler<'py> {
type Varargs;
/// Called by `FunctionDescription::extract_arguments_fastcall` with any additional arguments.
fn handle_varargs_fastcall(
py: Python<'py>,
varargs: &[Option<PyArg<'py>>],
function_description: &FunctionDescription,
) -> PyResult<Self::Varargs>;
/// Called by `FunctionDescription::extract_arguments_tuple_dict` with the original tuple.
///
/// Additional arguments are those in the tuple slice starting from `function_description.positional_parameter_names.len()`.
fn handle_varargs_tuple(
args: &Bound<'py, PyTuple>,
function_description: &FunctionDescription,
) -> PyResult<Self::Varargs>;
}
/// Marker struct which indicates varargs are not allowed.
pub struct NoVarargs;
impl<'py> VarargsHandler<'py> for NoVarargs {
type Varargs = ();
#[inline]
fn handle_varargs_fastcall(
_py: Python<'py>,
varargs: &[Option<PyArg<'py>>],
function_description: &FunctionDescription,
) -> PyResult<Self::Varargs> {
let extra_arguments = varargs.len();
if extra_arguments > 0 {
return Err(function_description.too_many_positional_arguments(
function_description.positional_parameter_names.len() + extra_arguments,
));
}
Ok(())
}
#[inline]
fn handle_varargs_tuple(
args: &Bound<'py, PyTuple>,
function_description: &FunctionDescription,
) -> PyResult<Self::Varargs> {
let positional_parameter_count = function_description.positional_parameter_names.len();
let provided_args_count = args.len();
if provided_args_count <= positional_parameter_count {
Ok(())
} else {
Err(function_description.too_many_positional_arguments(provided_args_count))
}
}
}
/// Marker struct which indicates varargs should be collected into a `PyTuple`.
pub struct TupleVarargs;
impl<'py> VarargsHandler<'py> for TupleVarargs {
type Varargs = Bound<'py, PyTuple>;
#[inline]
fn handle_varargs_fastcall(
py: Python<'py>,
varargs: &[Option<PyArg<'py>>],
_function_description: &FunctionDescription,
) -> PyResult<Self::Varargs> {
PyTuple::new(py, varargs)
}
#[inline]
fn handle_varargs_tuple(
args: &Bound<'py, PyTuple>,
function_description: &FunctionDescription,
) -> PyResult<Self::Varargs> {
let positional_parameters = function_description.positional_parameter_names.len();
Ok(args.get_slice(positional_parameters, args.len()))
}
}
/// A trait used to control whether to accept varkeywords in FunctionDescription::extract_argument_(method) functions.
pub trait VarkeywordsHandler<'py> {
type Varkeywords: Default;
fn handle_varkeyword(
varkeywords: &mut Self::Varkeywords,
name: PyArg<'py>,
value: PyArg<'py>,
function_description: &FunctionDescription,
) -> PyResult<()>;
}
/// Marker struct which indicates unknown keywords are not permitted.
pub struct NoVarkeywords;
impl<'py> VarkeywordsHandler<'py> for NoVarkeywords {
type Varkeywords = ();
#[inline]
fn handle_varkeyword(
_varkeywords: &mut Self::Varkeywords,
name: PyArg<'py>,
_value: PyArg<'py>,
function_description: &FunctionDescription,
) -> PyResult<()> {
Err(function_description.unexpected_keyword_argument(name))
}
}
/// Marker struct which indicates unknown keywords should be collected into a `PyDict`.
pub struct DictVarkeywords;
impl<'py> VarkeywordsHandler<'py> for DictVarkeywords {
type Varkeywords = Option<Bound<'py, PyDict>>;
#[inline]
fn handle_varkeyword(
varkeywords: &mut Self::Varkeywords,
name: PyArg<'py>,
value: PyArg<'py>,
_function_description: &FunctionDescription,
) -> PyResult<()> {
varkeywords
.get_or_insert_with(|| PyDict::new(name.py()))
.set_item(name, value)
}
}
fn push_parameter_list(msg: &mut String, parameter_names: &[&str]) {
let len = parameter_names.len();
for (i, parameter) in parameter_names.iter().enumerate() {
if i != 0 {
if len > 2 {
msg.push(',');
}
if i == len - 1 {
msg.push_str(" and ")
} else {
msg.push(' ')
}
}
msg.push('\'');
msg.push_str(parameter);
msg.push('\'');
}
}
#[cfg(test)]
mod tests {
use crate::types::{IntoPyDict, PyTuple};
use crate::Python;
use super::{push_parameter_list, FunctionDescription, NoVarargs, NoVarkeywords};
#[test]
fn unexpected_keyword_argument() {
let function_description = FunctionDescription {
cls_name: None,
func_name: "example",
positional_parameter_names: &[],
positional_only_parameters: 0,
required_positional_parameters: 0,
keyword_only_parameters: &[],
};
Python::with_gil(|py| {
let args = PyTuple::empty(py);
let kwargs = [("foo", 0u8)].into_py_dict(py).unwrap();
let err = unsafe {
function_description
.extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>(
py,
args.as_ptr(),
kwargs.as_ptr(),
&mut [],
)
.unwrap_err()
};
assert_eq!(
err.to_string(),
"TypeError: example() got an unexpected keyword argument 'foo'"
);
})
}
#[test]
fn keyword_not_string() {
let function_description = FunctionDescription {
cls_name: None,
func_name: "example",
positional_parameter_names: &[],
positional_only_parameters: 0,
required_positional_parameters: 0,
keyword_only_parameters: &[],
};
Python::with_gil(|py| {
let args = PyTuple::empty(py);
let kwargs = [(1u8, 1u8)].into_py_dict(py).unwrap();
let err = unsafe {
function_description
.extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>(
py,
args.as_ptr(),
kwargs.as_ptr(),
&mut [],
)
.unwrap_err()
};
assert_eq!(
err.to_string(),
"TypeError: example() got an unexpected keyword argument '1'"
);
})
}
#[test]
fn missing_required_arguments() {
let function_description = FunctionDescription {
cls_name: None,
func_name: "example",
positional_parameter_names: &["foo", "bar"],
positional_only_parameters: 0,
required_positional_parameters: 2,
keyword_only_parameters: &[],
};
Python::with_gil(|py| {
let args = PyTuple::empty(py);
let mut output = [None, None];
let err = unsafe {
function_description.extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>(
py,
args.as_ptr(),
std::ptr::null_mut(),
&mut output,
)
}
.unwrap_err();
assert_eq!(
err.to_string(),
"TypeError: example() missing 2 required positional arguments: 'foo' and 'bar'"
);
})
}
#[test]
fn push_parameter_list_empty() {
let mut s = String::new();
push_parameter_list(&mut s, &[]);
assert_eq!(&s, "");
}
#[test]
fn push_parameter_list_one() {
let mut s = String::new();
push_parameter_list(&mut s, &["a"]);
assert_eq!(&s, "'a'");
}
#[test]
fn push_parameter_list_two() {
let mut s = String::new();
push_parameter_list(&mut s, &["a", "b"]);
assert_eq!(&s, "'a' and 'b'");
}
#[test]
fn push_parameter_list_three() {
let mut s = String::new();
push_parameter_list(&mut s, &["a", "b", "c"]);
assert_eq!(&s, "'a', 'b', and 'c'");
}
#[test]
fn push_parameter_list_four() {
let mut s = String::new();
push_parameter_list(&mut s, &["a", "b", "c", "d"]);
assert_eq!(&s, "'a', 'b', 'c', and 'd'");
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/trampoline.rs | //! Trampolines for various pyfunction and pymethod implementations.
//!
//! They exist to monomorphise std::panic::catch_unwind once into PyO3, rather than inline in every
//! function, thus saving a huge amount of compile-time complexity.
use std::{
any::Any,
os::raw::c_int,
panic::{self, UnwindSafe},
};
use crate::gil::GILGuard;
use crate::{
ffi, ffi_ptr_ext::FfiPtrExt, impl_::callback::PyCallbackOutput, impl_::panic::PanicTrap,
impl_::pymethods::IPowModulo, panic::PanicException, types::PyModule, Py, PyResult, Python,
};
#[inline]
pub unsafe fn module_init(
f: for<'py> unsafe fn(Python<'py>) -> PyResult<Py<PyModule>>,
) -> *mut ffi::PyObject {
trampoline(|py| f(py).map(|module| module.into_ptr()))
}
#[inline]
#[allow(clippy::used_underscore_binding)]
pub unsafe fn noargs(
slf: *mut ffi::PyObject,
_args: *mut ffi::PyObject,
f: for<'py> unsafe fn(Python<'py>, *mut ffi::PyObject) -> PyResult<*mut ffi::PyObject>,
) -> *mut ffi::PyObject {
#[cfg(not(GraalPy))] // this is not specified and GraalPy does not pass null here
debug_assert!(_args.is_null());
trampoline(|py| f(py, slf))
}
macro_rules! trampoline {
(pub fn $name:ident($($arg_names:ident: $arg_types:ty),* $(,)?) -> $ret:ty;) => {
#[inline]
pub unsafe fn $name(
$($arg_names: $arg_types,)*
f: for<'py> unsafe fn (Python<'py>, $($arg_types),*) -> PyResult<$ret>,
) -> $ret {
trampoline(|py| f(py, $($arg_names,)*))
}
}
}
macro_rules! trampolines {
($(pub fn $name:ident($($arg_names:ident: $arg_types:ty),* $(,)?) -> $ret:ty);* ;) => {
$(trampoline!(pub fn $name($($arg_names: $arg_types),*) -> $ret;));*;
}
}
trampolines!(
pub fn fastcall_with_keywords(
slf: *mut ffi::PyObject,
args: *const *mut ffi::PyObject,
nargs: ffi::Py_ssize_t,
kwnames: *mut ffi::PyObject,
) -> *mut ffi::PyObject;
pub fn cfunction_with_keywords(
slf: *mut ffi::PyObject,
args: *mut ffi::PyObject,
kwargs: *mut ffi::PyObject,
) -> *mut ffi::PyObject;
);
// Trampolines used by slot methods
trampolines!(
pub fn getattrofunc(slf: *mut ffi::PyObject, attr: *mut ffi::PyObject) -> *mut ffi::PyObject;
pub fn setattrofunc(
slf: *mut ffi::PyObject,
attr: *mut ffi::PyObject,
value: *mut ffi::PyObject,
) -> c_int;
pub fn binaryfunc(slf: *mut ffi::PyObject, arg1: *mut ffi::PyObject) -> *mut ffi::PyObject;
pub fn descrgetfunc(
slf: *mut ffi::PyObject,
arg1: *mut ffi::PyObject,
arg2: *mut ffi::PyObject,
) -> *mut ffi::PyObject;
pub fn getiterfunc(slf: *mut ffi::PyObject) -> *mut ffi::PyObject;
pub fn hashfunc(slf: *mut ffi::PyObject) -> ffi::Py_hash_t;
pub fn inquiry(slf: *mut ffi::PyObject) -> c_int;
pub fn iternextfunc(slf: *mut ffi::PyObject) -> *mut ffi::PyObject;
pub fn lenfunc(slf: *mut ffi::PyObject) -> ffi::Py_ssize_t;
pub fn newfunc(
subtype: *mut ffi::PyTypeObject,
args: *mut ffi::PyObject,
kwargs: *mut ffi::PyObject,
) -> *mut ffi::PyObject;
pub fn objobjproc(slf: *mut ffi::PyObject, arg1: *mut ffi::PyObject) -> c_int;
pub fn reprfunc(slf: *mut ffi::PyObject) -> *mut ffi::PyObject;
pub fn richcmpfunc(
slf: *mut ffi::PyObject,
other: *mut ffi::PyObject,
op: c_int,
) -> *mut ffi::PyObject;
pub fn ssizeargfunc(arg1: *mut ffi::PyObject, arg2: ffi::Py_ssize_t) -> *mut ffi::PyObject;
pub fn ternaryfunc(
slf: *mut ffi::PyObject,
arg1: *mut ffi::PyObject,
arg2: *mut ffi::PyObject,
) -> *mut ffi::PyObject;
pub fn unaryfunc(slf: *mut ffi::PyObject) -> *mut ffi::PyObject;
);
#[cfg(any(not(Py_LIMITED_API), Py_3_11))]
trampoline! {
pub fn getbufferproc(slf: *mut ffi::PyObject, buf: *mut ffi::Py_buffer, flags: c_int) -> c_int;
}
#[cfg(any(not(Py_LIMITED_API), Py_3_11))]
#[inline]
pub unsafe fn releasebufferproc(
slf: *mut ffi::PyObject,
buf: *mut ffi::Py_buffer,
f: for<'py> unsafe fn(Python<'py>, *mut ffi::PyObject, *mut ffi::Py_buffer) -> PyResult<()>,
) {
trampoline_unraisable(|py| f(py, slf, buf), slf)
}
#[inline]
pub(crate) unsafe fn dealloc(
slf: *mut ffi::PyObject,
f: for<'py> unsafe fn(Python<'py>, *mut ffi::PyObject) -> (),
) {
// After calling tp_dealloc the object is no longer valid,
// so pass null_mut() to the context.
//
// (Note that we don't allow the implementation `f` to fail.)
trampoline_unraisable(
|py| {
f(py, slf);
Ok(())
},
std::ptr::null_mut(),
)
}
// Ipowfunc is a unique case where PyO3 has its own type
// to workaround a problem on 3.7 (see IPowModulo type definition).
// Once 3.7 support dropped can just remove this.
trampoline!(
pub fn ipowfunc(
arg1: *mut ffi::PyObject,
arg2: *mut ffi::PyObject,
arg3: IPowModulo,
) -> *mut ffi::PyObject;
);
/// Implementation of trampoline functions, which sets up a GILPool and calls F.
///
/// Panics during execution are trapped so that they don't propagate through any
/// outer FFI boundary.
///
/// The GIL must already be held when this is called.
#[inline]
pub(crate) unsafe fn trampoline<F, R>(body: F) -> R
where
F: for<'py> FnOnce(Python<'py>) -> PyResult<R> + UnwindSafe,
R: PyCallbackOutput,
{
let trap = PanicTrap::new("uncaught panic at ffi boundary");
// SAFETY: This function requires the GIL to already be held.
let guard = GILGuard::assume();
let py = guard.python();
let out = panic_result_into_callback_output(
py,
panic::catch_unwind(move || -> PyResult<_> { body(py) }),
);
trap.disarm();
out
}
/// Converts the output of std::panic::catch_unwind into a Python function output, either by raising a Python
/// exception or by unwrapping the contained success output.
#[inline]
fn panic_result_into_callback_output<R>(
py: Python<'_>,
panic_result: Result<PyResult<R>, Box<dyn Any + Send + 'static>>,
) -> R
where
R: PyCallbackOutput,
{
let py_err = match panic_result {
Ok(Ok(value)) => return value,
Ok(Err(py_err)) => py_err,
Err(payload) => PanicException::from_panic_payload(payload),
};
py_err.restore(py);
R::ERR_VALUE
}
/// Implementation of trampoline for functions which can't return an error.
///
/// Panics during execution are trapped so that they don't propagate through any
/// outer FFI boundary.
///
/// Exceptions produced are sent to `sys.unraisablehook`.
///
/// # Safety
///
/// - ctx must be either a valid ffi::PyObject or NULL
/// - The GIL must already be held when this is called.
#[inline]
unsafe fn trampoline_unraisable<F>(body: F, ctx: *mut ffi::PyObject)
where
F: for<'py> FnOnce(Python<'py>) -> PyResult<()> + UnwindSafe,
{
let trap = PanicTrap::new("uncaught panic at ffi boundary");
// SAFETY: The GIL is already held.
let guard = GILGuard::assume();
let py = guard.python();
if let Err(py_err) = panic::catch_unwind(move || body(py))
.unwrap_or_else(|payload| Err(PanicException::from_panic_payload(payload)))
{
py_err.write_unraisable(py, ctx.assume_borrowed_or_opt(py).as_deref());
}
trap.disarm();
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/freelist.rs | //! Support for [free allocation lists][1].
//!
//! This can improve performance for types that are often created and deleted in quick succession.
//!
//! Rather than implementing this manually,
//! implement it by annotating a struct with `#[pyclass(freelist = N)]`,
//! where `N` is the size of the freelist.
//!
//! [1]: https://en.wikipedia.org/wiki/Free_list
use std::mem;
/// Represents a slot of a [`FreeList`].
pub enum Slot<T> {
/// A free slot.
Empty,
/// An allocated slot.
Filled(T),
}
/// A free allocation list.
///
/// See [the parent module](crate::impl_::freelist) for more details.
pub struct FreeList<T> {
entries: Vec<Slot<T>>,
split: usize,
capacity: usize,
}
impl<T> FreeList<T> {
/// Creates a new `FreeList` instance with specified capacity.
pub fn with_capacity(capacity: usize) -> FreeList<T> {
let entries = (0..capacity).map(|_| Slot::Empty).collect::<Vec<_>>();
FreeList {
entries,
split: 0,
capacity,
}
}
/// Pops the first non empty item.
pub fn pop(&mut self) -> Option<T> {
let idx = self.split;
if idx == 0 {
None
} else {
match mem::replace(&mut self.entries[idx - 1], Slot::Empty) {
Slot::Filled(v) => {
self.split = idx - 1;
Some(v)
}
_ => panic!("FreeList is corrupt"),
}
}
}
/// Inserts a value into the list. Returns `Some(val)` if the `FreeList` is full.
pub fn insert(&mut self, val: T) -> Option<T> {
let next = self.split + 1;
if next < self.capacity {
self.entries[self.split] = Slot::Filled(val);
self.split = next;
None
} else {
Some(val)
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/not_send.rs | use std::marker::PhantomData;
use crate::Python;
/// A marker type that makes the type !Send.
/// Workaround for lack of !Send on stable (<https://github.com/rust-lang/rust/issues/68318>).
pub(crate) struct NotSend(PhantomData<*mut Python<'static>>);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pyfunction.rs | use crate::{
types::{PyCFunction, PyModule},
Borrowed, Bound, PyResult, Python,
};
pub use crate::impl_::pymethods::PyMethodDef;
/// Trait to enable the use of `wrap_pyfunction` with both `Python` and `PyModule`,
/// and also to infer the return type of either `&'py PyCFunction` or `Bound<'py, PyCFunction>`.
pub trait WrapPyFunctionArg<'py, T> {
fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<T>;
}
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Bound<'py, PyModule> {
fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
PyCFunction::internal_new(self.py(), method_def, Some(&self))
}
}
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for &'_ Bound<'py, PyModule> {
fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
PyCFunction::internal_new(self.py(), method_def, Some(self))
}
}
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Borrowed<'_, 'py, PyModule> {
fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
PyCFunction::internal_new(self.py(), method_def, Some(&self))
}
}
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for &'_ Borrowed<'_, 'py, PyModule> {
fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
PyCFunction::internal_new(self.py(), method_def, Some(self))
}
}
impl<'py> WrapPyFunctionArg<'py, Bound<'py, PyCFunction>> for Python<'py> {
fn wrap_pyfunction(self, method_def: &PyMethodDef) -> PyResult<Bound<'py, PyCFunction>> {
PyCFunction::internal_new(self, method_def, None)
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pyclass_init.rs | //! Contains initialization utilities for `#[pyclass]`.
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::internal::get_slot::TP_ALLOC;
use crate::types::PyType;
use crate::{ffi, Borrowed, PyErr, PyResult, Python};
use crate::{ffi::PyTypeObject, sealed::Sealed, type_object::PyTypeInfo};
use std::marker::PhantomData;
/// Initializer for Python types.
///
/// This trait is intended to use internally for distinguishing `#[pyclass]` and
/// Python native types.
pub trait PyObjectInit<T>: Sized + Sealed {
/// # Safety
/// - `subtype` must be a valid pointer to a type object of T or a subclass.
unsafe fn into_new_object(
self,
py: Python<'_>,
subtype: *mut PyTypeObject,
) -> PyResult<*mut ffi::PyObject>;
#[doc(hidden)]
fn can_be_subclassed(&self) -> bool;
}
/// Initializer for Python native types, like `PyDict`.
pub struct PyNativeTypeInitializer<T: PyTypeInfo>(pub PhantomData<T>);
impl<T: PyTypeInfo> PyObjectInit<T> for PyNativeTypeInitializer<T> {
unsafe fn into_new_object(
self,
py: Python<'_>,
subtype: *mut PyTypeObject,
) -> PyResult<*mut ffi::PyObject> {
unsafe fn inner(
py: Python<'_>,
type_object: *mut PyTypeObject,
subtype: *mut PyTypeObject,
) -> PyResult<*mut ffi::PyObject> {
// HACK (due to FIXME below): PyBaseObject_Type's tp_new isn't happy with NULL arguments
let is_base_object = type_object == std::ptr::addr_of_mut!(ffi::PyBaseObject_Type);
let subtype_borrowed: Borrowed<'_, '_, PyType> = subtype
.cast::<ffi::PyObject>()
.assume_borrowed_unchecked(py)
.downcast_unchecked();
if is_base_object {
let alloc = subtype_borrowed
.get_slot(TP_ALLOC)
.unwrap_or(ffi::PyType_GenericAlloc);
let obj = alloc(subtype, 0);
return if obj.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(obj)
};
}
#[cfg(Py_LIMITED_API)]
unreachable!("subclassing native types is not possible with the `abi3` feature");
#[cfg(not(Py_LIMITED_API))]
{
match (*type_object).tp_new {
// FIXME: Call __new__ with actual arguments
Some(newfunc) => {
let obj = newfunc(subtype, std::ptr::null_mut(), std::ptr::null_mut());
if obj.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(obj)
}
}
None => Err(crate::exceptions::PyTypeError::new_err(
"base type without tp_new",
)),
}
}
}
let type_object = T::type_object_raw(py);
inner(py, type_object, subtype)
}
#[inline]
fn can_be_subclassed(&self) -> bool {
true
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/frompyobject.rs | use crate::types::any::PyAnyMethods;
use crate::Bound;
use crate::{exceptions::PyTypeError, FromPyObject, PyAny, PyErr, PyResult, Python};
#[cold]
pub fn failed_to_extract_enum(
py: Python<'_>,
type_name: &str,
variant_names: &[&str],
error_names: &[&str],
errors: &[PyErr],
) -> PyErr {
// TODO maybe use ExceptionGroup on Python 3.11+ ?
let mut err_msg = format!(
"failed to extract enum {} ('{}')",
type_name,
error_names.join(" | ")
);
for ((variant_name, error_name), error) in variant_names.iter().zip(error_names).zip(errors) {
use std::fmt::Write;
write!(
&mut err_msg,
"\n- variant {variant_name} ({error_name}): {error_msg}",
variant_name = variant_name,
error_name = error_name,
error_msg = extract_traceback(py, error.clone_ref(py)),
)
.unwrap();
}
PyTypeError::new_err(err_msg)
}
/// Flattens a chain of errors into a single string.
fn extract_traceback(py: Python<'_>, mut error: PyErr) -> String {
use std::fmt::Write;
let mut error_msg = error.to_string();
while let Some(cause) = error.cause(py) {
write!(&mut error_msg, ", caused by {}", cause).unwrap();
error = cause
}
error_msg
}
pub fn extract_struct_field<'py, T>(
obj: &Bound<'py, PyAny>,
struct_name: &str,
field_name: &str,
) -> PyResult<T>
where
T: FromPyObject<'py>,
{
match obj.extract() {
Ok(value) => Ok(value),
Err(err) => Err(failed_to_extract_struct_field(
obj.py(),
err,
struct_name,
field_name,
)),
}
}
pub fn extract_struct_field_with<'a, 'py, T>(
extractor: fn(&'a Bound<'py, PyAny>) -> PyResult<T>,
obj: &'a Bound<'py, PyAny>,
struct_name: &str,
field_name: &str,
) -> PyResult<T> {
match extractor(obj) {
Ok(value) => Ok(value),
Err(err) => Err(failed_to_extract_struct_field(
obj.py(),
err,
struct_name,
field_name,
)),
}
}
#[cold]
fn failed_to_extract_struct_field(
py: Python<'_>,
inner_err: PyErr,
struct_name: &str,
field_name: &str,
) -> PyErr {
let new_err = PyTypeError::new_err(format!(
"failed to extract field {}.{}",
struct_name, field_name
));
new_err.set_cause(py, ::std::option::Option::Some(inner_err));
new_err
}
pub fn extract_tuple_struct_field<'py, T>(
obj: &Bound<'py, PyAny>,
struct_name: &str,
index: usize,
) -> PyResult<T>
where
T: FromPyObject<'py>,
{
match obj.extract() {
Ok(value) => Ok(value),
Err(err) => Err(failed_to_extract_tuple_struct_field(
obj.py(),
err,
struct_name,
index,
)),
}
}
pub fn extract_tuple_struct_field_with<'a, 'py, T>(
extractor: fn(&'a Bound<'py, PyAny>) -> PyResult<T>,
obj: &'a Bound<'py, PyAny>,
struct_name: &str,
index: usize,
) -> PyResult<T> {
match extractor(obj) {
Ok(value) => Ok(value),
Err(err) => Err(failed_to_extract_tuple_struct_field(
obj.py(),
err,
struct_name,
index,
)),
}
}
#[cold]
fn failed_to_extract_tuple_struct_field(
py: Python<'_>,
inner_err: PyErr,
struct_name: &str,
index: usize,
) -> PyErr {
let new_err =
PyTypeError::new_err(format!("failed to extract field {}.{}", struct_name, index));
new_err.set_cause(py, ::std::option::Option::Some(inner_err));
new_err
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pymethods.rs | use crate::exceptions::PyStopAsyncIteration;
use crate::gil::LockGIL;
use crate::impl_::callback::IntoPyCallbackOutput;
use crate::impl_::panic::PanicTrap;
use crate::impl_::pycell::{PyClassObject, PyClassObjectLayout};
use crate::internal::get_slot::{get_slot, TP_BASE, TP_CLEAR, TP_TRAVERSE};
use crate::pycell::impl_::PyClassBorrowChecker as _;
use crate::pycell::{PyBorrowError, PyBorrowMutError};
use crate::pyclass::boolean_struct::False;
use crate::types::any::PyAnyMethods;
use crate::types::PyType;
use crate::{
ffi, Bound, DowncastError, Py, PyAny, PyClass, PyClassInitializer, PyErr, PyObject, PyRef,
PyRefMut, PyResult, PyTraverseError, PyTypeCheck, PyVisit, Python,
};
use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{c_int, c_void};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr::null_mut;
use super::trampoline;
/// Python 3.8 and up - __ipow__ has modulo argument correctly populated.
#[cfg(Py_3_8)]
#[repr(transparent)]
pub struct IPowModulo(*mut ffi::PyObject);
/// Python 3.7 and older - __ipow__ does not have modulo argument correctly populated.
#[cfg(not(Py_3_8))]
#[repr(transparent)]
pub struct IPowModulo(#[allow(dead_code)] std::mem::MaybeUninit<*mut ffi::PyObject>);
/// Helper to use as pymethod ffi definition
#[allow(non_camel_case_types)]
pub type ipowfunc = unsafe extern "C" fn(
arg1: *mut ffi::PyObject,
arg2: *mut ffi::PyObject,
arg3: IPowModulo,
) -> *mut ffi::PyObject;
impl IPowModulo {
#[cfg(Py_3_8)]
#[inline]
pub fn as_ptr(self) -> *mut ffi::PyObject {
self.0
}
#[cfg(not(Py_3_8))]
#[inline]
pub fn as_ptr(self) -> *mut ffi::PyObject {
// Safety: returning a borrowed pointer to Python `None` singleton
unsafe { ffi::Py_None() }
}
}
/// `PyMethodDefType` represents different types of Python callable objects.
/// It is used by the `#[pymethods]` attribute.
#[cfg_attr(test, derive(Clone))]
pub enum PyMethodDefType {
/// Represents class method
Class(PyMethodDef),
/// Represents static method
Static(PyMethodDef),
/// Represents normal method
Method(PyMethodDef),
/// Represents class attribute, used by `#[attribute]`
ClassAttribute(PyClassAttributeDef),
/// Represents getter descriptor, used by `#[getter]`
Getter(PyGetterDef),
/// Represents setter descriptor, used by `#[setter]`
Setter(PySetterDef),
/// Represents a struct member
StructMember(ffi::PyMemberDef),
}
#[derive(Copy, Clone, Debug)]
pub enum PyMethodType {
PyCFunction(ffi::PyCFunction),
PyCFunctionWithKeywords(ffi::PyCFunctionWithKeywords),
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
PyCFunctionFastWithKeywords(ffi::PyCFunctionFastWithKeywords),
}
pub type PyClassAttributeFactory = for<'p> fn(Python<'p>) -> PyResult<PyObject>;
// TODO: it would be nice to use CStr in these types, but then the constructors can't be const fn
// until `CStr::from_bytes_with_nul_unchecked` is const fn.
#[derive(Clone, Debug)]
pub struct PyMethodDef {
pub(crate) ml_name: &'static CStr,
pub(crate) ml_meth: PyMethodType,
pub(crate) ml_flags: c_int,
pub(crate) ml_doc: &'static CStr,
}
#[derive(Copy, Clone)]
pub struct PyClassAttributeDef {
pub(crate) name: &'static CStr,
pub(crate) meth: PyClassAttributeFactory,
}
#[derive(Clone)]
pub struct PyGetterDef {
pub(crate) name: &'static CStr,
pub(crate) meth: Getter,
pub(crate) doc: &'static CStr,
}
#[derive(Clone)]
pub struct PySetterDef {
pub(crate) name: &'static CStr,
pub(crate) meth: Setter,
pub(crate) doc: &'static CStr,
}
unsafe impl Sync for PyMethodDef {}
unsafe impl Sync for PyGetterDef {}
unsafe impl Sync for PySetterDef {}
impl PyMethodDef {
/// Define a function with no `*args` and `**kwargs`.
pub const fn noargs(
ml_name: &'static CStr,
cfunction: ffi::PyCFunction,
ml_doc: &'static CStr,
) -> Self {
Self {
ml_name,
ml_meth: PyMethodType::PyCFunction(cfunction),
ml_flags: ffi::METH_NOARGS,
ml_doc,
}
}
/// Define a function that can take `*args` and `**kwargs`.
pub const fn cfunction_with_keywords(
ml_name: &'static CStr,
cfunction: ffi::PyCFunctionWithKeywords,
ml_doc: &'static CStr,
) -> Self {
Self {
ml_name,
ml_meth: PyMethodType::PyCFunctionWithKeywords(cfunction),
ml_flags: ffi::METH_VARARGS | ffi::METH_KEYWORDS,
ml_doc,
}
}
/// Define a function that can take `*args` and `**kwargs`.
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
pub const fn fastcall_cfunction_with_keywords(
ml_name: &'static CStr,
cfunction: ffi::PyCFunctionFastWithKeywords,
ml_doc: &'static CStr,
) -> Self {
Self {
ml_name,
ml_meth: PyMethodType::PyCFunctionFastWithKeywords(cfunction),
ml_flags: ffi::METH_FASTCALL | ffi::METH_KEYWORDS,
ml_doc,
}
}
pub const fn flags(mut self, flags: c_int) -> Self {
self.ml_flags |= flags;
self
}
/// Convert `PyMethodDef` to Python method definition struct `ffi::PyMethodDef`
pub(crate) fn as_method_def(&self) -> ffi::PyMethodDef {
let meth = match self.ml_meth {
PyMethodType::PyCFunction(meth) => ffi::PyMethodDefPointer { PyCFunction: meth },
PyMethodType::PyCFunctionWithKeywords(meth) => ffi::PyMethodDefPointer {
PyCFunctionWithKeywords: meth,
},
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
PyMethodType::PyCFunctionFastWithKeywords(meth) => ffi::PyMethodDefPointer {
PyCFunctionFastWithKeywords: meth,
},
};
ffi::PyMethodDef {
ml_name: self.ml_name.as_ptr(),
ml_meth: meth,
ml_flags: self.ml_flags,
ml_doc: self.ml_doc.as_ptr(),
}
}
}
impl PyClassAttributeDef {
/// Define a class attribute.
pub const fn new(name: &'static CStr, meth: PyClassAttributeFactory) -> Self {
Self { name, meth }
}
}
// Manual implementation because `Python<'_>` does not implement `Debug` and
// trait bounds on `fn` compiler-generated derive impls are too restrictive.
impl fmt::Debug for PyClassAttributeDef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PyClassAttributeDef")
.field("name", &self.name)
.finish()
}
}
/// Class getter / setters
pub(crate) type Getter =
for<'py> unsafe fn(Python<'py>, *mut ffi::PyObject) -> PyResult<*mut ffi::PyObject>;
pub(crate) type Setter =
for<'py> unsafe fn(Python<'py>, *mut ffi::PyObject, *mut ffi::PyObject) -> PyResult<c_int>;
impl PyGetterDef {
/// Define a getter.
pub const fn new(name: &'static CStr, getter: Getter, doc: &'static CStr) -> Self {
Self {
name,
meth: getter,
doc,
}
}
}
impl PySetterDef {
/// Define a setter.
pub const fn new(name: &'static CStr, setter: Setter, doc: &'static CStr) -> Self {
Self {
name,
meth: setter,
doc,
}
}
}
/// Calls an implementation of __traverse__ for tp_traverse
///
/// NB cannot accept `'static` visitor, this is a sanity check below:
///
/// ```rust,compile_fail
/// use pyo3::prelude::*;
/// use pyo3::pyclass::{PyTraverseError, PyVisit};
///
/// #[pyclass]
/// struct Foo;
///
/// #[pymethods]
/// impl Foo {
/// fn __traverse__(&self, _visit: PyVisit<'static>) -> Result<(), PyTraverseError> {
/// Ok(())
/// }
/// }
/// ```
///
/// Elided lifetime should compile ok:
///
/// ```rust
/// use pyo3::prelude::*;
/// use pyo3::pyclass::{PyTraverseError, PyVisit};
///
/// #[pyclass]
/// struct Foo;
///
/// #[pymethods]
/// impl Foo {
/// fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
/// Ok(())
/// }
/// }
/// ```
#[doc(hidden)]
pub unsafe fn _call_traverse<T>(
slf: *mut ffi::PyObject,
impl_: fn(&T, PyVisit<'_>) -> Result<(), PyTraverseError>,
visit: ffi::visitproc,
arg: *mut c_void,
current_traverse: ffi::traverseproc,
) -> c_int
where
T: PyClass,
{
// It is important the implementation of `__traverse__` cannot safely access the GIL,
// c.f. https://github.com/PyO3/pyo3/issues/3165, and hence we do not expose our GIL
// token to the user code and lock safe methods for acquiring the GIL.
// (This includes enforcing the `&self` method receiver as e.g. `PyRef<Self>` could
// reconstruct a GIL token via `PyRef::py`.)
// Since we do not create a `GILPool` at all, it is important that our usage of the GIL
// token does not produce any owned objects thereby calling into `register_owned`.
let trap = PanicTrap::new("uncaught panic inside __traverse__ handler");
let lock = LockGIL::during_traverse();
let super_retval = call_super_traverse(slf, visit, arg, current_traverse);
if super_retval != 0 {
return super_retval;
}
// SAFETY: `slf` is a valid Python object pointer to a class object of type T, and
// traversal is running so no mutations can occur.
let class_object: &PyClassObject<T> = &*slf.cast();
let retval =
// `#[pyclass(unsendable)]` types can only be deallocated by their own thread, so
// do not traverse them if not on their owning thread :(
if class_object.check_threadsafe().is_ok()
// ... and we cannot traverse a type which might be being mutated by a Rust thread
&& class_object.borrow_checker().try_borrow().is_ok() {
struct TraverseGuard<'a, T: PyClass>(&'a PyClassObject<T>);
impl<T: PyClass> Drop for TraverseGuard<'_, T> {
fn drop(&mut self) {
self.0.borrow_checker().release_borrow()
}
}
// `.try_borrow()` above created a borrow, we need to release it when we're done
// traversing the object. This allows us to read `instance` safely.
let _guard = TraverseGuard(class_object);
let instance = &*class_object.contents.value.get();
let visit = PyVisit { visit, arg, _guard: PhantomData };
match catch_unwind(AssertUnwindSafe(move || impl_(instance, visit))) {
Ok(Ok(())) => 0,
Ok(Err(traverse_error)) => traverse_error.into_inner(),
Err(_err) => -1,
}
} else {
0
};
// Drop lock before trap just in case dropping lock panics
drop(lock);
trap.disarm();
retval
}
/// Call super-type traverse method, if necessary.
///
/// Adapted from <https://github.com/cython/cython/blob/7acfb375fb54a033f021b0982a3cd40c34fb22ac/Cython/Utility/ExtensionTypes.c#L386>
///
/// TODO: There are possible optimizations over looking up the base type in this way
/// - if the base type is known in this module, can potentially look it up directly in module state
/// (when we have it)
/// - if the base type is a Python builtin, can jut call the C function directly
/// - if the base type is a PyO3 type defined in the same module, can potentially do similar to
/// tp_alloc where we solve this at compile time
unsafe fn call_super_traverse(
obj: *mut ffi::PyObject,
visit: ffi::visitproc,
arg: *mut c_void,
current_traverse: ffi::traverseproc,
) -> c_int {
// SAFETY: in this function here it's ok to work with raw type objects `ffi::Py_TYPE`
// because the GC is running and so
// - (a) we cannot do refcounting and
// - (b) the type of the object cannot change.
let mut ty = ffi::Py_TYPE(obj);
let mut traverse: Option<ffi::traverseproc>;
// First find the current type by the current_traverse function
loop {
traverse = get_slot(ty, TP_TRAVERSE);
if traverse == Some(current_traverse) {
break;
}
ty = get_slot(ty, TP_BASE);
if ty.is_null() {
// FIXME: return an error if current type not in the MRO? Should be impossible.
return 0;
}
}
// Get first base which has a different traverse function
while traverse == Some(current_traverse) {
ty = get_slot(ty, TP_BASE);
if ty.is_null() {
break;
}
traverse = get_slot(ty, TP_TRAVERSE);
}
// If we found a type with a different traverse function, call it
if let Some(traverse) = traverse {
return traverse(obj, visit, arg);
}
// FIXME same question as cython: what if the current type is not in the MRO?
0
}
/// Calls an implementation of __clear__ for tp_clear
pub unsafe fn _call_clear(
slf: *mut ffi::PyObject,
impl_: for<'py> unsafe fn(Python<'py>, *mut ffi::PyObject) -> PyResult<()>,
current_clear: ffi::inquiry,
) -> c_int {
trampoline::trampoline(move |py| {
let super_retval = call_super_clear(py, slf, current_clear);
if super_retval != 0 {
return Err(PyErr::fetch(py));
}
impl_(py, slf)?;
Ok(0)
})
}
/// Call super-type traverse method, if necessary.
///
/// Adapted from <https://github.com/cython/cython/blob/7acfb375fb54a033f021b0982a3cd40c34fb22ac/Cython/Utility/ExtensionTypes.c#L386>
///
/// TODO: There are possible optimizations over looking up the base type in this way
/// - if the base type is known in this module, can potentially look it up directly in module state
/// (when we have it)
/// - if the base type is a Python builtin, can jut call the C function directly
/// - if the base type is a PyO3 type defined in the same module, can potentially do similar to
/// tp_alloc where we solve this at compile time
unsafe fn call_super_clear(
py: Python<'_>,
obj: *mut ffi::PyObject,
current_clear: ffi::inquiry,
) -> c_int {
let mut ty = PyType::from_borrowed_type_ptr(py, ffi::Py_TYPE(obj));
let mut clear: Option<ffi::inquiry>;
// First find the current type by the current_clear function
loop {
clear = ty.get_slot(TP_CLEAR);
if clear == Some(current_clear) {
break;
}
let base = ty.get_slot(TP_BASE);
if base.is_null() {
// FIXME: return an error if current type not in the MRO? Should be impossible.
return 0;
}
ty = PyType::from_borrowed_type_ptr(py, base);
}
// Get first base which has a different clear function
while clear == Some(current_clear) {
let base = ty.get_slot(TP_BASE);
if base.is_null() {
break;
}
ty = PyType::from_borrowed_type_ptr(py, base);
clear = ty.get_slot(TP_CLEAR);
}
// If we found a type with a different clear function, call it
if let Some(clear) = clear {
return clear(obj);
}
// FIXME same question as cython: what if the current type is not in the MRO?
0
}
// Autoref-based specialization for handling `__next__` returning `Option`
pub struct IterBaseTag;
impl IterBaseTag {
#[inline]
pub fn convert<'py, Value, Target>(self, py: Python<'py>, value: Value) -> PyResult<Target>
where
Value: IntoPyCallbackOutput<'py, Target>,
{
value.convert(py)
}
}
pub trait IterBaseKind {
#[inline]
fn iter_tag(&self) -> IterBaseTag {
IterBaseTag
}
}
impl<Value> IterBaseKind for &Value {}
pub struct IterOptionTag;
impl IterOptionTag {
#[inline]
pub fn convert<'py, Value>(
self,
py: Python<'py>,
value: Option<Value>,
) -> PyResult<*mut ffi::PyObject>
where
Value: IntoPyCallbackOutput<'py, *mut ffi::PyObject>,
{
match value {
Some(value) => value.convert(py),
None => Ok(null_mut()),
}
}
}
pub trait IterOptionKind {
#[inline]
fn iter_tag(&self) -> IterOptionTag {
IterOptionTag
}
}
impl<Value> IterOptionKind for Option<Value> {}
pub struct IterResultOptionTag;
impl IterResultOptionTag {
#[inline]
pub fn convert<'py, Value, Error>(
self,
py: Python<'py>,
value: Result<Option<Value>, Error>,
) -> PyResult<*mut ffi::PyObject>
where
Value: IntoPyCallbackOutput<'py, *mut ffi::PyObject>,
Error: Into<PyErr>,
{
match value {
Ok(Some(value)) => value.convert(py),
Ok(None) => Ok(null_mut()),
Err(err) => Err(err.into()),
}
}
}
pub trait IterResultOptionKind {
#[inline]
fn iter_tag(&self) -> IterResultOptionTag {
IterResultOptionTag
}
}
impl<Value, Error> IterResultOptionKind for Result<Option<Value>, Error> {}
// Autoref-based specialization for handling `__anext__` returning `Option`
pub struct AsyncIterBaseTag;
impl AsyncIterBaseTag {
#[inline]
pub fn convert<'py, Value, Target>(self, py: Python<'py>, value: Value) -> PyResult<Target>
where
Value: IntoPyCallbackOutput<'py, Target>,
{
value.convert(py)
}
}
pub trait AsyncIterBaseKind {
#[inline]
fn async_iter_tag(&self) -> AsyncIterBaseTag {
AsyncIterBaseTag
}
}
impl<Value> AsyncIterBaseKind for &Value {}
pub struct AsyncIterOptionTag;
impl AsyncIterOptionTag {
#[inline]
pub fn convert<'py, Value>(
self,
py: Python<'py>,
value: Option<Value>,
) -> PyResult<*mut ffi::PyObject>
where
Value: IntoPyCallbackOutput<'py, *mut ffi::PyObject>,
{
match value {
Some(value) => value.convert(py),
None => Err(PyStopAsyncIteration::new_err(())),
}
}
}
pub trait AsyncIterOptionKind {
#[inline]
fn async_iter_tag(&self) -> AsyncIterOptionTag {
AsyncIterOptionTag
}
}
impl<Value> AsyncIterOptionKind for Option<Value> {}
pub struct AsyncIterResultOptionTag;
impl AsyncIterResultOptionTag {
#[inline]
pub fn convert<'py, Value, Error>(
self,
py: Python<'py>,
value: Result<Option<Value>, Error>,
) -> PyResult<*mut ffi::PyObject>
where
Value: IntoPyCallbackOutput<'py, *mut ffi::PyObject>,
Error: Into<PyErr>,
{
match value {
Ok(Some(value)) => value.convert(py),
Ok(None) => Err(PyStopAsyncIteration::new_err(())),
Err(err) => Err(err.into()),
}
}
}
pub trait AsyncIterResultOptionKind {
#[inline]
fn async_iter_tag(&self) -> AsyncIterResultOptionTag {
AsyncIterResultOptionTag
}
}
impl<Value, Error> AsyncIterResultOptionKind for Result<Option<Value>, Error> {}
/// Used in `#[classmethod]` to pass the class object to the method
/// and also in `#[pyfunction(pass_module)]`.
///
/// This is a wrapper to avoid implementing `From<Bound>` for GIL Refs.
///
/// Once the GIL Ref API is fully removed, it should be possible to simplify
/// this to just `&'a Bound<'py, T>` and `From` implementations.
pub struct BoundRef<'a, 'py, T>(pub &'a Bound<'py, T>);
impl<'a, 'py> BoundRef<'a, 'py, PyAny> {
pub unsafe fn ref_from_ptr(py: Python<'py>, ptr: &'a *mut ffi::PyObject) -> Self {
BoundRef(Bound::ref_from_ptr(py, ptr))
}
pub unsafe fn ref_from_ptr_or_opt(
py: Python<'py>,
ptr: &'a *mut ffi::PyObject,
) -> Option<Self> {
Bound::ref_from_ptr_or_opt(py, ptr).as_ref().map(BoundRef)
}
pub fn downcast<T: PyTypeCheck>(self) -> Result<BoundRef<'a, 'py, T>, DowncastError<'a, 'py>> {
self.0.downcast::<T>().map(BoundRef)
}
pub unsafe fn downcast_unchecked<T>(self) -> BoundRef<'a, 'py, T> {
BoundRef(self.0.downcast_unchecked::<T>())
}
}
impl<'a, 'py, T: PyClass> TryFrom<BoundRef<'a, 'py, T>> for PyRef<'py, T> {
type Error = PyBorrowError;
#[inline]
fn try_from(value: BoundRef<'a, 'py, T>) -> Result<Self, Self::Error> {
value.0.try_borrow()
}
}
impl<'a, 'py, T: PyClass<Frozen = False>> TryFrom<BoundRef<'a, 'py, T>> for PyRefMut<'py, T> {
type Error = PyBorrowMutError;
#[inline]
fn try_from(value: BoundRef<'a, 'py, T>) -> Result<Self, Self::Error> {
value.0.try_borrow_mut()
}
}
impl<'a, 'py, T> From<BoundRef<'a, 'py, T>> for Bound<'py, T> {
#[inline]
fn from(bound: BoundRef<'a, 'py, T>) -> Self {
bound.0.clone()
}
}
impl<'a, 'py, T> From<BoundRef<'a, 'py, T>> for &'a Bound<'py, T> {
#[inline]
fn from(bound: BoundRef<'a, 'py, T>) -> Self {
bound.0
}
}
impl<T> From<BoundRef<'_, '_, T>> for Py<T> {
#[inline]
fn from(bound: BoundRef<'_, '_, T>) -> Self {
bound.0.clone().unbind()
}
}
impl<'py, T> std::ops::Deref for BoundRef<'_, 'py, T> {
type Target = Bound<'py, T>;
#[inline]
fn deref(&self) -> &Self::Target {
self.0
}
}
pub unsafe fn tp_new_impl<T: PyClass>(
py: Python<'_>,
initializer: PyClassInitializer<T>,
target_type: *mut ffi::PyTypeObject,
) -> PyResult<*mut ffi::PyObject> {
initializer
.create_class_object_of_type(py, target_type)
.map(Bound::into_ptr)
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
fn test_fastcall_function_with_keywords() {
use super::PyMethodDef;
use crate::types::{PyAnyMethods, PyCFunction};
use crate::{ffi, Python};
Python::with_gil(|py| {
unsafe extern "C" fn accepts_no_arguments(
_slf: *mut ffi::PyObject,
_args: *const *mut ffi::PyObject,
nargs: ffi::Py_ssize_t,
kwargs: *mut ffi::PyObject,
) -> *mut ffi::PyObject {
assert_eq!(nargs, 0);
assert!(kwargs.is_null());
Python::assume_gil_acquired().None().into_ptr()
}
let f = PyCFunction::internal_new(
py,
&PyMethodDef::fastcall_cfunction_with_keywords(
ffi::c_str!("test"),
accepts_no_arguments,
ffi::c_str!("doc"),
),
None,
)
.unwrap();
f.call0().unwrap();
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/coroutine.rs | use std::{
future::Future,
ops::{Deref, DerefMut},
};
use crate::{
coroutine::{cancel::ThrowCallback, Coroutine},
instance::Bound,
pycell::impl_::PyClassBorrowChecker,
pyclass::boolean_struct::False,
types::{PyAnyMethods, PyString},
IntoPyObject, Py, PyAny, PyClass, PyErr, PyResult, Python,
};
pub fn new_coroutine<'py, F, T, E>(
name: &Bound<'py, PyString>,
qualname_prefix: Option<&'static str>,
throw_callback: Option<ThrowCallback>,
future: F,
) -> Coroutine
where
F: Future<Output = Result<T, E>> + Send + 'static,
T: IntoPyObject<'py>,
E: Into<PyErr>,
{
Coroutine::new(Some(name.clone()), qualname_prefix, throw_callback, future)
}
fn get_ptr<T: PyClass>(obj: &Py<T>) -> *mut T {
obj.get_class_object().get_ptr()
}
pub struct RefGuard<T: PyClass>(Py<T>);
impl<T: PyClass> RefGuard<T> {
pub fn new(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let bound = obj.downcast::<T>()?;
bound.get_class_object().borrow_checker().try_borrow()?;
Ok(RefGuard(bound.clone().unbind()))
}
}
impl<T: PyClass> Deref for RefGuard<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: `RefGuard` has been built from `PyRef` and provides the same guarantees
unsafe { &*get_ptr(&self.0) }
}
}
impl<T: PyClass> Drop for RefGuard<T> {
fn drop(&mut self) {
Python::with_gil(|gil| {
self.0
.bind(gil)
.get_class_object()
.borrow_checker()
.release_borrow()
})
}
}
pub struct RefMutGuard<T: PyClass<Frozen = False>>(Py<T>);
impl<T: PyClass<Frozen = False>> RefMutGuard<T> {
pub fn new(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let bound = obj.downcast::<T>()?;
bound.get_class_object().borrow_checker().try_borrow_mut()?;
Ok(RefMutGuard(bound.clone().unbind()))
}
}
impl<T: PyClass<Frozen = False>> Deref for RefMutGuard<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: `RefMutGuard` has been built from `PyRefMut` and provides the same guarantees
unsafe { &*get_ptr(&self.0) }
}
}
impl<T: PyClass<Frozen = False>> DerefMut for RefMutGuard<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: `RefMutGuard` has been built from `PyRefMut` and provides the same guarantees
unsafe { &mut *get_ptr(&self.0) }
}
}
impl<T: PyClass<Frozen = False>> Drop for RefMutGuard<T> {
fn drop(&mut self) {
Python::with_gil(|gil| {
self.0
.bind(gil)
.get_class_object()
.borrow_checker()
.release_borrow_mut()
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_ | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pyclass/lazy_type_object.rs | use std::{
ffi::CStr,
marker::PhantomData,
thread::{self, ThreadId},
};
use crate::{
exceptions::PyRuntimeError,
ffi,
impl_::pyclass::MaybeRuntimePyMethodDef,
impl_::pymethods::PyMethodDefType,
pyclass::{create_type_object, PyClassTypeObject},
sync::GILOnceCell,
types::PyType,
Bound, PyClass, PyErr, PyObject, PyResult, Python,
};
use std::sync::Mutex;
use super::PyClassItemsIter;
/// Lazy type object for PyClass.
#[doc(hidden)]
pub struct LazyTypeObject<T>(LazyTypeObjectInner, PhantomData<T>);
// Non-generic inner of LazyTypeObject to keep code size down
struct LazyTypeObjectInner {
value: GILOnceCell<PyClassTypeObject>,
// Threads which have begun initialization of the `tp_dict`. Used for
// reentrant initialization detection.
initializing_threads: Mutex<Vec<ThreadId>>,
tp_dict_filled: GILOnceCell<()>,
}
impl<T> LazyTypeObject<T> {
/// Creates an uninitialized `LazyTypeObject`.
#[allow(clippy::new_without_default)]
pub const fn new() -> Self {
LazyTypeObject(
LazyTypeObjectInner {
value: GILOnceCell::new(),
initializing_threads: Mutex::new(Vec::new()),
tp_dict_filled: GILOnceCell::new(),
},
PhantomData,
)
}
}
impl<T: PyClass> LazyTypeObject<T> {
/// Gets the type object contained by this `LazyTypeObject`, initializing it if needed.
pub fn get_or_init<'py>(&self, py: Python<'py>) -> &Bound<'py, PyType> {
self.get_or_try_init(py).unwrap_or_else(|err| {
err.print(py);
panic!("failed to create type object for {}", T::NAME)
})
}
/// Fallible version of the above.
pub(crate) fn get_or_try_init<'py>(&self, py: Python<'py>) -> PyResult<&Bound<'py, PyType>> {
self.0
.get_or_try_init(py, create_type_object::<T>, T::NAME, T::items_iter())
}
}
impl LazyTypeObjectInner {
// Uses dynamically dispatched fn(Python<'py>) -> PyResult<Py<PyType>
// so that this code is only instantiated once, instead of for every T
// like the generic LazyTypeObject<T> methods above.
fn get_or_try_init<'py>(
&self,
py: Python<'py>,
init: fn(Python<'py>) -> PyResult<PyClassTypeObject>,
name: &str,
items_iter: PyClassItemsIter,
) -> PyResult<&Bound<'py, PyType>> {
(|| -> PyResult<_> {
let type_object = self
.value
.get_or_try_init(py, || init(py))?
.type_object
.bind(py);
self.ensure_init(type_object, name, items_iter)?;
Ok(type_object)
})()
.map_err(|err| {
wrap_in_runtime_error(
py,
err,
format!("An error occurred while initializing class {}", name),
)
})
}
fn ensure_init(
&self,
type_object: &Bound<'_, PyType>,
name: &str,
items_iter: PyClassItemsIter,
) -> PyResult<()> {
let py = type_object.py();
// We might want to fill the `tp_dict` with python instances of `T`
// itself. In order to do so, we must first initialize the type object
// with an empty `tp_dict`: now we can create instances of `T`.
//
// Then we fill the `tp_dict`. Multiple threads may try to fill it at
// the same time, but only one of them will succeed.
//
// More importantly, if a thread is performing initialization of the
// `tp_dict`, it can still request the type object through `get_or_init`,
// but the `tp_dict` may appear empty of course.
if self.tp_dict_filled.get(py).is_some() {
// `tp_dict` is already filled: ok.
return Ok(());
}
let thread_id = thread::current().id();
{
let mut threads = self.initializing_threads.lock().unwrap();
if threads.contains(&thread_id) {
// Reentrant call: just return the type object, even if the
// `tp_dict` is not filled yet.
return Ok(());
}
threads.push(thread_id);
}
struct InitializationGuard<'a> {
initializing_threads: &'a Mutex<Vec<ThreadId>>,
thread_id: ThreadId,
}
impl Drop for InitializationGuard<'_> {
fn drop(&mut self) {
let mut threads = self.initializing_threads.lock().unwrap();
threads.retain(|id| *id != self.thread_id);
}
}
let guard = InitializationGuard {
initializing_threads: &self.initializing_threads,
thread_id,
};
// Pre-compute the class attribute objects: this can temporarily
// release the GIL since we're calling into arbitrary user code. It
// means that another thread can continue the initialization in the
// meantime: at worst, we'll just make a useless computation.
let mut items = vec![];
for class_items in items_iter {
for def in class_items.methods {
let built_method;
let method = match def {
MaybeRuntimePyMethodDef::Runtime(builder) => {
built_method = builder();
&built_method
}
MaybeRuntimePyMethodDef::Static(method) => method,
};
if let PyMethodDefType::ClassAttribute(attr) = method {
match (attr.meth)(py) {
Ok(val) => items.push((attr.name, val)),
Err(err) => {
return Err(wrap_in_runtime_error(
py,
err,
format!(
"An error occurred while initializing `{}.{}`",
name,
attr.name.to_str().unwrap()
),
))
}
}
}
}
}
// Now we hold the GIL and we can assume it won't be released until we
// return from the function.
let result = self.tp_dict_filled.get_or_try_init(py, move || {
let result = initialize_tp_dict(py, type_object.as_ptr(), items);
// Initialization successfully complete, can clear the thread list.
// (No further calls to get_or_init() will try to init, on any thread.)
let mut threads = {
drop(guard);
self.initializing_threads.lock().unwrap()
};
threads.clear();
result
});
if let Err(err) = result {
return Err(wrap_in_runtime_error(
py,
err.clone_ref(py),
format!("An error occurred while initializing `{}.__dict__`", name),
));
}
Ok(())
}
}
fn initialize_tp_dict(
py: Python<'_>,
type_object: *mut ffi::PyObject,
items: Vec<(&'static CStr, PyObject)>,
) -> PyResult<()> {
// We hold the GIL: the dictionary update can be considered atomic from
// the POV of other threads.
for (key, val) in items {
crate::err::error_on_minusone(py, unsafe {
ffi::PyObject_SetAttrString(type_object, key.as_ptr(), val.into_ptr())
})?;
}
Ok(())
}
// This is necessary for making static `LazyTypeObject`s
unsafe impl<T> Sync for LazyTypeObject<T> {}
#[cold]
fn wrap_in_runtime_error(py: Python<'_>, err: PyErr, message: String) -> PyErr {
let runtime_err = PyRuntimeError::new_err(message);
runtime_err.set_cause(py, Some(err));
runtime_err
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_ | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pyclass/probes.rs | use std::marker::PhantomData;
use crate::{conversion::IntoPyObject, Py};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
/// Trait used to combine with zero-sized types to calculate at compile time
/// some property of a type.
///
/// The trick uses the fact that an associated constant has higher priority
/// than a trait constant, so we can use the trait to define the false case.
///
/// The true case is defined in the zero-sized type's impl block, which is
/// gated on some property like trait bound or only being implemented
/// for fixed concrete types.
pub trait Probe {
const VALUE: bool = false;
}
macro_rules! probe {
($name:ident) => {
pub struct $name<T>(PhantomData<T>);
impl<T> Probe for $name<T> {}
};
}
probe!(IsPyT);
impl<T> IsPyT<Py<T>> {
pub const VALUE: bool = true;
}
probe!(IsToPyObject);
#[allow(deprecated)]
impl<T: ToPyObject> IsToPyObject<T> {
pub const VALUE: bool = true;
}
probe!(IsIntoPy);
#[allow(deprecated)]
impl<T: IntoPy<crate::PyObject>> IsIntoPy<T> {
pub const VALUE: bool = true;
}
probe!(IsIntoPyObjectRef);
// Possible clippy beta regression,
// see https://github.com/rust-lang/rust-clippy/issues/13578
#[allow(clippy::extra_unused_lifetimes)]
impl<'a, 'py, T: 'a> IsIntoPyObjectRef<T>
where
&'a T: IntoPyObject<'py>,
{
pub const VALUE: bool = true;
}
probe!(IsIntoPyObject);
impl<'py, T> IsIntoPyObject<T>
where
T: IntoPyObject<'py>,
{
pub const VALUE: bool = true;
}
probe!(IsSync);
impl<T: Sync> IsSync<T> {
pub const VALUE: bool = true;
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_ | lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pyclass/assertions.rs | /// Helper function that can be used at compile time to emit a diagnostic if
/// the type does not implement `Sync` when it should.
///
/// The mere act of invoking this function will cause the diagnostic to be
/// emitted if `T` does not implement `Sync` when it should.
///
/// The additional `const IS_SYNC: bool` parameter is used to allow the custom
/// diagnostic to be emitted; if `PyClassSync`
#[allow(unused)]
pub const fn assert_pyclass_sync<T>()
where
T: PyClassSync + Sync,
{
}
#[cfg_attr(
diagnostic_namespace,
diagnostic::on_unimplemented(
message = "the trait `Sync` is not implemented for `{Self}`",
label = "required by `#[pyclass]`",
note = "replace thread-unsafe fields with thread-safe alternatives",
note = "see <TODO INSERT PYO3 GUIDE> for more information",
)
)]
pub trait PyClassSync<T: Sync = Self> {}
impl<T> PyClassSync for T where T: Sync {}
mod tests {
#[cfg(feature = "macros")]
#[test]
fn test_assert_pyclass_sync() {
use super::assert_pyclass_sync;
#[crate::pyclass(crate = "crate")]
struct MyClass {}
assert_pyclass_sync::<MyClass>();
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/eyre.rs | #![cfg(feature = "eyre")]
//! A conversion from
//! [eyre](https://docs.rs/eyre/ "A library for easy idiomatic error handling and reporting in Rust applications.")’s
//! [`Report`] type to [`PyErr`].
//!
//! Use of an error handling library like [eyre] is common in application code and when you just
//! want error handling to be easy. If you are writing a library or you need more control over your
//! errors you might want to design your own error type instead.
//!
//! When the inner error is a [`PyErr`] without source, it will be extracted out.
//! Otherwise a Python [`RuntimeError`] will be created.
//! You might find that you need to map the error from your Rust code into another Python exception.
//! See [`PyErr::new`] for more information about that.
//!
//! For information about error handling in general, see the [Error handling] chapter of the Rust
//! book.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! ## change * to the version you want to use, ideally the latest.
//! eyre = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"eyre\"] }")]
//! ```
//!
//! Note that you must use compatible versions of eyre and PyO3.
//! The required eyre version may vary based on the version of PyO3.
//!
//! # Example: Propagating a `PyErr` into [`eyre::Report`]
//!
//! ```rust
//! use pyo3::prelude::*;
//! use std::path::PathBuf;
//!
//! // A wrapper around a Rust function.
//! // The pyfunction macro performs the conversion to a PyErr
//! #[pyfunction]
//! fn py_open(filename: PathBuf) -> eyre::Result<Vec<u8>> {
//! let data = std::fs::read(filename)?;
//! Ok(data)
//! }
//!
//! fn main() {
//! let error = Python::with_gil(|py| -> PyResult<Vec<u8>> {
//! let fun = wrap_pyfunction!(py_open, py)?;
//! let text = fun.call1(("foo.txt",))?.extract::<Vec<u8>>()?;
//! Ok(text)
//! }).unwrap_err();
//!
//! println!("{}", error);
//! }
//! ```
//!
//! # Example: Using `eyre` in general
//!
//! Note that you don't need this feature to convert a [`PyErr`] into an [`eyre::Report`], because
//! it can already convert anything that implements [`Error`](std::error::Error):
//!
//! ```rust
//! use pyo3::prelude::*;
//! use pyo3::types::PyBytes;
//!
//! // An example function that must handle multiple error types.
//! //
//! // To do this you usually need to design your own error type or use
//! // `Box<dyn Error>`. `eyre` is a convenient alternative for this.
//! pub fn decompress(bytes: &[u8]) -> eyre::Result<String> {
//! // An arbitrary example of a Python api you
//! // could call inside an application...
//! // This might return a `PyErr`.
//! let res = Python::with_gil(|py| {
//! let zlib = PyModule::import(py, "zlib")?;
//! let decompress = zlib.getattr("decompress")?;
//! let bytes = PyBytes::new(py, bytes);
//! let value = decompress.call1((bytes,))?;
//! value.extract::<Vec<u8>>()
//! })?;
//!
//! // This might be a `FromUtf8Error`.
//! let text = String::from_utf8(res)?;
//!
//! Ok(text)
//! }
//!
//! fn main() -> eyre::Result<()> {
//! let bytes: &[u8] = b"x\x9c\x8b\xcc/U(\xce\xc8/\xcdIQ((\xcaOJL\xca\xa9T\
//! (-NU(\xc9HU\xc8\xc9LJ\xcbI,IUH.\x02\x91\x99y\xc5%\
//! \xa9\x89)z\x00\xf2\x15\x12\xfe";
//! let text = decompress(bytes)?;
//!
//! println!("The text is \"{}\"", text);
//! # assert_eq!(text, "You should probably use the libflate crate instead.");
//! Ok(())
//! }
//! ```
//!
//! [eyre]: https://docs.rs/eyre/ "A library for easy idiomatic error handling and reporting in Rust applications."
//! [`RuntimeError`]: https://docs.python.org/3/library/exceptions.html#RuntimeError "Built-in Exceptions — Python documentation"
//! [Error handling]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html "Recoverable Errors with Result - The Rust Programming Language"
use crate::exceptions::PyRuntimeError;
use crate::PyErr;
use eyre::Report;
/// Converts [`eyre::Report`] to a [`PyErr`] containing a [`PyRuntimeError`].
///
/// If you want to raise a different Python exception you will have to do so manually. See
/// [`PyErr::new`] for more information about that.
impl From<eyre::Report> for PyErr {
fn from(mut error: Report) -> Self {
// Errors containing a PyErr without chain or context are returned as the underlying error
if error.source().is_none() {
error = match error.downcast::<Self>() {
Ok(py_err) => return py_err,
Err(error) => error,
};
}
PyRuntimeError::new_err(format!("{:?}", error))
}
}
#[cfg(test)]
mod tests {
use crate::exceptions::{PyRuntimeError, PyValueError};
use crate::types::IntoPyDict;
use crate::{ffi, prelude::*};
use eyre::{bail, eyre, Report, Result, WrapErr};
fn f() -> Result<()> {
use std::io;
bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!"));
}
fn g() -> Result<()> {
f().wrap_err("f failed")
}
fn h() -> Result<()> {
g().wrap_err("g failed")
}
#[test]
fn test_pyo3_exception_contents() {
let err = h().unwrap_err();
let expected_contents = format!("{:?}", err);
let pyerr = PyErr::from(err);
Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).unwrap();
let pyerr = py
.run(ffi::c_str!("raise err"), None, Some(&locals))
.unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents);
})
}
fn k() -> Result<()> {
Err(eyre!("Some sort of error"))
}
#[test]
fn test_pyo3_exception_contents2() {
let err = k().unwrap_err();
let expected_contents = format!("{:?}", err);
let pyerr = PyErr::from(err);
Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).unwrap();
let pyerr = py
.run(ffi::c_str!("raise err"), None, Some(&locals))
.unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents);
})
}
#[test]
fn test_pyo3_unwrap_simple_err() {
let origin_exc = PyValueError::new_err("Value Error");
let report: Report = origin_exc.into();
let converted: PyErr = report.into();
assert!(Python::with_gil(
|py| converted.is_instance_of::<PyValueError>(py)
))
}
#[test]
fn test_pyo3_unwrap_complex_err() {
let origin_exc = PyValueError::new_err("Value Error");
let mut report: Report = origin_exc.into();
report = report.wrap_err("Wrapped");
let converted: PyErr = report.into();
assert!(Python::with_gil(
|py| converted.is_instance_of::<PyRuntimeError>(py)
))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/serde.rs | #![cfg(feature = "serde")]
//! Enables (de)serialization of [`Py`]`<T>` objects via [serde](https://docs.rs/serde).
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"serde\"] }")]
//! serde = "1.0"
//! ```
use crate::{Py, PyAny, PyClass, Python};
use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};
impl<T> Serialize for Py<T>
where
T: Serialize + PyClass,
{
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
Python::with_gil(|py| {
self.try_borrow(py)
.map_err(|e| ser::Error::custom(e.to_string()))?
.serialize(serializer)
})
}
}
impl<'de, T> Deserialize<'de> for Py<T>
where
T: PyClass<BaseType = PyAny> + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Py<T>, D::Error>
where
D: Deserializer<'de>,
{
let deserialized = T::deserialize(deserializer)?;
Python::with_gil(|py| {
Py::new(py, deserialized).map_err(|e| de::Error::custom(e.to_string()))
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/either.rs | #![cfg(feature = "either")]
//! Conversion to/from
//! [either](https://docs.rs/either/ "A library for easy idiomatic error handling and reporting in Rust applications")’s
//! [`Either`] type to a union of two Python types.
//!
//! Use of a generic sum type like [either] is common when you want to either accept one of two possible
//! types as an argument or return one of two possible types from a function, without having to define
//! a helper type manually yourself.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! ## change * to the version you want to use, ideally the latest.
//! either = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"either\"] }")]
//! ```
//!
//! Note that you must use compatible versions of either and PyO3.
//! The required either version may vary based on the version of PyO3.
//!
//! # Example: Convert a `int | str` to `Either<i32, String>`.
//!
//! ```rust
//! use either::Either;
//! use pyo3::{Python, PyResult, IntoPyObject, types::PyAnyMethods};
//!
//! fn main() -> PyResult<()> {
//! pyo3::prepare_freethreaded_python();
//! Python::with_gil(|py| {
//! // Create a string and an int in Python.
//! let py_str = "crab".into_pyobject(py)?;
//! let py_int = 42i32.into_pyobject(py)?;
//! // Now convert it to an Either<i32, String>.
//! let either_str: Either<i32, String> = py_str.extract()?;
//! let either_int: Either<i32, String> = py_int.extract()?;
//! Ok(())
//! })
//! }
//! ```
//!
//! [either](https://docs.rs/either/ "A library for easy idiomatic error handling and reporting in Rust applications")’s
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::{
conversion::IntoPyObject, exceptions::PyTypeError, types::any::PyAnyMethods, Bound,
BoundObject, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use either::Either;
#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
#[allow(deprecated)]
impl<L, R> IntoPy<PyObject> for Either<L, R>
where
L: IntoPy<PyObject>,
R: IntoPy<PyObject>,
{
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
match self {
Either::Left(l) => l.into_py(py),
Either::Right(r) => r.into_py(py),
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
impl<'py, L, R> IntoPyObject<'py> for Either<L, R>
where
L: IntoPyObject<'py>,
R: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
match self {
Either::Left(l) => l
.into_pyobject(py)
.map(BoundObject::into_any)
.map(BoundObject::into_bound)
.map_err(Into::into),
Either::Right(r) => r
.into_pyobject(py)
.map(BoundObject::into_any)
.map(BoundObject::into_bound)
.map_err(Into::into),
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
impl<'a, 'py, L, R> IntoPyObject<'py> for &'a Either<L, R>
where
&'a L: IntoPyObject<'py>,
&'a R: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
match self {
Either::Left(l) => l
.into_pyobject(py)
.map(BoundObject::into_any)
.map(BoundObject::into_bound)
.map_err(Into::into),
Either::Right(r) => r
.into_pyobject(py)
.map(BoundObject::into_any)
.map(BoundObject::into_bound)
.map_err(Into::into),
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
#[allow(deprecated)]
impl<L, R> ToPyObject for Either<L, R>
where
L: ToPyObject,
R: ToPyObject,
{
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
match self {
Either::Left(l) => l.to_object(py),
Either::Right(r) => r.to_object(py),
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "either")))]
impl<'py, L, R> FromPyObject<'py> for Either<L, R>
where
L: FromPyObject<'py>,
R: FromPyObject<'py>,
{
#[inline]
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
if let Ok(l) = obj.extract::<L>() {
Ok(Either::Left(l))
} else if let Ok(r) = obj.extract::<R>() {
Ok(Either::Right(r))
} else {
// TODO: it might be nice to use the `type_input()` name here once `type_input`
// is not experimental, rather than the Rust type names.
let err_msg = format!(
"failed to convert the value to 'Union[{}, {}]'",
std::any::type_name::<L>(),
std::any::type_name::<R>()
);
Err(PyTypeError::new_err(err_msg))
}
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::union_of(&[L::type_input(), R::type_input()])
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use crate::exceptions::PyTypeError;
use crate::{IntoPyObject, Python};
use crate::types::PyAnyMethods;
use either::Either;
#[test]
fn test_either_conversion() {
type E = Either<i32, String>;
type E1 = Either<i32, f32>;
type E2 = Either<f32, i32>;
Python::with_gil(|py| {
let l = E::Left(42);
let obj_l = (&l).into_pyobject(py).unwrap();
assert_eq!(obj_l.extract::<i32>().unwrap(), 42);
assert_eq!(obj_l.extract::<E>().unwrap(), l);
let r = E::Right("foo".to_owned());
let obj_r = (&r).into_pyobject(py).unwrap();
assert_eq!(obj_r.extract::<Cow<'_, str>>().unwrap(), "foo");
assert_eq!(obj_r.extract::<E>().unwrap(), r);
let obj_s = "foo".into_pyobject(py).unwrap();
let err = obj_s.extract::<E1>().unwrap_err();
assert!(err.is_instance_of::<PyTypeError>(py));
assert_eq!(
err.to_string(),
"TypeError: failed to convert the value to 'Union[i32, f32]'"
);
let obj_i = 42i32.into_pyobject(py).unwrap();
assert_eq!(obj_i.extract::<E1>().unwrap(), E1::Left(42));
assert_eq!(obj_i.extract::<E2>().unwrap(), E2::Left(42.0));
let obj_f = 42.0f64.into_pyobject(py).unwrap();
assert_eq!(obj_f.extract::<E1>().unwrap(), E1::Right(42.0));
assert_eq!(obj_f.extract::<E2>().unwrap(), E2::Left(42.0));
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/anyhow.rs | #![cfg(feature = "anyhow")]
//! A conversion from [anyhow]’s [`Error`][anyhow-error] type to [`PyErr`].
//!
//! Use of an error handling library like [anyhow] is common in application code and when you just
//! want error handling to be easy. If you are writing a library or you need more control over your
//! errors you might want to design your own error type instead.
//!
//! When the inner error is a [`PyErr`] without source, it will be extracted out.
//! Otherwise a Python [`RuntimeError`] will be created.
//! You might find that you need to map the error from your Rust code into another Python exception.
//! See [`PyErr::new`] for more information about that.
//!
//! For information about error handling in general, see the [Error handling] chapter of the Rust
//! book.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! ## change * to the version you want to use, ideally the latest.
//! anyhow = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"anyhow\"] }")]
//! ```
//!
//! Note that you must use compatible versions of anyhow and PyO3.
//! The required anyhow version may vary based on the version of PyO3.
//!
//! # Example: Propagating a `PyErr` into [`anyhow::Error`]
//!
//! ```rust
//! use pyo3::prelude::*;
//! use std::path::PathBuf;
//!
//! // A wrapper around a Rust function.
//! // The pyfunction macro performs the conversion to a PyErr
//! #[pyfunction]
//! fn py_open(filename: PathBuf) -> anyhow::Result<Vec<u8>> {
//! let data = std::fs::read(filename)?;
//! Ok(data)
//! }
//!
//! fn main() {
//! let error = Python::with_gil(|py| -> PyResult<Vec<u8>> {
//! let fun = wrap_pyfunction!(py_open, py)?;
//! let text = fun.call1(("foo.txt",))?.extract::<Vec<u8>>()?;
//! Ok(text)
//! }).unwrap_err();
//!
//! println!("{}", error);
//! }
//! ```
//!
//! # Example: Using `anyhow` in general
//!
//! Note that you don't need this feature to convert a [`PyErr`] into an [`anyhow::Error`], because
//! it can already convert anything that implements [`Error`](std::error::Error):
//!
//! ```rust
//! use pyo3::prelude::*;
//! use pyo3::types::PyBytes;
//!
//! // An example function that must handle multiple error types.
//! //
//! // To do this you usually need to design your own error type or use
//! // `Box<dyn Error>`. `anyhow` is a convenient alternative for this.
//! pub fn decompress(bytes: &[u8]) -> anyhow::Result<String> {
//! // An arbitrary example of a Python api you
//! // could call inside an application...
//! // This might return a `PyErr`.
//! let res = Python::with_gil(|py| {
//! let zlib = PyModule::import(py, "zlib")?;
//! let decompress = zlib.getattr("decompress")?;
//! let bytes = PyBytes::new(py, bytes);
//! let value = decompress.call1((bytes,))?;
//! value.extract::<Vec<u8>>()
//! })?;
//!
//! // This might be a `FromUtf8Error`.
//! let text = String::from_utf8(res)?;
//!
//! Ok(text)
//! }
//!
//! fn main() -> anyhow::Result<()> {
//! let bytes: &[u8] = b"x\x9c\x8b\xcc/U(\xce\xc8/\xcdIQ((\xcaOJL\xca\xa9T\
//! (-NU(\xc9HU\xc8\xc9LJ\xcbI,IUH.\x02\x91\x99y\xc5%\
//! \xa9\x89)z\x00\xf2\x15\x12\xfe";
//! let text = decompress(bytes)?;
//!
//! println!("The text is \"{}\"", text);
//! # assert_eq!(text, "You should probably use the libflate crate instead.");
//! Ok(())
//! }
//! ```
//!
//! [anyhow]: https://docs.rs/anyhow/ "A trait object based error system for easy idiomatic error handling in Rust applications."
//! [anyhow-error]: https://docs.rs/anyhow/latest/anyhow/struct.Error.html "Anyhows `Error` type, a wrapper around a dynamic error type"
//! [`RuntimeError`]: https://docs.python.org/3/library/exceptions.html#RuntimeError "Built-in Exceptions — Python documentation"
//! [Error handling]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html "Recoverable Errors with Result - The Rust Programming Language"
use crate::exceptions::PyRuntimeError;
use crate::PyErr;
impl From<anyhow::Error> for PyErr {
fn from(mut error: anyhow::Error) -> Self {
// Errors containing a PyErr without chain or context are returned as the underlying error
if error.source().is_none() {
error = match error.downcast::<Self>() {
Ok(py_err) => return py_err,
Err(error) => error,
};
}
PyRuntimeError::new_err(format!("{:?}", error))
}
}
#[cfg(test)]
mod test_anyhow {
use crate::exceptions::{PyRuntimeError, PyValueError};
use crate::types::IntoPyDict;
use crate::{ffi, prelude::*};
use anyhow::{anyhow, bail, Context, Result};
fn f() -> Result<()> {
use std::io;
bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!"));
}
fn g() -> Result<()> {
f().context("f failed")
}
fn h() -> Result<()> {
g().context("g failed")
}
#[test]
fn test_pyo3_exception_contents() {
let err = h().unwrap_err();
let expected_contents = format!("{:?}", err);
let pyerr = PyErr::from(err);
Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).unwrap();
let pyerr = py
.run(ffi::c_str!("raise err"), None, Some(&locals))
.unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents);
})
}
fn k() -> Result<()> {
Err(anyhow!("Some sort of error"))
}
#[test]
fn test_pyo3_exception_contents2() {
let err = k().unwrap_err();
let expected_contents = format!("{:?}", err);
let pyerr = PyErr::from(err);
Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).unwrap();
let pyerr = py
.run(ffi::c_str!("raise err"), None, Some(&locals))
.unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents);
})
}
#[test]
fn test_pyo3_unwrap_simple_err() {
let origin_exc = PyValueError::new_err("Value Error");
let err: anyhow::Error = origin_exc.into();
let converted: PyErr = err.into();
assert!(Python::with_gil(
|py| converted.is_instance_of::<PyValueError>(py)
))
}
#[test]
fn test_pyo3_unwrap_complex_err() {
let origin_exc = PyValueError::new_err("Value Error");
let mut err: anyhow::Error = origin_exc.into();
err = err.context("Context");
let converted: PyErr = err.into();
assert!(Python::with_gil(
|py| converted.is_instance_of::<PyRuntimeError>(py)
))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/chrono.rs | #![cfg(feature = "chrono")]
//! Conversions to and from [chrono](https://docs.rs/chrono/)’s `Duration`,
//! `NaiveDate`, `NaiveTime`, `DateTime<Tz>`, `FixedOffset`, and `Utc`.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! chrono = "0.4"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"chrono\"] }")]
//! ```
//!
//! Note that you must use compatible versions of chrono and PyO3.
//! The required chrono version may vary based on the version of PyO3.
//!
//! # Example: Convert a `datetime.datetime` to chrono's `DateTime<Utc>`
//!
//! ```rust
//! use chrono::{DateTime, Duration, TimeZone, Utc};
//! use pyo3::{Python, PyResult, IntoPyObject, types::PyAnyMethods};
//!
//! fn main() -> PyResult<()> {
//! pyo3::prepare_freethreaded_python();
//! Python::with_gil(|py| {
//! // Build some chrono values
//! let chrono_datetime = Utc.with_ymd_and_hms(2022, 1, 1, 12, 0, 0).unwrap();
//! let chrono_duration = Duration::seconds(1);
//! // Convert them to Python
//! let py_datetime = chrono_datetime.into_pyobject(py)?;
//! let py_timedelta = chrono_duration.into_pyobject(py)?;
//! // Do an operation in Python
//! let py_sum = py_datetime.call_method1("__add__", (py_timedelta,))?;
//! // Convert back to Rust
//! let chrono_sum: DateTime<Utc> = py_sum.extract()?;
//! println!("DateTime<Utc>: {}", chrono_datetime);
//! Ok(())
//! })
//! }
//! ```
use crate::conversion::IntoPyObject;
use crate::exceptions::{PyTypeError, PyUserWarning, PyValueError};
#[cfg(Py_LIMITED_API)]
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
#[cfg(not(Py_LIMITED_API))]
use crate::types::datetime::timezone_from_offset;
use crate::types::PyNone;
#[cfg(not(Py_LIMITED_API))]
use crate::types::{
timezone_utc, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyTime, PyTimeAccess,
PyTzInfo, PyTzInfoAccess,
};
use crate::{ffi, Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python};
#[cfg(Py_LIMITED_API)]
use crate::{intern, DowncastError};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use chrono::offset::{FixedOffset, Utc};
use chrono::{
DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Offset, TimeZone, Timelike,
};
#[allow(deprecated)]
impl ToPyObject for Duration {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Duration {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Duration {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDelta;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
// Total number of days
let days = self.num_days();
// Remainder of seconds
let secs_dur = self - Duration::days(days);
let secs = secs_dur.num_seconds();
// Fractional part of the microseconds
let micros = (secs_dur - Duration::seconds(secs_dur.num_seconds()))
.num_microseconds()
// This should never panic since we are just getting the fractional
// part of the total microseconds, which should never overflow.
.unwrap();
#[cfg(not(Py_LIMITED_API))]
{
// We do not need to check the days i64 to i32 cast from rust because
// python will panic with OverflowError.
// We pass true as the `normalize` parameter since we'd need to do several checks here to
// avoid that, and it shouldn't have a big performance impact.
// The seconds and microseconds cast should never overflow since it's at most the number of seconds per day
PyDelta::new(
py,
days.try_into().unwrap_or(i32::MAX),
secs.try_into()?,
micros.try_into()?,
true,
)
}
#[cfg(Py_LIMITED_API)]
{
DatetimeTypes::try_get(py)
.and_then(|dt| dt.timedelta.bind(py).call1((days, secs, micros)))
}
}
}
impl<'py> IntoPyObject<'py> for &Duration {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDelta;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for Duration {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Duration> {
// Python size are much lower than rust size so we do not need bound checks.
// 0 <= microseconds < 1000000
// 0 <= seconds < 3600*24
// -999999999 <= days <= 999999999
#[cfg(not(Py_LIMITED_API))]
let (days, seconds, microseconds) = {
let delta = ob.downcast::<PyDelta>()?;
(
delta.get_days().into(),
delta.get_seconds().into(),
delta.get_microseconds().into(),
)
};
#[cfg(Py_LIMITED_API)]
let (days, seconds, microseconds) = {
check_type(ob, &DatetimeTypes::get(ob.py()).timedelta, "PyDelta")?;
(
ob.getattr(intern!(ob.py(), "days"))?.extract()?,
ob.getattr(intern!(ob.py(), "seconds"))?.extract()?,
ob.getattr(intern!(ob.py(), "microseconds"))?.extract()?,
)
};
Ok(
Duration::days(days)
+ Duration::seconds(seconds)
+ Duration::microseconds(microseconds),
)
}
}
#[allow(deprecated)]
impl ToPyObject for NaiveDate {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for NaiveDate {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for NaiveDate {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDate;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let DateArgs { year, month, day } = (&self).into();
#[cfg(not(Py_LIMITED_API))]
{
PyDate::new(py, year, month, day)
}
#[cfg(Py_LIMITED_API)]
{
DatetimeTypes::try_get(py).and_then(|dt| dt.date.bind(py).call1((year, month, day)))
}
}
}
impl<'py> IntoPyObject<'py> for &NaiveDate {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDate;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for NaiveDate {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<NaiveDate> {
#[cfg(not(Py_LIMITED_API))]
{
let date = ob.downcast::<PyDate>()?;
py_date_to_naive_date(date)
}
#[cfg(Py_LIMITED_API)]
{
check_type(ob, &DatetimeTypes::get(ob.py()).date, "PyDate")?;
py_date_to_naive_date(ob)
}
}
}
#[allow(deprecated)]
impl ToPyObject for NaiveTime {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for NaiveTime {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for NaiveTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&self).into();
#[cfg(not(Py_LIMITED_API))]
let time = PyTime::new(py, hour, min, sec, micro, None)?;
#[cfg(Py_LIMITED_API)]
let time = DatetimeTypes::try_get(py)
.and_then(|dt| dt.time.bind(py).call1((hour, min, sec, micro)))?;
if truncated_leap_second {
warn_truncated_leap_second(&time);
}
Ok(time)
}
}
impl<'py> IntoPyObject<'py> for &NaiveTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for NaiveTime {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<NaiveTime> {
#[cfg(not(Py_LIMITED_API))]
{
let time = ob.downcast::<PyTime>()?;
py_time_to_naive_time(time)
}
#[cfg(Py_LIMITED_API)]
{
check_type(ob, &DatetimeTypes::get(ob.py()).time, "PyTime")?;
py_time_to_naive_time(ob)
}
}
}
#[allow(deprecated)]
impl ToPyObject for NaiveDateTime {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for NaiveDateTime {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for NaiveDateTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let DateArgs { year, month, day } = (&self.date()).into();
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&self.time()).into();
#[cfg(not(Py_LIMITED_API))]
let datetime = PyDateTime::new(py, year, month, day, hour, min, sec, micro, None)?;
#[cfg(Py_LIMITED_API)]
let datetime = DatetimeTypes::try_get(py).and_then(|dt| {
dt.datetime
.bind(py)
.call1((year, month, day, hour, min, sec, micro))
})?;
if truncated_leap_second {
warn_truncated_leap_second(&datetime);
}
Ok(datetime)
}
}
impl<'py> IntoPyObject<'py> for &NaiveDateTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for NaiveDateTime {
fn extract_bound(dt: &Bound<'_, PyAny>) -> PyResult<NaiveDateTime> {
#[cfg(not(Py_LIMITED_API))]
let dt = dt.downcast::<PyDateTime>()?;
#[cfg(Py_LIMITED_API)]
check_type(dt, &DatetimeTypes::get(dt.py()).datetime, "PyDateTime")?;
// If the user tries to convert a timezone aware datetime into a naive one,
// we return a hard error. We could silently remove tzinfo, or assume local timezone
// and do a conversion, but better leave this decision to the user of the library.
#[cfg(not(Py_LIMITED_API))]
let has_tzinfo = dt.get_tzinfo().is_some();
#[cfg(Py_LIMITED_API)]
let has_tzinfo = !dt.getattr(intern!(dt.py(), "tzinfo"))?.is_none();
if has_tzinfo {
return Err(PyTypeError::new_err("expected a datetime without tzinfo"));
}
let dt = NaiveDateTime::new(py_date_to_naive_date(dt)?, py_time_to_naive_time(dt)?);
Ok(dt)
}
}
#[allow(deprecated)]
impl<Tz: TimeZone> ToPyObject for DateTime<Tz> {
fn to_object(&self, py: Python<'_>) -> PyObject {
// FIXME: convert to better timezone representation here than just convert to fixed offset
// See https://github.com/PyO3/pyo3/issues/3266
let tz = self.offset().fix().to_object(py);
let tz = tz.bind(py).downcast().unwrap();
naive_datetime_to_py_datetime(py, &self.naive_local(), Some(tz))
}
}
#[allow(deprecated)]
impl<Tz: TimeZone> IntoPy<PyObject> for DateTime<Tz> {
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py, Tz: TimeZone> IntoPyObject<'py> for DateTime<Tz> {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(&self).into_pyobject(py)
}
}
impl<'py, Tz: TimeZone> IntoPyObject<'py> for &DateTime<Tz> {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let tz = self.offset().fix().into_pyobject(py)?;
let DateArgs { year, month, day } = (&self.naive_local().date()).into();
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&self.naive_local().time()).into();
#[cfg(not(Py_LIMITED_API))]
let datetime = PyDateTime::new(py, year, month, day, hour, min, sec, micro, Some(&tz))?;
#[cfg(Py_LIMITED_API)]
let datetime = DatetimeTypes::try_get(py).and_then(|dt| {
dt.datetime
.bind(py)
.call1((year, month, day, hour, min, sec, micro, tz))
})?;
if truncated_leap_second {
warn_truncated_leap_second(&datetime);
}
Ok(datetime)
}
}
impl<Tz: TimeZone + for<'py> FromPyObject<'py>> FromPyObject<'_> for DateTime<Tz> {
fn extract_bound(dt: &Bound<'_, PyAny>) -> PyResult<DateTime<Tz>> {
#[cfg(not(Py_LIMITED_API))]
let dt = dt.downcast::<PyDateTime>()?;
#[cfg(Py_LIMITED_API)]
check_type(dt, &DatetimeTypes::get(dt.py()).datetime, "PyDateTime")?;
#[cfg(not(Py_LIMITED_API))]
let tzinfo = dt.get_tzinfo();
#[cfg(Py_LIMITED_API)]
let tzinfo: Option<Bound<'_, PyAny>> = dt.getattr(intern!(dt.py(), "tzinfo"))?.extract()?;
let tz = if let Some(tzinfo) = tzinfo {
tzinfo.extract()?
} else {
return Err(PyTypeError::new_err(
"expected a datetime with non-None tzinfo",
));
};
let naive_dt = NaiveDateTime::new(py_date_to_naive_date(dt)?, py_time_to_naive_time(dt)?);
naive_dt.and_local_timezone(tz).single().ok_or_else(|| {
PyValueError::new_err(format!(
"The datetime {:?} contains an incompatible or ambiguous timezone",
dt
))
})
}
}
#[allow(deprecated)]
impl ToPyObject for FixedOffset {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for FixedOffset {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for FixedOffset {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let seconds_offset = self.local_minus_utc();
#[cfg(not(Py_LIMITED_API))]
{
let td = PyDelta::new(py, 0, seconds_offset, 0, true)?;
timezone_from_offset(&td)
}
#[cfg(Py_LIMITED_API)]
{
let td = Duration::seconds(seconds_offset.into()).into_pyobject(py)?;
DatetimeTypes::try_get(py).and_then(|dt| dt.timezone.bind(py).call1((td,)))
}
}
}
impl<'py> IntoPyObject<'py> for &FixedOffset {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for FixedOffset {
/// Convert python tzinfo to rust [`FixedOffset`].
///
/// Note that the conversion will result in precision lost in microseconds as chrono offset
/// does not supports microseconds.
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<FixedOffset> {
#[cfg(not(Py_LIMITED_API))]
let ob = ob.downcast::<PyTzInfo>()?;
#[cfg(Py_LIMITED_API)]
check_type(ob, &DatetimeTypes::get(ob.py()).tzinfo, "PyTzInfo")?;
// Passing Python's None to the `utcoffset` function will only
// work for timezones defined as fixed offsets in Python.
// Any other timezone would require a datetime as the parameter, and return
// None if the datetime is not provided.
// Trying to convert None to a PyDelta in the next line will then fail.
let py_timedelta = ob.call_method1("utcoffset", (PyNone::get(ob.py()),))?;
if py_timedelta.is_none() {
return Err(PyTypeError::new_err(format!(
"{:?} is not a fixed offset timezone",
ob
)));
}
let total_seconds: Duration = py_timedelta.extract()?;
// This cast is safe since the timedelta is limited to -24 hours and 24 hours.
let total_seconds = total_seconds.num_seconds() as i32;
FixedOffset::east_opt(total_seconds)
.ok_or_else(|| PyValueError::new_err("fixed offset out of bounds"))
}
}
#[allow(deprecated)]
impl ToPyObject for Utc {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Utc {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Utc {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
#[cfg(Py_LIMITED_API)]
{
Ok(timezone_utc(py).into_any())
}
#[cfg(not(Py_LIMITED_API))]
{
Ok(timezone_utc(py))
}
}
}
impl<'py> IntoPyObject<'py> for &Utc {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for Utc {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Utc> {
let py_utc = timezone_utc(ob.py());
if ob.eq(py_utc)? {
Ok(Utc)
} else {
Err(PyValueError::new_err("expected datetime.timezone.utc"))
}
}
}
struct DateArgs {
year: i32,
month: u8,
day: u8,
}
impl From<&NaiveDate> for DateArgs {
fn from(value: &NaiveDate) -> Self {
Self {
year: value.year(),
month: value.month() as u8,
day: value.day() as u8,
}
}
}
struct TimeArgs {
hour: u8,
min: u8,
sec: u8,
micro: u32,
truncated_leap_second: bool,
}
impl From<&NaiveTime> for TimeArgs {
fn from(value: &NaiveTime) -> Self {
let ns = value.nanosecond();
let checked_sub = ns.checked_sub(1_000_000_000);
let truncated_leap_second = checked_sub.is_some();
let micro = checked_sub.unwrap_or(ns) / 1000;
Self {
hour: value.hour() as u8,
min: value.minute() as u8,
sec: value.second() as u8,
micro,
truncated_leap_second,
}
}
}
fn naive_datetime_to_py_datetime(
py: Python<'_>,
naive_datetime: &NaiveDateTime,
#[cfg(not(Py_LIMITED_API))] tzinfo: Option<&Bound<'_, PyTzInfo>>,
#[cfg(Py_LIMITED_API)] tzinfo: Option<&Bound<'_, PyAny>>,
) -> PyObject {
let DateArgs { year, month, day } = (&naive_datetime.date()).into();
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&naive_datetime.time()).into();
#[cfg(not(Py_LIMITED_API))]
let datetime = PyDateTime::new(py, year, month, day, hour, min, sec, micro, tzinfo)
.expect("failed to construct datetime");
#[cfg(Py_LIMITED_API)]
let datetime = DatetimeTypes::get(py)
.datetime
.bind(py)
.call1((year, month, day, hour, min, sec, micro, tzinfo))
.expect("failed to construct datetime.datetime");
if truncated_leap_second {
warn_truncated_leap_second(&datetime);
}
datetime.into()
}
fn warn_truncated_leap_second(obj: &Bound<'_, PyAny>) {
let py = obj.py();
if let Err(e) = PyErr::warn(
py,
&py.get_type::<PyUserWarning>(),
ffi::c_str!("ignored leap-second, `datetime` does not support leap-seconds"),
0,
) {
e.write_unraisable(py, Some(obj))
};
}
#[cfg(not(Py_LIMITED_API))]
fn py_date_to_naive_date(py_date: &impl PyDateAccess) -> PyResult<NaiveDate> {
NaiveDate::from_ymd_opt(
py_date.get_year(),
py_date.get_month().into(),
py_date.get_day().into(),
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range date"))
}
#[cfg(Py_LIMITED_API)]
fn py_date_to_naive_date(py_date: &Bound<'_, PyAny>) -> PyResult<NaiveDate> {
NaiveDate::from_ymd_opt(
py_date.getattr(intern!(py_date.py(), "year"))?.extract()?,
py_date.getattr(intern!(py_date.py(), "month"))?.extract()?,
py_date.getattr(intern!(py_date.py(), "day"))?.extract()?,
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range date"))
}
#[cfg(not(Py_LIMITED_API))]
fn py_time_to_naive_time(py_time: &impl PyTimeAccess) -> PyResult<NaiveTime> {
NaiveTime::from_hms_micro_opt(
py_time.get_hour().into(),
py_time.get_minute().into(),
py_time.get_second().into(),
py_time.get_microsecond(),
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range time"))
}
#[cfg(Py_LIMITED_API)]
fn py_time_to_naive_time(py_time: &Bound<'_, PyAny>) -> PyResult<NaiveTime> {
NaiveTime::from_hms_micro_opt(
py_time.getattr(intern!(py_time.py(), "hour"))?.extract()?,
py_time
.getattr(intern!(py_time.py(), "minute"))?
.extract()?,
py_time
.getattr(intern!(py_time.py(), "second"))?
.extract()?,
py_time
.getattr(intern!(py_time.py(), "microsecond"))?
.extract()?,
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range time"))
}
#[cfg(Py_LIMITED_API)]
fn check_type(value: &Bound<'_, PyAny>, t: &PyObject, type_name: &'static str) -> PyResult<()> {
if !value.is_instance(t.bind(value.py()))? {
return Err(DowncastError::new(value, type_name).into());
}
Ok(())
}
#[cfg(Py_LIMITED_API)]
struct DatetimeTypes {
date: PyObject,
datetime: PyObject,
time: PyObject,
timedelta: PyObject,
timezone: PyObject,
timezone_utc: PyObject,
tzinfo: PyObject,
}
#[cfg(Py_LIMITED_API)]
impl DatetimeTypes {
fn get(py: Python<'_>) -> &Self {
Self::try_get(py).expect("failed to load datetime module")
}
fn try_get(py: Python<'_>) -> PyResult<&Self> {
static TYPES: GILOnceCell<DatetimeTypes> = GILOnceCell::new();
TYPES.get_or_try_init(py, || {
let datetime = py.import("datetime")?;
let timezone = datetime.getattr("timezone")?;
Ok::<_, PyErr>(Self {
date: datetime.getattr("date")?.into(),
datetime: datetime.getattr("datetime")?.into(),
time: datetime.getattr("time")?.into(),
timedelta: datetime.getattr("timedelta")?.into(),
timezone_utc: timezone.getattr("utc")?.into(),
timezone: timezone.into(),
tzinfo: datetime.getattr("tzinfo")?.into(),
})
})
}
}
#[cfg(Py_LIMITED_API)]
fn timezone_utc(py: Python<'_>) -> Bound<'_, PyAny> {
DatetimeTypes::get(py).timezone_utc.bind(py).clone()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{types::PyTuple, BoundObject};
use std::{cmp::Ordering, panic};
#[test]
// Only Python>=3.9 has the zoneinfo package
// We skip the test on windows too since we'd need to install
// tzdata there to make this work.
#[cfg(all(Py_3_9, not(target_os = "windows")))]
fn test_zoneinfo_is_not_fixed_offset() {
use crate::ffi;
use crate::types::any::PyAnyMethods;
use crate::types::dict::PyDictMethods;
Python::with_gil(|py| {
let locals = crate::types::PyDict::new(py);
py.run(
ffi::c_str!("import zoneinfo; zi = zoneinfo.ZoneInfo('Europe/London')"),
None,
Some(&locals),
)
.unwrap();
let result: PyResult<FixedOffset> = locals.get_item("zi").unwrap().unwrap().extract();
assert!(result.is_err());
let res = result.err().unwrap();
// Also check the error message is what we expect
let msg = res.value(py).repr().unwrap().to_string();
assert_eq!(msg, "TypeError(\"zoneinfo.ZoneInfo(key='Europe/London') is not a fixed offset timezone\")");
});
}
#[test]
fn test_timezone_aware_to_naive_fails() {
// Test that if a user tries to convert a python's timezone aware datetime into a naive
// one, the conversion fails.
Python::with_gil(|py| {
let py_datetime =
new_py_datetime_ob(py, "datetime", (2022, 1, 1, 1, 0, 0, 0, python_utc(py)));
// Now test that converting a PyDateTime with tzinfo to a NaiveDateTime fails
let res: PyResult<NaiveDateTime> = py_datetime.extract();
assert_eq!(
res.unwrap_err().value(py).repr().unwrap().to_string(),
"TypeError('expected a datetime without tzinfo')"
);
});
}
#[test]
fn test_naive_to_timezone_aware_fails() {
// Test that if a user tries to convert a python's timezone aware datetime into a naive
// one, the conversion fails.
Python::with_gil(|py| {
let py_datetime = new_py_datetime_ob(py, "datetime", (2022, 1, 1, 1, 0, 0, 0));
// Now test that converting a PyDateTime with tzinfo to a NaiveDateTime fails
let res: PyResult<DateTime<Utc>> = py_datetime.extract();
assert_eq!(
res.unwrap_err().value(py).repr().unwrap().to_string(),
"TypeError('expected a datetime with non-None tzinfo')"
);
// Now test that converting a PyDateTime with tzinfo to a NaiveDateTime fails
let res: PyResult<DateTime<FixedOffset>> = py_datetime.extract();
assert_eq!(
res.unwrap_err().value(py).repr().unwrap().to_string(),
"TypeError('expected a datetime with non-None tzinfo')"
);
});
}
#[test]
fn test_invalid_types_fail() {
// Test that if a user tries to convert a python's timezone aware datetime into a naive
// one, the conversion fails.
Python::with_gil(|py| {
let none = py.None().into_bound(py);
assert_eq!(
none.extract::<Duration>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDelta'"
);
assert_eq!(
none.extract::<FixedOffset>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyTzInfo'"
);
assert_eq!(
none.extract::<Utc>().unwrap_err().to_string(),
"ValueError: expected datetime.timezone.utc"
);
assert_eq!(
none.extract::<NaiveTime>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyTime'"
);
assert_eq!(
none.extract::<NaiveDate>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDate'"
);
assert_eq!(
none.extract::<NaiveDateTime>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDateTime'"
);
assert_eq!(
none.extract::<DateTime<Utc>>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDateTime'"
);
assert_eq!(
none.extract::<DateTime<FixedOffset>>()
.unwrap_err()
.to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDateTime'"
);
});
}
#[test]
fn test_pyo3_timedelta_into_pyobject() {
// Utility function used to check different durations.
// The `name` parameter is used to identify the check in case of a failure.
let check = |name: &'static str, delta: Duration, py_days, py_seconds, py_ms| {
Python::with_gil(|py| {
let delta = delta.into_pyobject(py).unwrap();
let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms));
assert!(
delta.eq(&py_delta).unwrap(),
"{}: {} != {}",
name,
delta,
py_delta
);
});
};
let delta = Duration::days(-1) + Duration::seconds(1) + Duration::microseconds(-10);
check("delta normalization", delta, -1, 1, -10);
// Check the minimum value allowed by PyDelta, which is different
// from the minimum value allowed in Duration. This should pass.
let delta = Duration::seconds(-86399999913600); // min
check("delta min value", delta, -999999999, 0, 0);
// Same, for max value
let delta = Duration::seconds(86399999999999) + Duration::nanoseconds(999999000); // max
check("delta max value", delta, 999999999, 86399, 999999);
// Also check that trying to convert an out of bound value errors.
Python::with_gil(|py| {
assert!(Duration::min_value().into_pyobject(py).is_err());
assert!(Duration::max_value().into_pyobject(py).is_err());
});
}
#[test]
fn test_pyo3_timedelta_frompyobject() {
// Utility function used to check different durations.
// The `name` parameter is used to identify the check in case of a failure.
let check = |name: &'static str, delta: Duration, py_days, py_seconds, py_ms| {
Python::with_gil(|py| {
let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms));
let py_delta: Duration = py_delta.extract().unwrap();
assert_eq!(py_delta, delta, "{}: {} != {}", name, py_delta, delta);
})
};
// Check the minimum value allowed by PyDelta, which is different
// from the minimum value allowed in Duration. This should pass.
check(
"min py_delta value",
Duration::seconds(-86399999913600),
-999999999,
0,
0,
);
// Same, for max value
check(
"max py_delta value",
Duration::seconds(86399999999999) + Duration::microseconds(999999),
999999999,
86399,
999999,
);
// This check is to assert that we can't construct every possible Duration from a PyDelta
// since they have different bounds.
Python::with_gil(|py| {
let low_days: i32 = -1000000000;
// This is possible
assert!(panic::catch_unwind(|| Duration::days(low_days as i64)).is_ok());
// This panics on PyDelta::new
assert!(panic::catch_unwind(|| {
let py_delta = new_py_datetime_ob(py, "timedelta", (low_days, 0, 0));
if let Ok(_duration) = py_delta.extract::<Duration>() {
// So we should never get here
}
})
.is_err());
let high_days: i32 = 1000000000;
// This is possible
assert!(panic::catch_unwind(|| Duration::days(high_days as i64)).is_ok());
// This panics on PyDelta::new
assert!(panic::catch_unwind(|| {
let py_delta = new_py_datetime_ob(py, "timedelta", (high_days, 0, 0));
if let Ok(_duration) = py_delta.extract::<Duration>() {
// So we should never get here
}
})
.is_err());
});
}
#[test]
fn test_pyo3_date_into_pyobject() {
let eq_ymd = |name: &'static str, year, month, day| {
Python::with_gil(|py| {
let date = NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.into_pyobject(py)
.unwrap();
let py_date = new_py_datetime_ob(py, "date", (year, month, day));
assert_eq!(
date.compare(&py_date).unwrap(),
Ordering::Equal,
"{}: {} != {}",
name,
date,
py_date
);
})
};
eq_ymd("past date", 2012, 2, 29);
eq_ymd("min date", 1, 1, 1);
eq_ymd("future date", 3000, 6, 5);
eq_ymd("max date", 9999, 12, 31);
}
#[test]
fn test_pyo3_date_frompyobject() {
let eq_ymd = |name: &'static str, year, month, day| {
Python::with_gil(|py| {
let py_date = new_py_datetime_ob(py, "date", (year, month, day));
let py_date: NaiveDate = py_date.extract().unwrap();
let date = NaiveDate::from_ymd_opt(year, month, day).unwrap();
assert_eq!(py_date, date, "{}: {} != {}", name, date, py_date);
})
};
eq_ymd("past date", 2012, 2, 29);
eq_ymd("min date", 1, 1, 1);
eq_ymd("future date", 3000, 6, 5);
eq_ymd("max date", 9999, 12, 31);
}
#[test]
fn test_pyo3_datetime_into_pyobject_utc() {
Python::with_gil(|py| {
let check_utc =
|name: &'static str, year, month, day, hour, minute, second, ms, py_ms| {
let datetime = NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_micro_opt(hour, minute, second, ms)
.unwrap()
.and_utc();
let datetime = datetime.into_pyobject(py).unwrap();
let py_datetime = new_py_datetime_ob(
py,
"datetime",
(
year,
month,
day,
hour,
minute,
second,
py_ms,
python_utc(py),
),
);
assert_eq!(
datetime.compare(&py_datetime).unwrap(),
Ordering::Equal,
"{}: {} != {}",
name,
datetime,
py_datetime
);
};
check_utc("regular", 2014, 5, 6, 7, 8, 9, 999_999, 999_999);
#[cfg(not(Py_GIL_DISABLED))]
assert_warnings!(
py,
check_utc("leap second", 2014, 5, 6, 7, 8, 59, 1_999_999, 999_999),
[(
PyUserWarning,
"ignored leap-second, `datetime` does not support leap-seconds"
)]
);
})
}
#[test]
fn test_pyo3_datetime_into_pyobject_fixed_offset() {
Python::with_gil(|py| {
let check_fixed_offset =
|name: &'static str, year, month, day, hour, minute, second, ms, py_ms| {
let offset = FixedOffset::east_opt(3600).unwrap();
let datetime = NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_micro_opt(hour, minute, second, ms)
.unwrap()
.and_local_timezone(offset)
.unwrap();
let datetime = datetime.into_pyobject(py).unwrap();
let py_tz = offset.into_pyobject(py).unwrap();
let py_datetime = new_py_datetime_ob(
py,
"datetime",
(year, month, day, hour, minute, second, py_ms, py_tz),
);
assert_eq!(
datetime.compare(&py_datetime).unwrap(),
Ordering::Equal,
"{}: {} != {}",
name,
datetime,
py_datetime
);
};
check_fixed_offset("regular", 2014, 5, 6, 7, 8, 9, 999_999, 999_999);
#[cfg(not(Py_GIL_DISABLED))]
assert_warnings!(
py,
check_fixed_offset("leap second", 2014, 5, 6, 7, 8, 59, 1_999_999, 999_999),
[(
PyUserWarning,
"ignored leap-second, `datetime` does not support leap-seconds"
)]
);
})
}
#[test]
fn test_pyo3_datetime_frompyobject_utc() {
Python::with_gil(|py| {
let year = 2014;
let month = 5;
let day = 6;
let hour = 7;
let minute = 8;
let second = 9;
let micro = 999_999;
let tz_utc = timezone_utc(py);
let py_datetime = new_py_datetime_ob(
py,
"datetime",
(year, month, day, hour, minute, second, micro, tz_utc),
);
let py_datetime: DateTime<Utc> = py_datetime.extract().unwrap();
let datetime = NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_micro_opt(hour, minute, second, micro)
.unwrap()
.and_utc();
assert_eq!(py_datetime, datetime,);
})
}
#[test]
fn test_pyo3_datetime_frompyobject_fixed_offset() {
Python::with_gil(|py| {
let year = 2014;
let month = 5;
let day = 6;
let hour = 7;
let minute = 8;
let second = 9;
let micro = 999_999;
let offset = FixedOffset::east_opt(3600).unwrap();
let py_tz = offset.into_pyobject(py).unwrap();
let py_datetime = new_py_datetime_ob(
py,
"datetime",
(year, month, day, hour, minute, second, micro, py_tz),
);
let datetime_from_py: DateTime<FixedOffset> = py_datetime.extract().unwrap();
let datetime = NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_micro_opt(hour, minute, second, micro)
.unwrap();
let datetime = datetime.and_local_timezone(offset).unwrap();
assert_eq!(datetime_from_py, datetime);
assert!(
py_datetime.extract::<DateTime<Utc>>().is_err(),
"Extracting Utc from nonzero FixedOffset timezone will fail"
);
let utc = python_utc(py);
let py_datetime_utc = new_py_datetime_ob(
py,
"datetime",
(year, month, day, hour, minute, second, micro, utc),
);
assert!(
py_datetime_utc.extract::<DateTime<FixedOffset>>().is_ok(),
"Extracting FixedOffset from Utc timezone will succeed"
);
})
}
#[test]
fn test_pyo3_offset_fixed_into_pyobject() {
Python::with_gil(|py| {
// Chrono offset
let offset = FixedOffset::east_opt(3600)
.unwrap()
.into_pyobject(py)
.unwrap();
// Python timezone from timedelta
let td = new_py_datetime_ob(py, "timedelta", (0, 3600, 0));
let py_timedelta = new_py_datetime_ob(py, "timezone", (td,));
// Should be equal
assert!(offset.eq(py_timedelta).unwrap());
// Same but with negative values
let offset = FixedOffset::east_opt(-3600)
.unwrap()
.into_pyobject(py)
.unwrap();
let td = new_py_datetime_ob(py, "timedelta", (0, -3600, 0));
let py_timedelta = new_py_datetime_ob(py, "timezone", (td,));
assert!(offset.eq(py_timedelta).unwrap());
})
}
#[test]
fn test_pyo3_offset_fixed_frompyobject() {
Python::with_gil(|py| {
let py_timedelta = new_py_datetime_ob(py, "timedelta", (0, 3600, 0));
let py_tzinfo = new_py_datetime_ob(py, "timezone", (py_timedelta,));
let offset: FixedOffset = py_tzinfo.extract().unwrap();
assert_eq!(FixedOffset::east_opt(3600).unwrap(), offset);
})
}
#[test]
fn test_pyo3_offset_utc_into_pyobject() {
Python::with_gil(|py| {
let utc = Utc.into_pyobject(py).unwrap();
let py_utc = python_utc(py);
assert!(utc.is(&py_utc));
})
}
#[test]
fn test_pyo3_offset_utc_frompyobject() {
Python::with_gil(|py| {
let py_utc = python_utc(py);
let py_utc: Utc = py_utc.extract().unwrap();
assert_eq!(Utc, py_utc);
let py_timedelta = new_py_datetime_ob(py, "timedelta", (0, 0, 0));
let py_timezone_utc = new_py_datetime_ob(py, "timezone", (py_timedelta,));
let py_timezone_utc: Utc = py_timezone_utc.extract().unwrap();
assert_eq!(Utc, py_timezone_utc);
let py_timedelta = new_py_datetime_ob(py, "timedelta", (0, 3600, 0));
let py_timezone = new_py_datetime_ob(py, "timezone", (py_timedelta,));
assert!(py_timezone.extract::<Utc>().is_err());
})
}
#[test]
fn test_pyo3_time_into_pyobject() {
Python::with_gil(|py| {
let check_time = |name: &'static str, hour, minute, second, ms, py_ms| {
let time = NaiveTime::from_hms_micro_opt(hour, minute, second, ms)
.unwrap()
.into_pyobject(py)
.unwrap();
let py_time = new_py_datetime_ob(py, "time", (hour, minute, second, py_ms));
assert!(
time.eq(&py_time).unwrap(),
"{}: {} != {}",
name,
time,
py_time
);
};
check_time("regular", 3, 5, 7, 999_999, 999_999);
#[cfg(not(Py_GIL_DISABLED))]
assert_warnings!(
py,
check_time("leap second", 3, 5, 59, 1_999_999, 999_999),
[(
PyUserWarning,
"ignored leap-second, `datetime` does not support leap-seconds"
)]
);
})
}
#[test]
fn test_pyo3_time_frompyobject() {
let hour = 3;
let minute = 5;
let second = 7;
let micro = 999_999;
Python::with_gil(|py| {
let py_time = new_py_datetime_ob(py, "time", (hour, minute, second, micro));
let py_time: NaiveTime = py_time.extract().unwrap();
let time = NaiveTime::from_hms_micro_opt(hour, minute, second, micro).unwrap();
assert_eq!(py_time, time);
})
}
fn new_py_datetime_ob<'py, A>(py: Python<'py>, name: &str, args: A) -> Bound<'py, PyAny>
where
A: IntoPyObject<'py, Target = PyTuple>,
{
py.import("datetime")
.unwrap()
.getattr(name)
.unwrap()
.call1(
args.into_pyobject(py)
.map_err(Into::into)
.unwrap()
.into_bound(),
)
.unwrap()
}
fn python_utc(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime")
.unwrap()
.getattr("timezone")
.unwrap()
.getattr("utc")
.unwrap()
}
#[cfg(not(any(target_arch = "wasm32", Py_GIL_DISABLED)))]
mod proptests {
use super::*;
use crate::tests::common::CatchWarnings;
use crate::types::IntoPyDict;
use proptest::prelude::*;
use std::ffi::CString;
proptest! {
// Range is limited to 1970 to 2038 due to windows limitations
#[test]
fn test_pyo3_offset_fixed_frompyobject_created_in_python(timestamp in 0..(i32::MAX as i64), timedelta in -86399i32..=86399i32) {
Python::with_gil(|py| {
let globals = [("datetime", py.import("datetime").unwrap())].into_py_dict(py).unwrap();
let code = format!("datetime.datetime.fromtimestamp({}).replace(tzinfo=datetime.timezone(datetime.timedelta(seconds={})))", timestamp, timedelta);
let t = py.eval(&CString::new(code).unwrap(), Some(&globals), None).unwrap();
// Get ISO 8601 string from python
let py_iso_str = t.call_method0("isoformat").unwrap();
// Get ISO 8601 string from rust
let t = t.extract::<DateTime<FixedOffset>>().unwrap();
// Python doesn't print the seconds of the offset if they are 0
let rust_iso_str = if timedelta % 60 == 0 {
t.format("%Y-%m-%dT%H:%M:%S%:z").to_string()
} else {
t.format("%Y-%m-%dT%H:%M:%S%::z").to_string()
};
// They should be equal
assert_eq!(py_iso_str.to_string(), rust_iso_str);
})
}
#[test]
fn test_duration_roundtrip(days in -999999999i64..=999999999i64) {
// Test roundtrip conversion rust->python->rust for all allowed
// python values of durations (from -999999999 to 999999999 days),
Python::with_gil(|py| {
let dur = Duration::days(days);
let py_delta = dur.into_pyobject(py).unwrap();
let roundtripped: Duration = py_delta.extract().expect("Round trip");
assert_eq!(dur, roundtripped);
})
}
#[test]
fn test_fixed_offset_roundtrip(secs in -86399i32..=86399i32) {
Python::with_gil(|py| {
let offset = FixedOffset::east_opt(secs).unwrap();
let py_offset = offset.into_pyobject(py).unwrap();
let roundtripped: FixedOffset = py_offset.extract().expect("Round trip");
assert_eq!(offset, roundtripped);
})
}
#[test]
fn test_naive_date_roundtrip(
year in 1i32..=9999i32,
month in 1u32..=12u32,
day in 1u32..=31u32
) {
// Test roundtrip conversion rust->python->rust for all allowed
// python dates (from year 1 to year 9999)
Python::with_gil(|py| {
// We use to `from_ymd_opt` constructor so that we only test valid `NaiveDate`s.
// This is to skip the test if we are creating an invalid date, like February 31.
if let Some(date) = NaiveDate::from_ymd_opt(year, month, day) {
let py_date = date.into_pyobject(py).unwrap();
let roundtripped: NaiveDate = py_date.extract().expect("Round trip");
assert_eq!(date, roundtripped);
}
})
}
#[test]
fn test_naive_time_roundtrip(
hour in 0u32..=23u32,
min in 0u32..=59u32,
sec in 0u32..=59u32,
micro in 0u32..=1_999_999u32
) {
// Test roundtrip conversion rust->python->rust for naive times.
// Python time has a resolution of microseconds, so we only test
// NaiveTimes with microseconds resolution, even if NaiveTime has nanosecond
// resolution.
Python::with_gil(|py| {
if let Some(time) = NaiveTime::from_hms_micro_opt(hour, min, sec, micro) {
// Wrap in CatchWarnings to avoid to_object firing warning for truncated leap second
let py_time = CatchWarnings::enter(py, |_| time.into_pyobject(py)).unwrap();
let roundtripped: NaiveTime = py_time.extract().expect("Round trip");
// Leap seconds are not roundtripped
let expected_roundtrip_time = micro.checked_sub(1_000_000).map(|micro| NaiveTime::from_hms_micro_opt(hour, min, sec, micro).unwrap()).unwrap_or(time);
assert_eq!(expected_roundtrip_time, roundtripped);
}
})
}
#[test]
fn test_naive_datetime_roundtrip(
year in 1i32..=9999i32,
month in 1u32..=12u32,
day in 1u32..=31u32,
hour in 0u32..=24u32,
min in 0u32..=60u32,
sec in 0u32..=60u32,
micro in 0u32..=999_999u32
) {
Python::with_gil(|py| {
let date_opt = NaiveDate::from_ymd_opt(year, month, day);
let time_opt = NaiveTime::from_hms_micro_opt(hour, min, sec, micro);
if let (Some(date), Some(time)) = (date_opt, time_opt) {
let dt = NaiveDateTime::new(date, time);
let pydt = dt.into_pyobject(py).unwrap();
let roundtripped: NaiveDateTime = pydt.extract().expect("Round trip");
assert_eq!(dt, roundtripped);
}
})
}
#[test]
fn test_utc_datetime_roundtrip(
year in 1i32..=9999i32,
month in 1u32..=12u32,
day in 1u32..=31u32,
hour in 0u32..=23u32,
min in 0u32..=59u32,
sec in 0u32..=59u32,
micro in 0u32..=1_999_999u32
) {
Python::with_gil(|py| {
let date_opt = NaiveDate::from_ymd_opt(year, month, day);
let time_opt = NaiveTime::from_hms_micro_opt(hour, min, sec, micro);
if let (Some(date), Some(time)) = (date_opt, time_opt) {
let dt: DateTime<Utc> = NaiveDateTime::new(date, time).and_utc();
// Wrap in CatchWarnings to avoid into_py firing warning for truncated leap second
let py_dt = CatchWarnings::enter(py, |_| dt.into_pyobject(py)).unwrap();
let roundtripped: DateTime<Utc> = py_dt.extract().expect("Round trip");
// Leap seconds are not roundtripped
let expected_roundtrip_time = micro.checked_sub(1_000_000).map(|micro| NaiveTime::from_hms_micro_opt(hour, min, sec, micro).unwrap()).unwrap_or(time);
let expected_roundtrip_dt: DateTime<Utc> = NaiveDateTime::new(date, expected_roundtrip_time).and_utc();
assert_eq!(expected_roundtrip_dt, roundtripped);
}
})
}
#[test]
fn test_fixed_offset_datetime_roundtrip(
year in 1i32..=9999i32,
month in 1u32..=12u32,
day in 1u32..=31u32,
hour in 0u32..=23u32,
min in 0u32..=59u32,
sec in 0u32..=59u32,
micro in 0u32..=1_999_999u32,
offset_secs in -86399i32..=86399i32
) {
Python::with_gil(|py| {
let date_opt = NaiveDate::from_ymd_opt(year, month, day);
let time_opt = NaiveTime::from_hms_micro_opt(hour, min, sec, micro);
let offset = FixedOffset::east_opt(offset_secs).unwrap();
if let (Some(date), Some(time)) = (date_opt, time_opt) {
let dt: DateTime<FixedOffset> = NaiveDateTime::new(date, time).and_local_timezone(offset).unwrap();
// Wrap in CatchWarnings to avoid into_py firing warning for truncated leap second
let py_dt = CatchWarnings::enter(py, |_| dt.into_pyobject(py)).unwrap();
let roundtripped: DateTime<FixedOffset> = py_dt.extract().expect("Round trip");
// Leap seconds are not roundtripped
let expected_roundtrip_time = micro.checked_sub(1_000_000).map(|micro| NaiveTime::from_hms_micro_opt(hour, min, sec, micro).unwrap()).unwrap_or(time);
let expected_roundtrip_dt: DateTime<FixedOffset> = NaiveDateTime::new(date, expected_roundtrip_time).and_local_timezone(offset).unwrap();
assert_eq!(expected_roundtrip_dt, roundtripped);
}
})
}
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/indexmap.rs | #![cfg(feature = "indexmap")]
//! Conversions to and from [indexmap](https://docs.rs/indexmap/)’s
//! `IndexMap`.
//!
//! [`indexmap::IndexMap`] is a hash table that is closely compatible with the standard [`std::collections::HashMap`],
//! with the difference that it preserves the insertion order when iterating over keys. It was inspired
//! by Python's 3.6+ dict implementation.
//!
//! Dictionary order is guaranteed to be insertion order in Python, hence IndexMap is a good candidate
//! for maintaining an equivalent behaviour in Rust.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! # change * to the latest versions
//! indexmap = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"indexmap\"] }")]
//! ```
//!
//! Note that you must use compatible versions of indexmap and PyO3.
//! The required indexmap version may vary based on the version of PyO3.
//!
//! # Examples
//!
//! Using [indexmap](https://docs.rs/indexmap) to return a dictionary with some statistics
//! about a list of numbers. Because of the insertion order guarantees, the Python code will
//! always print the same result, matching users' expectations about Python's dict.
//! ```rust
//! use indexmap::{indexmap, IndexMap};
//! use pyo3::prelude::*;
//!
//! fn median(data: &Vec<i32>) -> f32 {
//! let sorted_data = data.clone().sort();
//! let mid = data.len() / 2;
//! if data.len() % 2 == 0 {
//! data[mid] as f32
//! }
//! else {
//! (data[mid] + data[mid - 1]) as f32 / 2.0
//! }
//! }
//!
//! fn mean(data: &Vec<i32>) -> f32 {
//! data.iter().sum::<i32>() as f32 / data.len() as f32
//! }
//! fn mode(data: &Vec<i32>) -> f32 {
//! let mut frequency = IndexMap::new(); // we can use IndexMap as any hash table
//!
//! for &element in data {
//! *frequency.entry(element).or_insert(0) += 1;
//! }
//!
//! frequency
//! .iter()
//! .max_by(|a, b| a.1.cmp(&b.1))
//! .map(|(k, _v)| *k)
//! .unwrap() as f32
//! }
//!
//! #[pyfunction]
//! fn calculate_statistics(data: Vec<i32>) -> IndexMap<&'static str, f32> {
//! indexmap! {
//! "median" => median(&data),
//! "mean" => mean(&data),
//! "mode" => mode(&data),
//! }
//! }
//!
//! #[pymodule]
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
//! m.add_function(wrap_pyfunction!(calculate_statistics, m)?)?;
//! Ok(())
//! }
//! ```
//!
//! Python code:
//! ```python
//! from my_module import calculate_statistics
//!
//! data = [1, 1, 1, 3, 4, 5]
//! print(calculate_statistics(data))
//! # always prints {"median": 2.0, "mean": 2.5, "mode": 1.0} in the same order
//! # if another hash table was used, the order could be random
//! ```
use crate::conversion::IntoPyObject;
use crate::types::*;
use crate::{Bound, FromPyObject, PyErr, PyObject, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::{cmp, hash};
#[allow(deprecated)]
impl<K, V, H> ToPyObject for indexmap::IndexMap<K, V, H>
where
K: hash::Hash + cmp::Eq + ToPyObject,
V: ToPyObject,
H: hash::BuildHasher,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.to_object(py), v.to_object(py)).unwrap();
}
dict.into_any().unbind()
}
}
#[allow(deprecated)]
impl<K, V, H> IntoPy<PyObject> for indexmap::IndexMap<K, V, H>
where
K: hash::Hash + cmp::Eq + IntoPy<PyObject>,
V: IntoPy<PyObject>,
H: hash::BuildHasher,
{
fn into_py(self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.into_py(py), v.into_py(py)).unwrap();
}
dict.into_any().unbind()
}
}
impl<'py, K, V, H> IntoPyObject<'py> for indexmap::IndexMap<K, V, H>
where
K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
V: IntoPyObject<'py>,
H: hash::BuildHasher,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
}
impl<'a, 'py, K, V, H> IntoPyObject<'py> for &'a indexmap::IndexMap<K, V, H>
where
&'a K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
&'a V: IntoPyObject<'py>,
H: hash::BuildHasher,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
}
impl<'py, K, V, S> FromPyObject<'py> for indexmap::IndexMap<K, V, S>
where
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
V: FromPyObject<'py>,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = indexmap::IndexMap::with_capacity_and_hasher(dict.len(), S::default());
for (k, v) in dict {
ret.insert(k.extract()?, v.extract()?);
}
Ok(ret)
}
}
#[cfg(test)]
mod test_indexmap {
use crate::types::*;
use crate::{IntoPyObject, Python};
#[test]
fn test_indexmap_indexmap_into_pyobject() {
Python::with_gil(|py| {
let mut map = indexmap::IndexMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = (&map).into_pyobject(py).unwrap();
assert!(py_map.len() == 1);
assert!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
== 1
);
assert_eq!(
map,
py_map.extract::<indexmap::IndexMap::<i32, i32>>().unwrap()
);
});
}
#[test]
fn test_indexmap_indexmap_into_dict() {
Python::with_gil(|py| {
let mut map = indexmap::IndexMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = map.into_py_dict(py).unwrap();
assert_eq!(py_map.len(), 1);
assert_eq!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap(),
1
);
});
}
#[test]
fn test_indexmap_indexmap_insertion_order_round_trip() {
Python::with_gil(|py| {
let n = 20;
let mut map = indexmap::IndexMap::<i32, i32>::new();
for i in 1..=n {
if i % 2 == 1 {
map.insert(i, i);
} else {
map.insert(n - i, i);
}
}
let py_map = (&map).into_py_dict(py).unwrap();
let trip_map = py_map.extract::<indexmap::IndexMap<i32, i32>>().unwrap();
for (((k1, v1), (k2, v2)), (k3, v3)) in
map.iter().zip(py_map.iter()).zip(trip_map.iter())
{
let k2 = k2.extract::<i32>().unwrap();
let v2 = v2.extract::<i32>().unwrap();
assert_eq!((k1, v1), (&k2, &v2));
assert_eq!((k1, v1), (k3, v3));
assert_eq!((&k2, &v2), (k3, v3));
}
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/rust_decimal.rs | #![cfg(feature = "rust_decimal")]
//! Conversions to and from [rust_decimal](https://docs.rs/rust_decimal)'s [`Decimal`] type.
//!
//! This is useful for converting Python's decimal.Decimal into and from a native Rust type.
//!
//! # Setup
//!
//! To use this feature, add to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"rust_decimal\"] }")]
//! rust_decimal = "1.0"
//! ```
//!
//! Note that you must use a compatible version of rust_decimal and PyO3.
//! The required rust_decimal version may vary based on the version of PyO3.
//!
//! # Example
//!
//! Rust code to create a function that adds one to a Decimal
//!
//! ```rust
//! use rust_decimal::Decimal;
//! use pyo3::prelude::*;
//!
//! #[pyfunction]
//! fn add_one(d: Decimal) -> Decimal {
//! d + Decimal::ONE
//! }
//!
//! #[pymodule]
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
//! m.add_function(wrap_pyfunction!(add_one, m)?)?;
//! Ok(())
//! }
//! ```
//!
//! Python code that validates the functionality
//!
//!
//! ```python
//! from my_module import add_one
//! from decimal import Decimal
//!
//! d = Decimal("2")
//! value = add_one(d)
//!
//! assert d + 1 == value
//! ```
use crate::conversion::IntoPyObject;
use crate::exceptions::PyValueError;
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
use crate::types::string::PyStringMethods;
use crate::types::PyType;
use crate::{Bound, FromPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use rust_decimal::Decimal;
use std::str::FromStr;
impl FromPyObject<'_> for Decimal {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
// use the string representation to not be lossy
if let Ok(val) = obj.extract() {
Ok(Decimal::new(val, 0))
} else {
let py_str = &obj.str()?;
let rs_str = &py_str.to_cow()?;
Decimal::from_str(rs_str).or_else(|_| {
Decimal::from_scientific(rs_str).map_err(|e| PyValueError::new_err(e.to_string()))
})
}
}
}
static DECIMAL_CLS: GILOnceCell<Py<PyType>> = GILOnceCell::new();
fn get_decimal_cls(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
DECIMAL_CLS.import(py, "decimal", "Decimal")
}
#[allow(deprecated)]
impl ToPyObject for Decimal {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Decimal {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Decimal {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dec_cls = get_decimal_cls(py)?;
// now call the constructor with the Rust Decimal string-ified
// to not be lossy
dec_cls.call1((self.to_string(),))
}
}
impl<'py> IntoPyObject<'py> for &Decimal {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
#[cfg(test)]
mod test_rust_decimal {
use super::*;
use crate::types::dict::PyDictMethods;
use crate::types::PyDict;
use std::ffi::CString;
use crate::ffi;
#[cfg(not(target_arch = "wasm32"))]
use proptest::prelude::*;
macro_rules! convert_constants {
($name:ident, $rs:expr, $py:literal) => {
#[test]
fn $name() {
Python::with_gil(|py| {
let rs_orig = $rs;
let rs_dec = rs_orig.into_pyobject(py).unwrap();
let locals = PyDict::new(py);
locals.set_item("rs_dec", &rs_dec).unwrap();
// Checks if Rust Decimal -> Python Decimal conversion is correct
py.run(
&CString::new(format!(
"import decimal\npy_dec = decimal.Decimal({})\nassert py_dec == rs_dec",
$py
))
.unwrap(),
None,
Some(&locals),
)
.unwrap();
// Checks if Python Decimal -> Rust Decimal conversion is correct
let py_dec = locals.get_item("py_dec").unwrap().unwrap();
let py_result: Decimal = py_dec.extract().unwrap();
assert_eq!(rs_orig, py_result);
})
}
};
}
convert_constants!(convert_zero, Decimal::ZERO, "0");
convert_constants!(convert_one, Decimal::ONE, "1");
convert_constants!(convert_neg_one, Decimal::NEGATIVE_ONE, "-1");
convert_constants!(convert_two, Decimal::TWO, "2");
convert_constants!(convert_ten, Decimal::TEN, "10");
convert_constants!(convert_one_hundred, Decimal::ONE_HUNDRED, "100");
convert_constants!(convert_one_thousand, Decimal::ONE_THOUSAND, "1000");
#[cfg(not(target_arch = "wasm32"))]
proptest! {
#[test]
fn test_roundtrip(
lo in any::<u32>(),
mid in any::<u32>(),
high in any::<u32>(),
negative in any::<bool>(),
scale in 0..28u32
) {
let num = Decimal::from_parts(lo, mid, high, negative, scale);
Python::with_gil(|py| {
let rs_dec = num.into_pyobject(py).unwrap();
let locals = PyDict::new(py);
locals.set_item("rs_dec", &rs_dec).unwrap();
py.run(
&CString::new(format!(
"import decimal\npy_dec = decimal.Decimal(\"{}\")\nassert py_dec == rs_dec",
num)).unwrap(),
None, Some(&locals)).unwrap();
let roundtripped: Decimal = rs_dec.extract().unwrap();
assert_eq!(num, roundtripped);
})
}
#[test]
fn test_integers(num in any::<i64>()) {
Python::with_gil(|py| {
let py_num = num.into_pyobject(py).unwrap();
let roundtripped: Decimal = py_num.extract().unwrap();
let rs_dec = Decimal::new(num, 0);
assert_eq!(rs_dec, roundtripped);
})
}
}
#[test]
fn test_nan() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("import decimal\npy_dec = decimal.Decimal(\"NaN\")"),
None,
Some(&locals),
)
.unwrap();
let py_dec = locals.get_item("py_dec").unwrap().unwrap();
let roundtripped: Result<Decimal, PyErr> = py_dec.extract();
assert!(roundtripped.is_err());
})
}
#[test]
fn test_scientific_notation() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("import decimal\npy_dec = decimal.Decimal(\"1e3\")"),
None,
Some(&locals),
)
.unwrap();
let py_dec = locals.get_item("py_dec").unwrap().unwrap();
let roundtripped: Decimal = py_dec.extract().unwrap();
let rs_dec = Decimal::from_scientific("1e3").unwrap();
assert_eq!(rs_dec, roundtripped);
})
}
#[test]
fn test_infinity() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("import decimal\npy_dec = decimal.Decimal(\"Infinity\")"),
None,
Some(&locals),
)
.unwrap();
let py_dec = locals.get_item("py_dec").unwrap().unwrap();
let roundtripped: Result<Decimal, PyErr> = py_dec.extract();
assert!(roundtripped.is_err());
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/num_complex.rs | #![cfg(feature = "num-complex")]
//! Conversions to and from [num-complex](https://docs.rs/num-complex)’
//! [`Complex`]`<`[`f32`]`>` and [`Complex`]`<`[`f64`]`>`.
//!
//! num-complex’ [`Complex`] supports more operations than PyO3's [`PyComplex`]
//! and can be used with the rest of the Rust ecosystem.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! # change * to the latest versions
//! num-complex = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"num-complex\"] }")]
//! ```
//!
//! Note that you must use compatible versions of num-complex and PyO3.
//! The required num-complex version may vary based on the version of PyO3.
//!
//! # Examples
//!
//! Using [num-complex](https://docs.rs/num-complex) and [nalgebra](https://docs.rs/nalgebra)
//! to create a pyfunction that calculates the eigenvalues of a 2x2 matrix.
//! ```ignore
//! # // not tested because nalgebra isn't supported on msrv
//! # // please file an issue if it breaks!
//! use nalgebra::base::{dimension::Const, Matrix};
//! use num_complex::Complex;
//! use pyo3::prelude::*;
//!
//! type T = Complex<f64>;
//!
//! #[pyfunction]
//! fn get_eigenvalues(m11: T, m12: T, m21: T, m22: T) -> Vec<T> {
//! let mat = Matrix::<T, Const<2>, Const<2>, _>::new(m11, m12, m21, m22);
//!
//! match mat.eigenvalues() {
//! Some(e) => e.data.as_slice().to_vec(),
//! None => vec![],
//! }
//! }
//!
//! #[pymodule]
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
//! m.add_function(wrap_pyfunction!(get_eigenvalues, m)?)?;
//! Ok(())
//! }
//! # // test
//! # use assert_approx_eq::assert_approx_eq;
//! # use nalgebra::ComplexField;
//! # use pyo3::types::PyComplex;
//! #
//! # fn main() -> PyResult<()> {
//! # Python::with_gil(|py| -> PyResult<()> {
//! # let module = PyModule::new(py, "my_module")?;
//! #
//! # module.add_function(&wrap_pyfunction!(get_eigenvalues, module)?)?;
//! #
//! # let m11 = PyComplex::from_doubles(py, 0_f64, -1_f64);
//! # let m12 = PyComplex::from_doubles(py, 1_f64, 0_f64);
//! # let m21 = PyComplex::from_doubles(py, 2_f64, -1_f64);
//! # let m22 = PyComplex::from_doubles(py, -1_f64, 0_f64);
//! #
//! # let result = module
//! # .getattr("get_eigenvalues")?
//! # .call1((m11, m12, m21, m22))?;
//! # println!("eigenvalues: {:?}", result);
//! #
//! # let result = result.extract::<Vec<T>>()?;
//! # let e0 = result[0];
//! # let e1 = result[1];
//! #
//! # assert_approx_eq!(e0, Complex::new(1_f64, -1_f64));
//! # assert_approx_eq!(e1, Complex::new(-2_f64, 0_f64));
//! #
//! # Ok(())
//! # })
//! # }
//! ```
//!
//! Python code:
//! ```python
//! from my_module import get_eigenvalues
//!
//! m11 = complex(0,-1)
//! m12 = complex(1,0)
//! m21 = complex(2,-1)
//! m22 = complex(-1,0)
//!
//! result = get_eigenvalues(m11,m12,m21,m22)
//! assert result == [complex(1,-1), complex(-2,0)]
//! ```
#[allow(deprecated)]
use crate::ToPyObject;
use crate::{
ffi,
ffi_ptr_ext::FfiPtrExt,
types::{any::PyAnyMethods, PyComplex},
Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python,
};
use num_complex::Complex;
use std::os::raw::c_double;
impl PyComplex {
/// Creates a new Python `PyComplex` object from `num_complex`'s [`Complex`].
pub fn from_complex_bound<F: Into<c_double>>(
py: Python<'_>,
complex: Complex<F>,
) -> Bound<'_, PyComplex> {
unsafe {
ffi::PyComplex_FromDoubles(complex.re.into(), complex.im.into())
.assume_owned(py)
.downcast_into_unchecked()
}
}
}
macro_rules! complex_conversion {
($float: ty) => {
#[cfg_attr(docsrs, doc(cfg(feature = "num-complex")))]
#[allow(deprecated)]
impl ToPyObject for Complex<$float> {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
crate::IntoPy::<PyObject>::into_py(self.to_owned(), py)
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-complex")))]
#[allow(deprecated)]
impl crate::IntoPy<PyObject> for Complex<$float> {
fn into_py(self, py: Python<'_>) -> PyObject {
unsafe {
let raw_obj =
ffi::PyComplex_FromDoubles(self.re as c_double, self.im as c_double);
PyObject::from_owned_ptr(py, raw_obj)
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-complex")))]
impl<'py> crate::conversion::IntoPyObject<'py> for Complex<$float> {
type Target = PyComplex;
type Output = Bound<'py, Self::Target>;
type Error = std::convert::Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
unsafe {
Ok(
ffi::PyComplex_FromDoubles(self.re as c_double, self.im as c_double)
.assume_owned(py)
.downcast_into_unchecked(),
)
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-complex")))]
impl<'py> crate::conversion::IntoPyObject<'py> for &Complex<$float> {
type Target = PyComplex;
type Output = Bound<'py, Self::Target>;
type Error = std::convert::Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-complex")))]
impl FromPyObject<'_> for Complex<$float> {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Complex<$float>> {
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
unsafe {
let val = ffi::PyComplex_AsCComplex(obj.as_ptr());
if val.real == -1.0 {
if let Some(err) = PyErr::take(obj.py()) {
return Err(err);
}
}
Ok(Complex::new(val.real as $float, val.imag as $float))
}
#[cfg(any(Py_LIMITED_API, PyPy))]
unsafe {
let complex;
let obj = if obj.is_instance_of::<PyComplex>() {
obj
} else if let Some(method) =
obj.lookup_special(crate::intern!(obj.py(), "__complex__"))?
{
complex = method.call0()?;
&complex
} else {
// `obj` might still implement `__float__` or `__index__`, which will be
// handled by `PyComplex_{Real,Imag}AsDouble`, including propagating any
// errors if those methods don't exist / raise exceptions.
obj
};
let ptr = obj.as_ptr();
let real = ffi::PyComplex_RealAsDouble(ptr);
if real == -1.0 {
if let Some(err) = PyErr::take(obj.py()) {
return Err(err);
}
}
let imag = ffi::PyComplex_ImagAsDouble(ptr);
Ok(Complex::new(real as $float, imag as $float))
}
}
}
};
}
complex_conversion!(f32);
complex_conversion!(f64);
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::common::generate_unique_module_name;
use crate::types::{complex::PyComplexMethods, PyModule};
use crate::IntoPyObject;
use pyo3_ffi::c_str;
#[test]
fn from_complex() {
Python::with_gil(|py| {
let complex = Complex::new(3.0, 1.2);
let py_c = PyComplex::from_complex_bound(py, complex);
assert_eq!(py_c.real(), 3.0);
assert_eq!(py_c.imag(), 1.2);
});
}
#[test]
fn to_from_complex() {
Python::with_gil(|py| {
let val = Complex::new(3.0f64, 1.2);
let obj = val.into_pyobject(py).unwrap();
assert_eq!(obj.extract::<Complex<f64>>().unwrap(), val);
});
}
#[test]
fn from_complex_err() {
Python::with_gil(|py| {
let obj = vec![1i32].into_pyobject(py).unwrap();
assert!(obj.extract::<Complex<f64>>().is_err());
});
}
#[test]
fn from_python_magic() {
Python::with_gil(|py| {
let module = PyModule::from_code(
py,
c_str!(
r#"
class A:
def __complex__(self): return 3.0+1.2j
class B:
def __float__(self): return 3.0
class C:
def __index__(self): return 3
"#
),
c_str!("test.py"),
&generate_unique_module_name("test"),
)
.unwrap();
let from_complex = module.getattr("A").unwrap().call0().unwrap();
assert_eq!(
from_complex.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 1.2)
);
let from_float = module.getattr("B").unwrap().call0().unwrap();
assert_eq!(
from_float.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 0.0)
);
// Before Python 3.8, `__index__` wasn't tried by `float`/`complex`.
#[cfg(Py_3_8)]
{
let from_index = module.getattr("C").unwrap().call0().unwrap();
assert_eq!(
from_index.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 0.0)
);
}
})
}
#[test]
fn from_python_inherited_magic() {
Python::with_gil(|py| {
let module = PyModule::from_code(
py,
c_str!(
r#"
class First: pass
class ComplexMixin:
def __complex__(self): return 3.0+1.2j
class FloatMixin:
def __float__(self): return 3.0
class IndexMixin:
def __index__(self): return 3
class A(First, ComplexMixin): pass
class B(First, FloatMixin): pass
class C(First, IndexMixin): pass
"#
),
c_str!("test.py"),
&generate_unique_module_name("test"),
)
.unwrap();
let from_complex = module.getattr("A").unwrap().call0().unwrap();
assert_eq!(
from_complex.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 1.2)
);
let from_float = module.getattr("B").unwrap().call0().unwrap();
assert_eq!(
from_float.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 0.0)
);
#[cfg(Py_3_8)]
{
let from_index = module.getattr("C").unwrap().call0().unwrap();
assert_eq!(
from_index.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 0.0)
);
}
})
}
#[test]
fn from_python_noncallable_descriptor_magic() {
// Functions and lambdas implement the descriptor protocol in a way that makes
// `type(inst).attr(inst)` equivalent to `inst.attr()` for methods, but this isn't the only
// way the descriptor protocol might be implemented.
Python::with_gil(|py| {
let module = PyModule::from_code(
py,
c_str!(
r#"
class A:
@property
def __complex__(self):
return lambda: 3.0+1.2j
"#
),
c_str!("test.py"),
&generate_unique_module_name("test"),
)
.unwrap();
let obj = module.getattr("A").unwrap().call0().unwrap();
assert_eq!(
obj.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 1.2)
);
})
}
#[test]
fn from_python_nondescriptor_magic() {
// Magic methods don't need to implement the descriptor protocol, if they're callable.
Python::with_gil(|py| {
let module = PyModule::from_code(
py,
c_str!(
r#"
class MyComplex:
def __call__(self): return 3.0+1.2j
class A:
__complex__ = MyComplex()
"#
),
c_str!("test.py"),
&generate_unique_module_name("test"),
)
.unwrap();
let obj = module.getattr("A").unwrap().call0().unwrap();
assert_eq!(
obj.extract::<Complex<f64>>().unwrap(),
Complex::new(3.0, 1.2)
);
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/smallvec.rs | #![cfg(feature = "smallvec")]
//! Conversions to and from [smallvec](https://docs.rs/smallvec/).
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! # change * to the latest versions
//! smallvec = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"smallvec\"] }")]
//! ```
//!
//! Note that you must use compatible versions of smallvec and PyO3.
//! The required smallvec version may vary based on the version of PyO3.
use crate::conversion::IntoPyObject;
use crate::exceptions::PyTypeError;
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::types::any::PyAnyMethods;
use crate::types::list::new_from_iter;
use crate::types::{PySequence, PyString};
use crate::PyErr;
use crate::{err::DowncastError, ffi, Bound, FromPyObject, PyAny, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use smallvec::{Array, SmallVec};
#[allow(deprecated)]
impl<A> ToPyObject for SmallVec<A>
where
A: Array,
A::Item: ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
self.as_slice().to_object(py)
}
}
#[allow(deprecated)]
impl<A> IntoPy<PyObject> for SmallVec<A>
where
A: Array,
A::Item: IntoPy<PyObject>,
{
fn into_py(self, py: Python<'_>) -> PyObject {
let mut iter = self.into_iter().map(|e| e.into_py(py));
let list = new_from_iter(py, &mut iter);
list.into()
}
}
impl<'py, A> IntoPyObject<'py> for SmallVec<A>
where
A: Array,
A::Item: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns [`SmallVec<u8>`] into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
<A::Item>::owned_sequence_into_pyobject(self, py, crate::conversion::private::Token)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::list_of(A::Item::type_output())
}
}
impl<'a, 'py, A> IntoPyObject<'py> for &'a SmallVec<A>
where
A: Array,
&'a A::Item: IntoPyObject<'py>,
A::Item: 'a, // MSRV
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_slice().into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::list_of(<&A::Item>::type_output())
}
}
impl<'py, A> FromPyObject<'py> for SmallVec<A>
where
A: Array,
A::Item: FromPyObject<'py>,
{
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
if obj.is_instance_of::<PyString>() {
return Err(PyTypeError::new_err("Can't extract `str` to `SmallVec`"));
}
extract_sequence(obj)
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::sequence_of(A::Item::type_input())
}
}
fn extract_sequence<'py, A>(obj: &Bound<'py, PyAny>) -> PyResult<SmallVec<A>>
where
A: Array,
A::Item: FromPyObject<'py>,
{
// Types that pass `PySequence_Check` usually implement enough of the sequence protocol
// to support this function and if not, we will only fail extraction safely.
let seq = unsafe {
if ffi::PySequence_Check(obj.as_ptr()) != 0 {
obj.downcast_unchecked::<PySequence>()
} else {
return Err(DowncastError::new(obj, "Sequence").into());
}
};
let mut sv = SmallVec::with_capacity(seq.len().unwrap_or(0));
for item in seq.try_iter()? {
sv.push(item?.extract::<A::Item>()?);
}
Ok(sv)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{PyBytes, PyBytesMethods, PyDict, PyList};
#[test]
#[allow(deprecated)]
fn test_smallvec_into_py() {
Python::with_gil(|py| {
let sv: SmallVec<[u64; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hso: PyObject = sv.clone().into_py(py);
let l = PyList::new(py, [1, 2, 3, 4, 5]).unwrap();
assert!(l.eq(hso).unwrap());
});
}
#[test]
fn test_smallvec_from_py_object() {
Python::with_gil(|py| {
let l = PyList::new(py, [1, 2, 3, 4, 5]).unwrap();
let sv: SmallVec<[u64; 8]> = l.extract().unwrap();
assert_eq!(sv.as_slice(), [1, 2, 3, 4, 5]);
});
}
#[test]
fn test_smallvec_from_py_object_fails() {
Python::with_gil(|py| {
let dict = PyDict::new(py);
let sv: PyResult<SmallVec<[u64; 8]>> = dict.extract();
assert_eq!(
sv.unwrap_err().to_string(),
"TypeError: 'dict' object cannot be converted to 'Sequence'"
);
});
}
#[test]
fn test_smallvec_into_pyobject() {
Python::with_gil(|py| {
let sv: SmallVec<[u64; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hso = sv.into_pyobject(py).unwrap();
let l = PyList::new(py, [1, 2, 3, 4, 5]).unwrap();
assert!(l.eq(hso).unwrap());
});
}
#[test]
fn test_smallvec_intopyobject_impl() {
Python::with_gil(|py| {
let bytes: SmallVec<[u8; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
let obj = bytes.clone().into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &*bytes);
let nums: SmallVec<[u16; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
let obj = nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/num_rational.rs | #![cfg(feature = "num-rational")]
//! Conversions to and from [num-rational](https://docs.rs/num-rational) types.
//!
//! This is useful for converting between Python's [fractions.Fraction](https://docs.python.org/3/library/fractions.html) into and from a native Rust
//! type.
//!
//!
//! To use this feature, add to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"num-rational\"] }")]
//! num-rational = "0.4.1"
//! ```
//!
//! # Example
//!
//! Rust code to create a function that adds five to a fraction:
//!
//! ```rust
//! use num_rational::Ratio;
//! use pyo3::prelude::*;
//!
//! #[pyfunction]
//! fn add_five_to_fraction(fraction: Ratio<i32>) -> Ratio<i32> {
//! fraction + Ratio::new(5, 1)
//! }
//!
//! #[pymodule]
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
//! m.add_function(wrap_pyfunction!(add_five_to_fraction, m)?)?;
//! Ok(())
//! }
//! ```
//!
//! Python code that validates the functionality:
//! ```python
//! from my_module import add_five_to_fraction
//! from fractions import Fraction
//!
//! fraction = Fraction(2,1)
//! fraction_plus_five = add_five_to_fraction(f)
//! assert fraction + 5 == fraction_plus_five
//! ```
use crate::conversion::IntoPyObject;
use crate::ffi;
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
use crate::types::PyType;
use crate::{Bound, FromPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[cfg(feature = "num-bigint")]
use num_bigint::BigInt;
use num_rational::Ratio;
static FRACTION_CLS: GILOnceCell<Py<PyType>> = GILOnceCell::new();
fn get_fraction_cls(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
FRACTION_CLS.import(py, "fractions", "Fraction")
}
macro_rules! rational_conversion {
($int: ty) => {
impl<'py> FromPyObject<'py> for Ratio<$int> {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
let py = obj.py();
let py_numerator_obj = obj.getattr(crate::intern!(py, "numerator"))?;
let py_denominator_obj = obj.getattr(crate::intern!(py, "denominator"))?;
let numerator_owned = unsafe {
Bound::from_owned_ptr_or_err(py, ffi::PyNumber_Long(py_numerator_obj.as_ptr()))?
};
let denominator_owned = unsafe {
Bound::from_owned_ptr_or_err(
py,
ffi::PyNumber_Long(py_denominator_obj.as_ptr()),
)?
};
let rs_numerator: $int = numerator_owned.extract()?;
let rs_denominator: $int = denominator_owned.extract()?;
Ok(Ratio::new(rs_numerator, rs_denominator))
}
}
#[allow(deprecated)]
impl ToPyObject for Ratio<$int> {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Ratio<$int> {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Ratio<$int> {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(&self).into_pyobject(py)
}
}
impl<'py> IntoPyObject<'py> for &Ratio<$int> {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
get_fraction_cls(py)?.call1((self.numer().clone(), self.denom().clone()))
}
}
};
}
rational_conversion!(i8);
rational_conversion!(i16);
rational_conversion!(i32);
rational_conversion!(isize);
rational_conversion!(i64);
#[cfg(feature = "num-bigint")]
rational_conversion!(BigInt);
#[cfg(test)]
mod tests {
use super::*;
use crate::types::dict::PyDictMethods;
use crate::types::PyDict;
#[cfg(not(target_arch = "wasm32"))]
use proptest::prelude::*;
#[test]
fn test_negative_fraction() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("import fractions\npy_frac = fractions.Fraction(-0.125)"),
None,
Some(&locals),
)
.unwrap();
let py_frac = locals.get_item("py_frac").unwrap().unwrap();
let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
let rs_frac = Ratio::new(-1, 8);
assert_eq!(roundtripped, rs_frac);
})
}
#[test]
fn test_obj_with_incorrect_atts() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("not_fraction = \"contains_incorrect_atts\""),
None,
Some(&locals),
)
.unwrap();
let py_frac = locals.get_item("not_fraction").unwrap().unwrap();
assert!(py_frac.extract::<Ratio<i32>>().is_err());
})
}
#[test]
fn test_fraction_with_fraction_type() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!(
"import fractions\npy_frac = fractions.Fraction(fractions.Fraction(10))"
),
None,
Some(&locals),
)
.unwrap();
let py_frac = locals.get_item("py_frac").unwrap().unwrap();
let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
let rs_frac = Ratio::new(10, 1);
assert_eq!(roundtripped, rs_frac);
})
}
#[test]
fn test_fraction_with_decimal() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("import fractions\n\nfrom decimal import Decimal\npy_frac = fractions.Fraction(Decimal(\"1.1\"))"),
None,
Some(&locals),
)
.unwrap();
let py_frac = locals.get_item("py_frac").unwrap().unwrap();
let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
let rs_frac = Ratio::new(11, 10);
assert_eq!(roundtripped, rs_frac);
})
}
#[test]
fn test_fraction_with_num_den() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
ffi::c_str!("import fractions\npy_frac = fractions.Fraction(10,5)"),
None,
Some(&locals),
)
.unwrap();
let py_frac = locals.get_item("py_frac").unwrap().unwrap();
let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
let rs_frac = Ratio::new(10, 5);
assert_eq!(roundtripped, rs_frac);
})
}
#[cfg(target_arch = "wasm32")]
#[test]
fn test_int_roundtrip() {
Python::with_gil(|py| {
let rs_frac = Ratio::new(1i32, 2);
let py_frac = rs_frac.into_pyobject(py).unwrap();
let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
assert_eq!(rs_frac, roundtripped);
// float conversion
})
}
#[cfg(target_arch = "wasm32")]
#[test]
fn test_big_int_roundtrip() {
Python::with_gil(|py| {
let rs_frac = Ratio::from_float(5.5).unwrap();
let py_frac = rs_frac.clone().into_pyobject(py).unwrap();
let roundtripped: Ratio<BigInt> = py_frac.extract().unwrap();
assert_eq!(rs_frac, roundtripped);
})
}
#[cfg(not(target_arch = "wasm32"))]
proptest! {
#[test]
fn test_int_roundtrip(num in any::<i32>(), den in any::<i32>()) {
Python::with_gil(|py| {
let rs_frac = Ratio::new(num, den);
let py_frac = rs_frac.into_pyobject(py).unwrap();
let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
assert_eq!(rs_frac, roundtripped);
})
}
#[test]
#[cfg(feature = "num-bigint")]
fn test_big_int_roundtrip(num in any::<f32>()) {
Python::with_gil(|py| {
let rs_frac = Ratio::from_float(num).unwrap();
let py_frac = rs_frac.clone().into_pyobject(py).unwrap();
let roundtripped: Ratio<BigInt> = py_frac.extract().unwrap();
assert_eq!(roundtripped, rs_frac);
})
}
}
#[test]
fn test_infinity() {
Python::with_gil(|py| {
let locals = PyDict::new(py);
let py_bound = py.run(
ffi::c_str!("import fractions\npy_frac = fractions.Fraction(\"Infinity\")"),
None,
Some(&locals),
);
assert!(py_bound.is_err());
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/hashbrown.rs | #![cfg(feature = "hashbrown")]
//! Conversions to and from [hashbrown](https://docs.rs/hashbrown/)’s
//! `HashMap` and `HashSet`.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! # change * to the latest versions
//! hashbrown = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"hashbrown\"] }")]
//! ```
//!
//! Note that you must use compatible versions of hashbrown and PyO3.
//! The required hashbrown version may vary based on the version of PyO3.
use crate::{
conversion::IntoPyObject,
types::{
any::PyAnyMethods,
dict::PyDictMethods,
frozenset::PyFrozenSetMethods,
set::{new_from_iter, try_new_from_iter, PySetMethods},
PyDict, PyFrozenSet, PySet,
},
Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::{cmp, hash};
#[allow(deprecated)]
impl<K, V, H> ToPyObject for hashbrown::HashMap<K, V, H>
where
K: hash::Hash + cmp::Eq + ToPyObject,
V: ToPyObject,
H: hash::BuildHasher,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.to_object(py), v.to_object(py)).unwrap();
}
dict.into_any().unbind()
}
}
#[allow(deprecated)]
impl<K, V, H> IntoPy<PyObject> for hashbrown::HashMap<K, V, H>
where
K: hash::Hash + cmp::Eq + IntoPy<PyObject>,
V: IntoPy<PyObject>,
H: hash::BuildHasher,
{
fn into_py(self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.into_py(py), v.into_py(py)).unwrap();
}
dict.into_any().unbind()
}
}
impl<'py, K, V, H> IntoPyObject<'py> for hashbrown::HashMap<K, V, H>
where
K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
V: IntoPyObject<'py>,
H: hash::BuildHasher,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
}
impl<'a, 'py, K, V, H> IntoPyObject<'py> for &'a hashbrown::HashMap<K, V, H>
where
&'a K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
&'a V: IntoPyObject<'py>,
H: hash::BuildHasher,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
}
impl<'py, K, V, S> FromPyObject<'py> for hashbrown::HashMap<K, V, S>
where
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
V: FromPyObject<'py>,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = hashbrown::HashMap::with_capacity_and_hasher(dict.len(), S::default());
for (k, v) in dict {
ret.insert(k.extract()?, v.extract()?);
}
Ok(ret)
}
}
#[allow(deprecated)]
impl<T> ToPyObject for hashbrown::HashSet<T>
where
T: hash::Hash + Eq + ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
new_from_iter(py, self)
.expect("Failed to create Python set from hashbrown::HashSet")
.into()
}
}
#[allow(deprecated)]
impl<K, S> IntoPy<PyObject> for hashbrown::HashSet<K, S>
where
K: IntoPy<PyObject> + Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn into_py(self, py: Python<'_>) -> PyObject {
new_from_iter(py, self.into_iter().map(|item| item.into_py(py)))
.expect("Failed to create Python set from hashbrown::HashSet")
.into()
}
}
impl<'py, K, H> IntoPyObject<'py> for hashbrown::HashSet<K, H>
where
K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
H: hash::BuildHasher,
{
type Target = PySet;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
try_new_from_iter(py, self)
}
}
impl<'a, 'py, K, H> IntoPyObject<'py> for &'a hashbrown::HashSet<K, H>
where
&'a K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
H: hash::BuildHasher,
{
type Target = PySet;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
try_new_from_iter(py, self)
}
}
impl<'py, K, S> FromPyObject<'py> for hashbrown::HashSet<K, S>
where
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
match ob.downcast::<PySet>() {
Ok(set) => set.iter().map(|any| any.extract()).collect(),
Err(err) => {
if let Ok(frozen_set) = ob.downcast::<PyFrozenSet>() {
frozen_set.iter().map(|any| any.extract()).collect()
} else {
Err(PyErr::from(err))
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::IntoPyDict;
#[test]
fn test_hashbrown_hashmap_into_pyobject() {
Python::with_gil(|py| {
let mut map = hashbrown::HashMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = (&map).into_pyobject(py).unwrap();
assert!(py_map.len() == 1);
assert!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
== 1
);
assert_eq!(map, py_map.extract().unwrap());
});
}
#[test]
fn test_hashbrown_hashmap_into_dict() {
Python::with_gil(|py| {
let mut map = hashbrown::HashMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = map.into_py_dict(py).unwrap();
assert_eq!(py_map.len(), 1);
assert_eq!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap(),
1
);
});
}
#[test]
fn test_extract_hashbrown_hashset() {
Python::with_gil(|py| {
let set = PySet::new(py, [1, 2, 3, 4, 5]).unwrap();
let hash_set: hashbrown::HashSet<usize> = set.extract().unwrap();
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
let set = PyFrozenSet::new(py, [1, 2, 3, 4, 5]).unwrap();
let hash_set: hashbrown::HashSet<usize> = set.extract().unwrap();
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
});
}
#[test]
fn test_hashbrown_hashset_into_pyobject() {
Python::with_gil(|py| {
let hs: hashbrown::HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hso = hs.clone().into_pyobject(py).unwrap();
assert_eq!(hs, hso.extract().unwrap());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/num_bigint.rs | #![cfg(feature = "num-bigint")]
//! Conversions to and from [num-bigint](https://docs.rs/num-bigint)’s [`BigInt`] and [`BigUint`] types.
//!
//! This is useful for converting Python integers when they may not fit in Rust's built-in integer types.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! num-bigint = "*"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"num-bigint\"] }")]
//! ```
//!
//! Note that you must use compatible versions of num-bigint and PyO3.
//! The required num-bigint version may vary based on the version of PyO3.
//!
//! ## Examples
//!
//! Using [`BigInt`] to correctly increment an arbitrary precision integer.
//! This is not possible with Rust's native integers if the Python integer is too large,
//! in which case it will fail its conversion and raise `OverflowError`.
//! ```rust
//! use num_bigint::BigInt;
//! use pyo3::prelude::*;
//!
//! #[pyfunction]
//! fn add_one(n: BigInt) -> BigInt {
//! n + 1
//! }
//!
//! #[pymodule]
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
//! m.add_function(wrap_pyfunction!(add_one, m)?)?;
//! Ok(())
//! }
//! ```
//!
//! Python code:
//! ```python
//! from my_module import add_one
//!
//! n = 1 << 1337
//! value = add_one(n)
//!
//! assert n + 1 == value
//! ```
#[cfg(Py_LIMITED_API)]
use crate::types::{bytes::PyBytesMethods, PyBytes};
use crate::{
conversion::IntoPyObject,
ffi,
instance::Bound,
types::{any::PyAnyMethods, PyInt},
FromPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use num_bigint::{BigInt, BigUint};
#[cfg(not(Py_LIMITED_API))]
use num_bigint::Sign;
// for identical functionality between BigInt and BigUint
macro_rules! bigint_conversion {
($rust_ty: ty, $is_signed: literal, $to_bytes: path) => {
#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
#[allow(deprecated)]
impl ToPyObject for $rust_ty {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
#[allow(deprecated)]
impl IntoPy<PyObject> for $rust_ty {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
impl<'py> IntoPyObject<'py> for $rust_ty {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(&self).into_pyobject(py)
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
impl<'py> IntoPyObject<'py> for &$rust_ty {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[cfg(not(Py_LIMITED_API))]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
use crate::ffi_ptr_ext::FfiPtrExt;
let bytes = $to_bytes(&self);
unsafe {
Ok(ffi::_PyLong_FromByteArray(
bytes.as_ptr().cast(),
bytes.len(),
1,
$is_signed.into(),
)
.assume_owned(py)
.downcast_into_unchecked())
}
}
#[cfg(Py_LIMITED_API)]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
use $crate::py_result_ext::PyResultExt;
let bytes = $to_bytes(&self);
let bytes_obj = PyBytes::new(py, &bytes);
let kwargs = if $is_signed {
let kwargs = crate::types::PyDict::new(py);
kwargs.set_item(crate::intern!(py, "signed"), true)?;
Some(kwargs)
} else {
None
};
unsafe {
py.get_type::<PyInt>()
.call_method("from_bytes", (bytes_obj, "little"), kwargs.as_ref())
.downcast_into_unchecked()
}
}
}
};
}
bigint_conversion!(BigUint, false, BigUint::to_bytes_le);
bigint_conversion!(BigInt, true, BigInt::to_signed_bytes_le);
#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
impl<'py> FromPyObject<'py> for BigInt {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<BigInt> {
let py = ob.py();
// fast path - checking for subclass of `int` just checks a bit in the type object
let num_owned: Py<PyInt>;
let num = if let Ok(long) = ob.downcast::<PyInt>() {
long
} else {
num_owned = unsafe { Py::from_owned_ptr_or_err(py, ffi::PyNumber_Index(ob.as_ptr()))? };
num_owned.bind(py)
};
#[cfg(not(Py_LIMITED_API))]
{
let mut buffer = int_to_u32_vec::<true>(num)?;
let sign = if buffer.last().copied().map_or(false, |last| last >> 31 != 0) {
// BigInt::new takes an unsigned array, so need to convert from two's complement
// flip all bits, 'subtract' 1 (by adding one to the unsigned array)
let mut elements = buffer.iter_mut();
for element in elements.by_ref() {
*element = (!*element).wrapping_add(1);
if *element != 0 {
// if the element didn't wrap over, no need to keep adding further ...
break;
}
}
// ... so just two's complement the rest
for element in elements {
*element = !*element;
}
Sign::Minus
} else {
Sign::Plus
};
Ok(BigInt::new(sign, buffer))
}
#[cfg(Py_LIMITED_API)]
{
let n_bits = int_n_bits(num)?;
if n_bits == 0 {
return Ok(BigInt::from(0isize));
}
let bytes = int_to_py_bytes(num, (n_bits + 8) / 8, true)?;
Ok(BigInt::from_signed_bytes_le(bytes.as_bytes()))
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))]
impl<'py> FromPyObject<'py> for BigUint {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<BigUint> {
let py = ob.py();
// fast path - checking for subclass of `int` just checks a bit in the type object
let num_owned: Py<PyInt>;
let num = if let Ok(long) = ob.downcast::<PyInt>() {
long
} else {
num_owned = unsafe { Py::from_owned_ptr_or_err(py, ffi::PyNumber_Index(ob.as_ptr()))? };
num_owned.bind(py)
};
#[cfg(not(Py_LIMITED_API))]
{
let buffer = int_to_u32_vec::<false>(num)?;
Ok(BigUint::new(buffer))
}
#[cfg(Py_LIMITED_API)]
{
let n_bits = int_n_bits(num)?;
if n_bits == 0 {
return Ok(BigUint::from(0usize));
}
let bytes = int_to_py_bytes(num, (n_bits + 7) / 8, false)?;
Ok(BigUint::from_bytes_le(bytes.as_bytes()))
}
}
}
#[cfg(not(any(Py_LIMITED_API, Py_3_13)))]
#[inline]
fn int_to_u32_vec<const SIGNED: bool>(long: &Bound<'_, PyInt>) -> PyResult<Vec<u32>> {
let mut buffer = Vec::new();
let n_bits = int_n_bits(long)?;
if n_bits == 0 {
return Ok(buffer);
}
let n_digits = if SIGNED {
(n_bits + 32) / 32
} else {
(n_bits + 31) / 32
};
buffer.reserve_exact(n_digits);
unsafe {
crate::err::error_on_minusone(
long.py(),
ffi::_PyLong_AsByteArray(
long.as_ptr().cast(),
buffer.as_mut_ptr() as *mut u8,
n_digits * 4,
1,
SIGNED.into(),
),
)?;
buffer.set_len(n_digits)
};
buffer
.iter_mut()
.for_each(|chunk| *chunk = u32::from_le(*chunk));
Ok(buffer)
}
#[cfg(all(not(Py_LIMITED_API), Py_3_13))]
#[inline]
fn int_to_u32_vec<const SIGNED: bool>(long: &Bound<'_, PyInt>) -> PyResult<Vec<u32>> {
let mut buffer = Vec::new();
let mut flags = ffi::Py_ASNATIVEBYTES_LITTLE_ENDIAN;
if !SIGNED {
flags |= ffi::Py_ASNATIVEBYTES_UNSIGNED_BUFFER | ffi::Py_ASNATIVEBYTES_REJECT_NEGATIVE;
}
let n_bytes =
unsafe { ffi::PyLong_AsNativeBytes(long.as_ptr().cast(), std::ptr::null_mut(), 0, flags) };
let n_bytes_unsigned: usize = n_bytes
.try_into()
.map_err(|_| crate::PyErr::fetch(long.py()))?;
if n_bytes == 0 {
return Ok(buffer);
}
// TODO: use div_ceil when MSRV >= 1.73
let n_digits = {
let adjust = if n_bytes % 4 == 0 { 0 } else { 1 };
(n_bytes_unsigned / 4) + adjust
};
buffer.reserve_exact(n_digits);
unsafe {
ffi::PyLong_AsNativeBytes(
long.as_ptr().cast(),
buffer.as_mut_ptr().cast(),
(n_digits * 4).try_into().unwrap(),
flags,
);
buffer.set_len(n_digits);
};
buffer
.iter_mut()
.for_each(|chunk| *chunk = u32::from_le(*chunk));
Ok(buffer)
}
#[cfg(Py_LIMITED_API)]
fn int_to_py_bytes<'py>(
long: &Bound<'py, PyInt>,
n_bytes: usize,
is_signed: bool,
) -> PyResult<Bound<'py, PyBytes>> {
use crate::intern;
let py = long.py();
let kwargs = if is_signed {
let kwargs = crate::types::PyDict::new(py);
kwargs.set_item(intern!(py, "signed"), true)?;
Some(kwargs)
} else {
None
};
let bytes = long.call_method(
intern!(py, "to_bytes"),
(n_bytes, intern!(py, "little")),
kwargs.as_ref(),
)?;
Ok(bytes.downcast_into()?)
}
#[inline]
#[cfg(any(not(Py_3_13), Py_LIMITED_API))]
fn int_n_bits(long: &Bound<'_, PyInt>) -> PyResult<usize> {
let py = long.py();
#[cfg(not(Py_LIMITED_API))]
{
// fast path
let n_bits = unsafe { ffi::_PyLong_NumBits(long.as_ptr()) };
if n_bits == (-1isize as usize) {
return Err(crate::PyErr::fetch(py));
}
Ok(n_bits)
}
#[cfg(Py_LIMITED_API)]
{
// slow path
long.call_method0(crate::intern!(py, "bit_length"))
.and_then(|any| any.extract())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::common::generate_unique_module_name;
use crate::types::{PyDict, PyModule};
use indoc::indoc;
use pyo3_ffi::c_str;
fn rust_fib<T>() -> impl Iterator<Item = T>
where
T: From<u16>,
for<'a> &'a T: std::ops::Add<Output = T>,
{
let mut f0: T = T::from(1);
let mut f1: T = T::from(1);
std::iter::from_fn(move || {
let f2 = &f0 + &f1;
Some(std::mem::replace(&mut f0, std::mem::replace(&mut f1, f2)))
})
}
fn python_fib(py: Python<'_>) -> impl Iterator<Item = Bound<'_, PyAny>> + '_ {
let mut f0 = 1i32.into_pyobject(py).unwrap().into_any();
let mut f1 = 1i32.into_pyobject(py).unwrap().into_any();
std::iter::from_fn(move || {
let f2 = f0.call_method1("__add__", (&f1,)).unwrap();
Some(std::mem::replace(&mut f0, std::mem::replace(&mut f1, f2)))
})
}
#[test]
fn convert_biguint() {
Python::with_gil(|py| {
// check the first 2000 numbers in the fibonacci sequence
for (py_result, rs_result) in python_fib(py).zip(rust_fib::<BigUint>()).take(2000) {
// Python -> Rust
assert_eq!(py_result.extract::<BigUint>().unwrap(), rs_result);
// Rust -> Python
assert!(py_result.eq(rs_result).unwrap());
}
});
}
#[test]
fn convert_bigint() {
Python::with_gil(|py| {
// check the first 2000 numbers in the fibonacci sequence
for (py_result, rs_result) in python_fib(py).zip(rust_fib::<BigInt>()).take(2000) {
// Python -> Rust
assert_eq!(py_result.extract::<BigInt>().unwrap(), rs_result);
// Rust -> Python
assert!(py_result.eq(&rs_result).unwrap());
// negate
let rs_result = rs_result * -1;
let py_result = py_result.call_method0("__neg__").unwrap();
// Python -> Rust
assert_eq!(py_result.extract::<BigInt>().unwrap(), rs_result);
// Rust -> Python
assert!(py_result.eq(rs_result).unwrap());
}
});
}
fn python_index_class(py: Python<'_>) -> Bound<'_, PyModule> {
let index_code = c_str!(indoc!(
r#"
class C:
def __init__(self, x):
self.x = x
def __index__(self):
return self.x
"#
));
PyModule::from_code(
py,
index_code,
c_str!("index.py"),
&generate_unique_module_name("index"),
)
.unwrap()
}
#[test]
fn convert_index_class() {
Python::with_gil(|py| {
let index = python_index_class(py);
let locals = PyDict::new(py);
locals.set_item("index", index).unwrap();
let ob = py
.eval(ffi::c_str!("index.C(10)"), None, Some(&locals))
.unwrap();
let _: BigInt = ob.extract().unwrap();
});
}
#[test]
fn handle_zero() {
Python::with_gil(|py| {
let zero: BigInt = 0i32.into_pyobject(py).unwrap().extract().unwrap();
assert_eq!(zero, BigInt::from(0));
})
}
/// `OverflowError` on converting Python int to BigInt, see issue #629
#[test]
fn check_overflow() {
Python::with_gil(|py| {
macro_rules! test {
($T:ty, $value:expr, $py:expr) => {
let value = $value;
println!("{}: {}", stringify!($T), value);
let python_value = value.clone().into_pyobject(py).unwrap();
let roundtrip_value = python_value.extract::<$T>().unwrap();
assert_eq!(value, roundtrip_value);
};
}
for i in 0..=256usize {
// test a lot of values to help catch other bugs too
test!(BigInt, BigInt::from(i), py);
test!(BigUint, BigUint::from(i), py);
test!(BigInt, -BigInt::from(i), py);
test!(BigInt, BigInt::from(1) << i, py);
test!(BigUint, BigUint::from(1u32) << i, py);
test!(BigInt, -BigInt::from(1) << i, py);
test!(BigInt, (BigInt::from(1) << i) + 1u32, py);
test!(BigUint, (BigUint::from(1u32) << i) + 1u32, py);
test!(BigInt, (-BigInt::from(1) << i) + 1u32, py);
test!(BigInt, (BigInt::from(1) << i) - 1u32, py);
test!(BigUint, (BigUint::from(1u32) << i) - 1u32, py);
test!(BigInt, (-BigInt::from(1) << i) - 1u32, py);
}
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/chrono_tz.rs | #![cfg(all(Py_3_9, feature = "chrono-tz"))]
//! Conversions to and from [chrono-tz](https://docs.rs/chrono-tz/)’s `Tz`.
//!
//! This feature requires at least Python 3.9.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! chrono-tz = "0.8"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"chrono-tz\"] }")]
//! ```
//!
//! Note that you must use compatible versions of chrono, chrono-tz and PyO3.
//! The required chrono version may vary based on the version of PyO3.
//!
//! # Example: Convert a `zoneinfo.ZoneInfo` to chrono-tz's `Tz`
//!
//! ```rust,no_run
//! use chrono_tz::Tz;
//! use pyo3::{Python, PyResult, IntoPyObject, types::PyAnyMethods};
//!
//! fn main() -> PyResult<()> {
//! pyo3::prepare_freethreaded_python();
//! Python::with_gil(|py| {
//! // Convert to Python
//! let py_tzinfo = Tz::Europe__Paris.into_pyobject(py)?;
//! // Convert back to Rust
//! assert_eq!(py_tzinfo.extract::<Tz>()?, Tz::Europe__Paris);
//! Ok(())
//! })
//! }
//! ```
use crate::conversion::IntoPyObject;
use crate::exceptions::PyValueError;
use crate::pybacked::PyBackedStr;
use crate::sync::GILOnceCell;
use crate::types::{any::PyAnyMethods, PyType};
use crate::{intern, Bound, FromPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use chrono_tz::Tz;
use std::str::FromStr;
#[allow(deprecated)]
impl ToPyObject for Tz {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Tz {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().unbind()
}
}
impl<'py> IntoPyObject<'py> for Tz {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
static ZONE_INFO: GILOnceCell<Py<PyType>> = GILOnceCell::new();
ZONE_INFO
.import(py, "zoneinfo", "ZoneInfo")
.and_then(|obj| obj.call1((self.name(),)))
}
}
impl<'py> IntoPyObject<'py> for &Tz {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for Tz {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Tz> {
Tz::from_str(
&ob.getattr(intern!(ob.py(), "key"))?
.extract::<PyBackedStr>()?,
)
.map_err(|e| PyValueError::new_err(e.to_string()))
}
}
#[cfg(all(test, not(windows)))] // Troubles loading timezones on Windows
mod tests {
use super::*;
#[test]
fn test_frompyobject() {
Python::with_gil(|py| {
assert_eq!(
new_zoneinfo(py, "Europe/Paris").extract::<Tz>().unwrap(),
Tz::Europe__Paris
);
assert_eq!(new_zoneinfo(py, "UTC").extract::<Tz>().unwrap(), Tz::UTC);
assert_eq!(
new_zoneinfo(py, "Etc/GMT-5").extract::<Tz>().unwrap(),
Tz::Etc__GMTMinus5
);
});
}
#[test]
#[cfg(not(Py_GIL_DISABLED))] // https://github.com/python/cpython/issues/116738#issuecomment-2404360445
fn test_into_pyobject() {
Python::with_gil(|py| {
let assert_eq = |l: Bound<'_, PyAny>, r: Bound<'_, PyAny>| {
assert!(l.eq(&r).unwrap(), "{:?} != {:?}", l, r);
};
assert_eq(
Tz::Europe__Paris.into_pyobject(py).unwrap(),
new_zoneinfo(py, "Europe/Paris"),
);
assert_eq(Tz::UTC.into_pyobject(py).unwrap(), new_zoneinfo(py, "UTC"));
assert_eq(
Tz::Etc__GMTMinus5.into_pyobject(py).unwrap(),
new_zoneinfo(py, "Etc/GMT-5"),
);
});
}
fn new_zoneinfo<'py>(py: Python<'py>, name: &str) -> Bound<'py, PyAny> {
zoneinfo_class(py).call1((name,)).unwrap()
}
fn zoneinfo_class(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("zoneinfo").unwrap().getattr("ZoneInfo").unwrap()
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/mod.rs | //! This module contains conversions between various Rust object and their representation in Python.
pub mod anyhow;
pub mod chrono;
pub mod chrono_tz;
pub mod either;
pub mod eyre;
pub mod hashbrown;
pub mod indexmap;
pub mod num_bigint;
pub mod num_complex;
pub mod num_rational;
pub mod rust_decimal;
pub mod serde;
pub mod smallvec;
mod std;
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/path.rs | use crate::conversion::IntoPyObject;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::instance::Bound;
use crate::types::any::PyAnyMethods;
use crate::types::PyString;
use crate::{ffi, FromPyObject, PyAny, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::borrow::Cow;
use std::convert::Infallible;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
#[allow(deprecated)]
impl ToPyObject for Path {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
// See osstr.rs for why there's no FromPyObject impl for &Path
impl FromPyObject<'_> for PathBuf {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> {
// We use os.fspath to get the underlying path as bytes or str
let path = unsafe { ffi::PyOS_FSPath(ob.as_ptr()).assume_owned_or_err(ob.py())? };
Ok(path.extract::<OsString>()?.into())
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for &Path {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for &Path {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
impl<'py> IntoPyObject<'py> for &&Path {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
#[allow(deprecated)]
impl ToPyObject for Cow<'_, Path> {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Cow<'_, Path> {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Cow<'_, Path> {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
impl<'py> IntoPyObject<'py> for &Cow<'_, Path> {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
#[allow(deprecated)]
impl ToPyObject for PathBuf {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for PathBuf {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for PathBuf {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for &PathBuf {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for &PathBuf {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
#[cfg(test)]
mod tests {
use crate::types::{PyAnyMethods, PyString, PyStringMethods};
use crate::{BoundObject, IntoPyObject, Python};
use std::borrow::Cow;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
#[test]
#[cfg(not(windows))]
fn test_non_utf8_conversion() {
Python::with_gil(|py| {
use std::ffi::OsStr;
#[cfg(not(target_os = "wasi"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "wasi")]
use std::os::wasi::ffi::OsStrExt;
// this is not valid UTF-8
let payload = &[250, 251, 252, 253, 254, 255, 0, 255];
let path = Path::new(OsStr::from_bytes(payload));
// do a roundtrip into Pythonland and back and compare
let py_str = path.into_pyobject(py).unwrap();
let path_2: PathBuf = py_str.extract().unwrap();
assert_eq!(path, path_2);
});
}
#[test]
fn test_intopyobject_roundtrip() {
Python::with_gil(|py| {
fn test_roundtrip<'py, T>(py: Python<'py>, obj: T)
where
T: IntoPyObject<'py> + AsRef<Path> + Debug + Clone,
T::Error: Debug,
{
let pyobject = obj.clone().into_pyobject(py).unwrap().into_any();
let pystring = pyobject.as_borrowed().downcast::<PyString>().unwrap();
assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
let roundtripped_obj: PathBuf = pystring.extract().unwrap();
assert_eq!(obj.as_ref(), roundtripped_obj.as_path());
}
let path = Path::new("Hello\0\n🐍");
test_roundtrip::<&Path>(py, path);
test_roundtrip::<Cow<'_, Path>>(py, Cow::Borrowed(path));
test_roundtrip::<Cow<'_, Path>>(py, Cow::Owned(path.to_path_buf()));
test_roundtrip::<PathBuf>(py, path.to_path_buf());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/array.rs | use crate::conversion::IntoPyObject;
use crate::instance::Bound;
use crate::types::any::PyAnyMethods;
use crate::types::PySequence;
use crate::{err::DowncastError, ffi, FromPyObject, Py, PyAny, PyObject, PyResult, Python};
use crate::{exceptions, PyErr};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[allow(deprecated)]
impl<T, const N: usize> IntoPy<PyObject> for [T; N]
where
T: IntoPy<PyObject>,
{
fn into_py(self, py: Python<'_>) -> PyObject {
unsafe {
let len = N as ffi::Py_ssize_t;
let ptr = ffi::PyList_New(len);
// We create the `Py` pointer here for two reasons:
// - panics if the ptr is null
// - its Drop cleans up the list if user code panics.
let list: Py<PyAny> = Py::from_owned_ptr(py, ptr);
for (i, obj) in (0..len).zip(self) {
let obj = obj.into_py(py).into_ptr();
#[cfg(not(Py_LIMITED_API))]
ffi::PyList_SET_ITEM(ptr, i, obj);
#[cfg(Py_LIMITED_API)]
ffi::PyList_SetItem(ptr, i, obj);
}
list
}
}
}
impl<'py, T, const N: usize> IntoPyObject<'py> for [T; N]
where
T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns [`[u8; N]`](std::array) into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
T::owned_sequence_into_pyobject(self, py, crate::conversion::private::Token)
}
}
impl<'a, 'py, T, const N: usize> IntoPyObject<'py> for &'a [T; N]
where
&'a T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_slice().into_pyobject(py)
}
}
#[allow(deprecated)]
impl<T, const N: usize> ToPyObject for [T; N]
where
T: ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
self.as_ref().to_object(py)
}
}
impl<'py, T, const N: usize> FromPyObject<'py> for [T; N]
where
T: FromPyObject<'py>,
{
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
create_array_from_obj(obj)
}
}
fn create_array_from_obj<'py, T, const N: usize>(obj: &Bound<'py, PyAny>) -> PyResult<[T; N]>
where
T: FromPyObject<'py>,
{
// Types that pass `PySequence_Check` usually implement enough of the sequence protocol
// to support this function and if not, we will only fail extraction safely.
let seq = unsafe {
if ffi::PySequence_Check(obj.as_ptr()) != 0 {
obj.downcast_unchecked::<PySequence>()
} else {
return Err(DowncastError::new(obj, "Sequence").into());
}
};
let seq_len = seq.len()?;
if seq_len != N {
return Err(invalid_sequence_length(N, seq_len));
}
array_try_from_fn(|idx| seq.get_item(idx).and_then(|any| any.extract()))
}
// TODO use std::array::try_from_fn, if that stabilises:
// (https://github.com/rust-lang/rust/issues/89379)
fn array_try_from_fn<E, F, T, const N: usize>(mut cb: F) -> Result<[T; N], E>
where
F: FnMut(usize) -> Result<T, E>,
{
// Helper to safely create arrays since the standard library doesn't
// provide one yet. Shouldn't be necessary in the future.
struct ArrayGuard<T, const N: usize> {
dst: *mut T,
initialized: usize,
}
impl<T, const N: usize> Drop for ArrayGuard<T, N> {
fn drop(&mut self) {
debug_assert!(self.initialized <= N);
let initialized_part = core::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
unsafe {
core::ptr::drop_in_place(initialized_part);
}
}
}
// [MaybeUninit<T>; N] would be "nicer" but is actually difficult to create - there are nightly
// APIs which would make this easier.
let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit();
let mut guard: ArrayGuard<T, N> = ArrayGuard {
dst: array.as_mut_ptr() as _,
initialized: 0,
};
unsafe {
let mut value_ptr = array.as_mut_ptr() as *mut T;
for i in 0..N {
core::ptr::write(value_ptr, cb(i)?);
value_ptr = value_ptr.offset(1);
guard.initialized += 1;
}
core::mem::forget(guard);
Ok(array.assume_init())
}
}
fn invalid_sequence_length(expected: usize, actual: usize) -> PyErr {
exceptions::PyValueError::new_err(format!(
"expected a sequence of length {} (got {})",
expected, actual
))
}
#[cfg(test)]
mod tests {
use std::{
panic,
sync::atomic::{AtomicUsize, Ordering},
};
use crate::{
conversion::IntoPyObject,
ffi,
types::{any::PyAnyMethods, PyBytes, PyBytesMethods},
};
use crate::{types::PyList, PyResult, Python};
#[test]
fn array_try_from_fn() {
static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
struct CountDrop;
impl Drop for CountDrop {
fn drop(&mut self) {
DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
let _ = catch_unwind_silent(move || {
let _: Result<[CountDrop; 4], ()> = super::array_try_from_fn(|idx| {
#[allow(clippy::manual_assert)]
if idx == 2 {
panic!("peek a boo");
}
Ok(CountDrop)
});
});
assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 2);
}
#[test]
fn test_extract_bytearray_to_array() {
Python::with_gil(|py| {
let v: [u8; 33] = py
.eval(
ffi::c_str!("bytearray(b'abcabcabcabcabcabcabcabcabcabcabc')"),
None,
None,
)
.unwrap()
.extract()
.unwrap();
assert!(&v == b"abcabcabcabcabcabcabcabcabcabcabc");
})
}
#[test]
fn test_extract_small_bytearray_to_array() {
Python::with_gil(|py| {
let v: [u8; 3] = py
.eval(ffi::c_str!("bytearray(b'abc')"), None, None)
.unwrap()
.extract()
.unwrap();
assert!(&v == b"abc");
});
}
#[test]
fn test_into_pyobject_array_conversion() {
Python::with_gil(|py| {
let array: [f32; 4] = [0.0, -16.0, 16.0, 42.0];
let pyobject = array.into_pyobject(py).unwrap();
let pylist = pyobject.downcast::<PyList>().unwrap();
assert_eq!(pylist.get_item(0).unwrap().extract::<f32>().unwrap(), 0.0);
assert_eq!(pylist.get_item(1).unwrap().extract::<f32>().unwrap(), -16.0);
assert_eq!(pylist.get_item(2).unwrap().extract::<f32>().unwrap(), 16.0);
assert_eq!(pylist.get_item(3).unwrap().extract::<f32>().unwrap(), 42.0);
});
}
#[test]
fn test_extract_invalid_sequence_length() {
Python::with_gil(|py| {
let v: PyResult<[u8; 3]> = py
.eval(ffi::c_str!("bytearray(b'abcdefg')"), None, None)
.unwrap()
.extract();
assert_eq!(
v.unwrap_err().to_string(),
"ValueError: expected a sequence of length 3 (got 7)"
);
})
}
#[test]
fn test_intopyobject_array_conversion() {
Python::with_gil(|py| {
let array: [f32; 4] = [0.0, -16.0, 16.0, 42.0];
let pylist = array
.into_pyobject(py)
.unwrap()
.downcast_into::<PyList>()
.unwrap();
assert_eq!(pylist.get_item(0).unwrap().extract::<f32>().unwrap(), 0.0);
assert_eq!(pylist.get_item(1).unwrap().extract::<f32>().unwrap(), -16.0);
assert_eq!(pylist.get_item(2).unwrap().extract::<f32>().unwrap(), 16.0);
assert_eq!(pylist.get_item(3).unwrap().extract::<f32>().unwrap(), 42.0);
});
}
#[test]
fn test_array_intopyobject_impl() {
Python::with_gil(|py| {
let bytes: [u8; 6] = *b"foobar";
let obj = bytes.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &bytes);
let nums: [u16; 4] = [0, 1, 2, 3];
let obj = nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
#[test]
fn test_extract_non_iterable_to_array() {
Python::with_gil(|py| {
let v = py.eval(ffi::c_str!("42"), None, None).unwrap();
v.extract::<i32>().unwrap();
v.extract::<[i32; 1]>().unwrap_err();
});
}
#[cfg(feature = "macros")]
#[test]
fn test_pyclass_intopy_array_conversion() {
#[crate::pyclass(crate = "crate")]
struct Foo;
Python::with_gil(|py| {
let array: [Foo; 8] = [Foo, Foo, Foo, Foo, Foo, Foo, Foo, Foo];
let list = array
.into_pyobject(py)
.unwrap()
.downcast_into::<PyList>()
.unwrap();
let _bound = list.get_item(4).unwrap().downcast::<Foo>().unwrap();
});
}
// https://stackoverflow.com/a/59211505
fn catch_unwind_silent<F, R>(f: F) -> std::thread::Result<R>
where
F: FnOnce() -> R + panic::UnwindSafe,
{
let prev_hook = panic::take_hook();
panic::set_hook(Box::new(|_| {}));
let result = panic::catch_unwind(f);
panic::set_hook(prev_hook);
result
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/map.rs | use std::{cmp, collections, hash};
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::{
conversion::IntoPyObject,
instance::Bound,
types::{any::PyAnyMethods, dict::PyDictMethods, PyDict},
FromPyObject, PyAny, PyErr, PyObject, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[allow(deprecated)]
impl<K, V, H> ToPyObject for collections::HashMap<K, V, H>
where
K: hash::Hash + cmp::Eq + ToPyObject,
V: ToPyObject,
H: hash::BuildHasher,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.to_object(py), v.to_object(py)).unwrap();
}
dict.into_any().unbind()
}
}
#[allow(deprecated)]
impl<K, V> ToPyObject for collections::BTreeMap<K, V>
where
K: cmp::Eq + ToPyObject,
V: ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.to_object(py), v.to_object(py)).unwrap();
}
dict.into_any().unbind()
}
}
#[allow(deprecated)]
impl<K, V, H> IntoPy<PyObject> for collections::HashMap<K, V, H>
where
K: hash::Hash + cmp::Eq + IntoPy<PyObject>,
V: IntoPy<PyObject>,
H: hash::BuildHasher,
{
fn into_py(self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.into_py(py), v.into_py(py)).unwrap();
}
dict.into_any().unbind()
}
}
impl<'py, K, V, H> IntoPyObject<'py> for collections::HashMap<K, V, H>
where
K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
V: IntoPyObject<'py>,
H: hash::BuildHasher,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::dict_of(K::type_output(), V::type_output())
}
}
impl<'a, 'py, K, V, H> IntoPyObject<'py> for &'a collections::HashMap<K, V, H>
where
&'a K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
&'a V: IntoPyObject<'py>,
K: 'a, // MSRV
V: 'a, // MSRV
H: hash::BuildHasher,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::dict_of(<&K>::type_output(), <&V>::type_output())
}
}
#[allow(deprecated)]
impl<K, V> IntoPy<PyObject> for collections::BTreeMap<K, V>
where
K: cmp::Eq + IntoPy<PyObject>,
V: IntoPy<PyObject>,
{
fn into_py(self, py: Python<'_>) -> PyObject {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k.into_py(py), v.into_py(py)).unwrap();
}
dict.into_any().unbind()
}
}
impl<'py, K, V> IntoPyObject<'py> for collections::BTreeMap<K, V>
where
K: IntoPyObject<'py> + cmp::Eq,
V: IntoPyObject<'py>,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::dict_of(K::type_output(), V::type_output())
}
}
impl<'a, 'py, K, V> IntoPyObject<'py> for &'a collections::BTreeMap<K, V>
where
&'a K: IntoPyObject<'py> + cmp::Eq,
&'a V: IntoPyObject<'py>,
K: 'a,
V: 'a,
{
type Target = PyDict;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let dict = PyDict::new(py);
for (k, v) in self {
dict.set_item(k, v)?;
}
Ok(dict)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::dict_of(<&K>::type_output(), <&V>::type_output())
}
}
impl<'py, K, V, S> FromPyObject<'py> for collections::HashMap<K, V, S>
where
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
V: FromPyObject<'py>,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = collections::HashMap::with_capacity_and_hasher(dict.len(), S::default());
for (k, v) in dict {
ret.insert(k.extract()?, v.extract()?);
}
Ok(ret)
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::mapping_of(K::type_input(), V::type_input())
}
}
impl<'py, K, V> FromPyObject<'py> for collections::BTreeMap<K, V>
where
K: FromPyObject<'py> + cmp::Ord,
V: FromPyObject<'py>,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
let dict = ob.downcast::<PyDict>()?;
let mut ret = collections::BTreeMap::new();
for (k, v) in dict {
ret.insert(k.extract()?, v.extract()?);
}
Ok(ret)
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::mapping_of(K::type_input(), V::type_input())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{BTreeMap, HashMap};
#[test]
fn test_hashmap_to_python() {
Python::with_gil(|py| {
let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = (&map).into_pyobject(py).unwrap();
assert!(py_map.len() == 1);
assert!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
== 1
);
assert_eq!(map, py_map.extract().unwrap());
});
}
#[test]
fn test_btreemap_to_python() {
Python::with_gil(|py| {
let mut map = BTreeMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = (&map).into_pyobject(py).unwrap();
assert!(py_map.len() == 1);
assert!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
== 1
);
assert_eq!(map, py_map.extract().unwrap());
});
}
#[test]
fn test_hashmap_into_python() {
Python::with_gil(|py| {
let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = map.into_pyobject(py).unwrap();
assert!(py_map.len() == 1);
assert!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
== 1
);
});
}
#[test]
fn test_btreemap_into_py() {
Python::with_gil(|py| {
let mut map = BTreeMap::<i32, i32>::new();
map.insert(1, 1);
let py_map = map.into_pyobject(py).unwrap();
assert!(py_map.len() == 1);
assert!(
py_map
.get_item(1)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
== 1
);
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/vec.rs | use crate::conversion::IntoPyObject;
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::types::list::new_from_iter;
use crate::{Bound, PyAny, PyErr, PyObject, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[allow(deprecated)]
impl<T> ToPyObject for [T]
where
T: ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
let mut iter = self.iter().map(|e| e.to_object(py));
let list = new_from_iter(py, &mut iter);
list.into()
}
}
#[allow(deprecated)]
impl<T> ToPyObject for Vec<T>
where
T: ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
self.as_slice().to_object(py)
}
}
#[allow(deprecated)]
impl<T> IntoPy<PyObject> for Vec<T>
where
T: IntoPy<PyObject>,
{
fn into_py(self, py: Python<'_>) -> PyObject {
let mut iter = self.into_iter().map(|e| e.into_py(py));
let list = new_from_iter(py, &mut iter);
list.into()
}
}
impl<'py, T> IntoPyObject<'py> for Vec<T>
where
T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns [`Vec<u8>`] into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
T::owned_sequence_into_pyobject(self, py, crate::conversion::private::Token)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::list_of(T::type_output())
}
}
impl<'a, 'py, T> IntoPyObject<'py> for &'a Vec<T>
where
&'a T: IntoPyObject<'py>,
T: 'a, // MSRV
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
// NB: we could actually not cast to `PyAny`, which would be nice for
// `&Vec<u8>`, but that'd be inconsistent with the `IntoPyObject` impl
// above which always returns a `PyAny` for `Vec<T>`.
self.as_slice().into_pyobject(py).map(Bound::into_any)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::list_of(<&T>::type_output())
}
}
#[cfg(test)]
mod tests {
use crate::conversion::IntoPyObject;
use crate::types::{PyAnyMethods, PyBytes, PyBytesMethods, PyList};
use crate::Python;
#[test]
fn test_vec_intopyobject_impl() {
Python::with_gil(|py| {
let bytes: Vec<u8> = b"foobar".to_vec();
let obj = bytes.clone().into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &bytes);
let nums: Vec<u16> = vec![0, 1, 2, 3];
let obj = nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
#[test]
fn test_vec_reference_intopyobject_impl() {
Python::with_gil(|py| {
let bytes: Vec<u8> = b"foobar".to_vec();
let obj = (&bytes).into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &bytes);
let nums: Vec<u16> = vec![0, 1, 2, 3];
let obj = (&nums).into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/set.rs | use std::{cmp, collections, hash};
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::{
conversion::IntoPyObject,
instance::Bound,
types::{
any::PyAnyMethods,
frozenset::PyFrozenSetMethods,
set::{new_from_iter, try_new_from_iter, PySetMethods},
PyFrozenSet, PySet,
},
FromPyObject, PyAny, PyErr, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[allow(deprecated)]
impl<T, S> ToPyObject for collections::HashSet<T, S>
where
T: hash::Hash + Eq + ToPyObject,
S: hash::BuildHasher + Default,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
new_from_iter(py, self)
.expect("Failed to create Python set from HashSet")
.into()
}
}
#[allow(deprecated)]
impl<T> ToPyObject for collections::BTreeSet<T>
where
T: hash::Hash + Eq + ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
new_from_iter(py, self)
.expect("Failed to create Python set from BTreeSet")
.into()
}
}
#[allow(deprecated)]
impl<K, S> IntoPy<PyObject> for collections::HashSet<K, S>
where
K: IntoPy<PyObject> + Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn into_py(self, py: Python<'_>) -> PyObject {
new_from_iter(py, self.into_iter().map(|item| item.into_py(py)))
.expect("Failed to create Python set from HashSet")
.into()
}
}
impl<'py, K, S> IntoPyObject<'py> for collections::HashSet<K, S>
where
K: IntoPyObject<'py> + Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
type Target = PySet;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
try_new_from_iter(py, self)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::set_of(K::type_output())
}
}
impl<'a, 'py, K, H> IntoPyObject<'py> for &'a collections::HashSet<K, H>
where
&'a K: IntoPyObject<'py> + Eq + hash::Hash,
K: 'a, // MSRV
H: hash::BuildHasher,
{
type Target = PySet;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
try_new_from_iter(py, self.iter())
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::set_of(<&K>::type_output())
}
}
impl<'py, K, S> FromPyObject<'py> for collections::HashSet<K, S>
where
K: FromPyObject<'py> + cmp::Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
match ob.downcast::<PySet>() {
Ok(set) => set.iter().map(|any| any.extract()).collect(),
Err(err) => {
if let Ok(frozen_set) = ob.downcast::<PyFrozenSet>() {
frozen_set.iter().map(|any| any.extract()).collect()
} else {
Err(PyErr::from(err))
}
}
}
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::set_of(K::type_input())
}
}
#[allow(deprecated)]
impl<K> IntoPy<PyObject> for collections::BTreeSet<K>
where
K: IntoPy<PyObject> + cmp::Ord,
{
fn into_py(self, py: Python<'_>) -> PyObject {
new_from_iter(py, self.into_iter().map(|item| item.into_py(py)))
.expect("Failed to create Python set from BTreeSet")
.into()
}
}
impl<'py, K> IntoPyObject<'py> for collections::BTreeSet<K>
where
K: IntoPyObject<'py> + cmp::Ord,
{
type Target = PySet;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
try_new_from_iter(py, self)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::set_of(K::type_output())
}
}
impl<'a, 'py, K> IntoPyObject<'py> for &'a collections::BTreeSet<K>
where
&'a K: IntoPyObject<'py> + cmp::Ord,
K: 'a,
{
type Target = PySet;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
try_new_from_iter(py, self.iter())
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::set_of(<&K>::type_output())
}
}
impl<'py, K> FromPyObject<'py> for collections::BTreeSet<K>
where
K: FromPyObject<'py> + cmp::Ord,
{
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
match ob.downcast::<PySet>() {
Ok(set) => set.iter().map(|any| any.extract()).collect(),
Err(err) => {
if let Ok(frozen_set) = ob.downcast::<PyFrozenSet>() {
frozen_set.iter().map(|any| any.extract()).collect()
} else {
Err(PyErr::from(err))
}
}
}
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::set_of(K::type_input())
}
}
#[cfg(test)]
mod tests {
use crate::types::{any::PyAnyMethods, PyFrozenSet, PySet};
use crate::{IntoPyObject, PyObject, Python};
use std::collections::{BTreeSet, HashSet};
#[test]
fn test_extract_hashset() {
Python::with_gil(|py| {
let set = PySet::new(py, [1, 2, 3, 4, 5]).unwrap();
let hash_set: HashSet<usize> = set.extract().unwrap();
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
let set = PyFrozenSet::new(py, [1, 2, 3, 4, 5]).unwrap();
let hash_set: HashSet<usize> = set.extract().unwrap();
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
});
}
#[test]
fn test_extract_btreeset() {
Python::with_gil(|py| {
let set = PySet::new(py, [1, 2, 3, 4, 5]).unwrap();
let hash_set: BTreeSet<usize> = set.extract().unwrap();
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
let set = PyFrozenSet::new(py, [1, 2, 3, 4, 5]).unwrap();
let hash_set: BTreeSet<usize> = set.extract().unwrap();
assert_eq!(hash_set, [1, 2, 3, 4, 5].iter().copied().collect());
});
}
#[test]
#[allow(deprecated)]
fn test_set_into_py() {
use crate::IntoPy;
Python::with_gil(|py| {
let bt: BTreeSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hs: HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let bto: PyObject = bt.clone().into_py(py);
let hso: PyObject = hs.clone().into_py(py);
assert_eq!(bt, bto.extract(py).unwrap());
assert_eq!(hs, hso.extract(py).unwrap());
});
}
#[test]
fn test_set_into_pyobject() {
Python::with_gil(|py| {
let bt: BTreeSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let hs: HashSet<u64> = [1, 2, 3, 4, 5].iter().cloned().collect();
let bto = (&bt).into_pyobject(py).unwrap();
let hso = (&hs).into_pyobject(py).unwrap();
assert_eq!(bt, bto.extract().unwrap());
assert_eq!(hs, hso.extract().unwrap());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/string.rs | use std::{borrow::Cow, convert::Infallible};
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::{
conversion::IntoPyObject,
instance::Bound,
types::{any::PyAnyMethods, string::PyStringMethods, PyString},
FromPyObject, Py, PyAny, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
/// Converts a Rust `str` to a Python object.
/// See `PyString::new` for details on the conversion.
#[allow(deprecated)]
impl ToPyObject for str {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for &str {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<Py<PyString>> for &str {
#[inline]
fn into_py(self, py: Python<'_>) -> Py<PyString> {
self.into_pyobject(py).unwrap().unbind()
}
}
impl<'py> IntoPyObject<'py> for &str {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(PyString::new(py, self))
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
impl<'py> IntoPyObject<'py> for &&str {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
/// Converts a Rust `Cow<'_, str>` to a Python object.
/// See `PyString::new` for details on the conversion.
#[allow(deprecated)]
impl ToPyObject for Cow<'_, str> {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Cow<'_, str> {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Cow<'_, str> {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
impl<'py> IntoPyObject<'py> for &Cow<'_, str> {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(&**self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
/// Converts a Rust `String` to a Python object.
/// See `PyString::new` for details on the conversion.
#[allow(deprecated)]
impl ToPyObject for String {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl ToPyObject for char {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for char {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for char {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let mut bytes = [0u8; 4];
Ok(PyString::new(py, self.encode_utf8(&mut bytes)))
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
impl<'py> IntoPyObject<'py> for &char {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for String {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for String {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(PyString::new(py, &self))
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("str")
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for &String {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for &String {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(PyString::new(py, self))
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<String>::type_output()
}
}
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for &'a str {
fn from_py_object_bound(ob: crate::Borrowed<'a, '_, PyAny>) -> PyResult<Self> {
ob.downcast::<PyString>()?.to_str()
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
<String as crate::FromPyObject>::type_input()
}
}
impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for Cow<'a, str> {
fn from_py_object_bound(ob: crate::Borrowed<'a, '_, PyAny>) -> PyResult<Self> {
ob.downcast::<PyString>()?.to_cow()
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
<String as crate::FromPyObject>::type_input()
}
}
/// Allows extracting strings from Python objects.
/// Accepts Python `str` and `unicode` objects.
impl FromPyObject<'_> for String {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
obj.downcast::<PyString>()?.to_cow().map(Cow::into_owned)
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
impl FromPyObject<'_> for char {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let s = obj.downcast::<PyString>()?.to_cow()?;
let mut iter = s.chars();
if let (Some(ch), None) = (iter.next(), iter.next()) {
Ok(ch)
} else {
Err(crate::exceptions::PyValueError::new_err(
"expected a string of length 1",
))
}
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
<String>::type_input()
}
}
#[cfg(test)]
mod tests {
use crate::types::any::PyAnyMethods;
use crate::{IntoPyObject, PyObject, Python};
use std::borrow::Cow;
#[test]
#[allow(deprecated)]
fn test_cow_into_py() {
use crate::IntoPy;
Python::with_gil(|py| {
let s = "Hello Python";
let py_string: PyObject = Cow::Borrowed(s).into_py(py);
assert_eq!(s, py_string.extract::<Cow<'_, str>>(py).unwrap());
let py_string: PyObject = Cow::<str>::Owned(s.into()).into_py(py);
assert_eq!(s, py_string.extract::<Cow<'_, str>>(py).unwrap());
})
}
#[test]
fn test_cow_into_pyobject() {
Python::with_gil(|py| {
let s = "Hello Python";
let py_string = Cow::Borrowed(s).into_pyobject(py).unwrap();
assert_eq!(s, py_string.extract::<Cow<'_, str>>().unwrap());
let py_string = Cow::<str>::Owned(s.into()).into_pyobject(py).unwrap();
assert_eq!(s, py_string.extract::<Cow<'_, str>>().unwrap());
})
}
#[test]
fn test_non_bmp() {
Python::with_gil(|py| {
let s = "\u{1F30F}";
let py_string = s.into_pyobject(py).unwrap();
assert_eq!(s, py_string.extract::<String>().unwrap());
})
}
#[test]
fn test_extract_str() {
Python::with_gil(|py| {
let s = "Hello Python";
let py_string = s.into_pyobject(py).unwrap();
let s2: Cow<'_, str> = py_string.extract().unwrap();
assert_eq!(s, s2);
})
}
#[test]
fn test_extract_char() {
Python::with_gil(|py| {
let ch = '😃';
let py_string = ch.into_pyobject(py).unwrap();
let ch2: char = py_string.extract().unwrap();
assert_eq!(ch, ch2);
})
}
#[test]
fn test_extract_char_err() {
Python::with_gil(|py| {
let s = "Hello Python";
let py_string = s.into_pyobject(py).unwrap();
let err: crate::PyResult<char> = py_string.extract();
assert!(err
.unwrap_err()
.to_string()
.contains("expected a string of length 1"));
})
}
#[test]
fn test_string_into_pyobject() {
Python::with_gil(|py| {
let s = "Hello Python";
let s2 = s.to_owned();
let s3 = &s2;
assert_eq!(
s,
s3.into_pyobject(py)
.unwrap()
.extract::<Cow<'_, str>>()
.unwrap()
);
assert_eq!(
s,
s2.into_pyobject(py)
.unwrap()
.extract::<Cow<'_, str>>()
.unwrap()
);
assert_eq!(
s,
s.into_pyobject(py)
.unwrap()
.extract::<Cow<'_, str>>()
.unwrap()
);
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/slice.rs | use std::borrow::Cow;
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::{
conversion::IntoPyObject,
types::{PyByteArray, PyByteArrayMethods, PyBytes},
Bound, Py, PyAny, PyErr, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[allow(deprecated)]
impl IntoPy<PyObject> for &[u8] {
fn into_py(self, py: Python<'_>) -> PyObject {
PyBytes::new(py, self).unbind().into()
}
}
impl<'a, 'py, T> IntoPyObject<'py> for &'a [T]
where
&'a T: IntoPyObject<'py>,
T: 'a, // MSRV
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns [`&[u8]`](std::slice) into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
<&T>::borrowed_sequence_into_pyobject(self, py, crate::conversion::private::Token)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::union_of(&[
TypeInfo::builtin("bytes"),
TypeInfo::list_of(<&T>::type_output()),
])
}
}
impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for &'a [u8] {
fn from_py_object_bound(obj: crate::Borrowed<'a, '_, PyAny>) -> PyResult<Self> {
Ok(obj.downcast::<PyBytes>()?.as_bytes())
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::builtin("bytes")
}
}
/// Special-purpose trait impl to efficiently handle both `bytes` and `bytearray`
///
/// If the source object is a `bytes` object, the `Cow` will be borrowed and
/// pointing into the source object, and no copying or heap allocations will happen.
/// If it is a `bytearray`, its contents will be copied to an owned `Cow`.
impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for Cow<'a, [u8]> {
fn from_py_object_bound(ob: crate::Borrowed<'a, '_, PyAny>) -> PyResult<Self> {
if let Ok(bytes) = ob.downcast::<PyBytes>() {
return Ok(Cow::Borrowed(bytes.as_bytes()));
}
let byte_array = ob.downcast::<PyByteArray>()?;
Ok(Cow::Owned(byte_array.to_vec()))
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
#[allow(deprecated)]
impl ToPyObject for Cow<'_, [u8]> {
fn to_object(&self, py: Python<'_>) -> Py<PyAny> {
PyBytes::new(py, self.as_ref()).into()
}
}
#[allow(deprecated)]
impl IntoPy<Py<PyAny>> for Cow<'_, [u8]> {
fn into_py(self, py: Python<'_>) -> Py<PyAny> {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py, T> IntoPyObject<'py> for Cow<'_, [T]>
where
T: Clone,
for<'a> &'a T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns `Cow<[u8]>` into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
<&T>::borrowed_sequence_into_pyobject(self.as_ref(), py, crate::conversion::private::Token)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use crate::{
conversion::IntoPyObject,
ffi,
types::{any::PyAnyMethods, PyBytes, PyBytesMethods, PyList},
Python,
};
#[test]
fn test_extract_bytes() {
Python::with_gil(|py| {
let py_bytes = py.eval(ffi::c_str!("b'Hello Python'"), None, None).unwrap();
let bytes: &[u8] = py_bytes.extract().unwrap();
assert_eq!(bytes, b"Hello Python");
});
}
#[test]
fn test_cow_impl() {
Python::with_gil(|py| {
let bytes = py.eval(ffi::c_str!(r#"b"foobar""#), None, None).unwrap();
let cow = bytes.extract::<Cow<'_, [u8]>>().unwrap();
assert_eq!(cow, Cow::<[u8]>::Borrowed(b"foobar"));
let byte_array = py
.eval(ffi::c_str!(r#"bytearray(b"foobar")"#), None, None)
.unwrap();
let cow = byte_array.extract::<Cow<'_, [u8]>>().unwrap();
assert_eq!(cow, Cow::<[u8]>::Owned(b"foobar".to_vec()));
let something_else_entirely = py.eval(ffi::c_str!("42"), None, None).unwrap();
something_else_entirely
.extract::<Cow<'_, [u8]>>()
.unwrap_err();
let cow = Cow::<[u8]>::Borrowed(b"foobar").into_pyobject(py).unwrap();
assert!(cow.is_instance_of::<PyBytes>());
let cow = Cow::<[u8]>::Owned(b"foobar".to_vec())
.into_pyobject(py)
.unwrap();
assert!(cow.is_instance_of::<PyBytes>());
});
}
#[test]
fn test_slice_intopyobject_impl() {
Python::with_gil(|py| {
let bytes: &[u8] = b"foobar";
let obj = bytes.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), bytes);
let nums: &[u16] = &[0, 1, 2, 3];
let obj = nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
#[test]
fn test_cow_intopyobject_impl() {
Python::with_gil(|py| {
let borrowed_bytes = Cow::<[u8]>::Borrowed(b"foobar");
let obj = borrowed_bytes.clone().into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &*borrowed_bytes);
let owned_bytes = Cow::<[u8]>::Owned(b"foobar".to_vec());
let obj = owned_bytes.clone().into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &*owned_bytes);
let borrowed_nums = Cow::<[u16]>::Borrowed(&[0, 1, 2, 3]);
let obj = borrowed_nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
let owned_nums = Cow::<[u16]>::Owned(vec![0, 1, 2, 3]);
let obj = owned_nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/cell.rs | use std::cell::Cell;
use crate::{
conversion::IntoPyObject, types::any::PyAnyMethods, Bound, FromPyObject, PyAny, PyObject,
PyResult, Python,
};
#[allow(deprecated)]
impl<T: Copy + crate::ToPyObject> crate::ToPyObject for Cell<T> {
fn to_object(&self, py: Python<'_>) -> PyObject {
self.get().to_object(py)
}
}
#[allow(deprecated)]
impl<T: Copy + crate::IntoPy<PyObject>> crate::IntoPy<PyObject> for Cell<T> {
fn into_py(self, py: Python<'_>) -> PyObject {
self.get().into_py(py)
}
}
impl<'py, T: Copy + IntoPyObject<'py>> IntoPyObject<'py> for Cell<T> {
type Target = T::Target;
type Output = T::Output;
type Error = T::Error;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.get().into_pyobject(py)
}
}
impl<'py, T: Copy + IntoPyObject<'py>> IntoPyObject<'py> for &Cell<T> {
type Target = T::Target;
type Output = T::Output;
type Error = T::Error;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.get().into_pyobject(py)
}
}
impl<'py, T: FromPyObject<'py>> FromPyObject<'py> for Cell<T> {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
ob.extract().map(Cell::new)
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/osstr.rs | use crate::conversion::IntoPyObject;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::instance::Bound;
use crate::types::any::PyAnyMethods;
use crate::types::PyString;
use crate::{ffi, FromPyObject, PyAny, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::borrow::Cow;
use std::convert::Infallible;
use std::ffi::{OsStr, OsString};
#[allow(deprecated)]
impl ToPyObject for OsStr {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for &OsStr {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
// If the string is UTF-8, take the quick and easy shortcut
if let Some(valid_utf8_path) = self.to_str() {
return valid_utf8_path.into_pyobject(py);
}
// All targets besides windows support the std::os::unix::ffi::OsStrExt API:
// https://doc.rust-lang.org/src/std/sys_common/mod.rs.html#59
#[cfg(not(windows))]
{
#[cfg(target_os = "wasi")]
let bytes = std::os::wasi::ffi::OsStrExt::as_bytes(self);
#[cfg(not(target_os = "wasi"))]
let bytes = std::os::unix::ffi::OsStrExt::as_bytes(self);
let ptr = bytes.as_ptr().cast();
let len = bytes.len() as ffi::Py_ssize_t;
unsafe {
// DecodeFSDefault automatically chooses an appropriate decoding mechanism to
// parse os strings losslessly (i.e. surrogateescape most of the time)
Ok(ffi::PyUnicode_DecodeFSDefaultAndSize(ptr, len)
.assume_owned(py)
.downcast_into_unchecked::<PyString>())
}
}
#[cfg(windows)]
{
let wstr: Vec<u16> = std::os::windows::ffi::OsStrExt::encode_wide(self).collect();
unsafe {
// This will not panic because the data from encode_wide is well-formed Windows
// string data
Ok(
ffi::PyUnicode_FromWideChar(wstr.as_ptr(), wstr.len() as ffi::Py_ssize_t)
.assume_owned(py)
.downcast_into_unchecked::<PyString>(),
)
}
}
}
}
impl<'py> IntoPyObject<'py> for &&OsStr {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
// There's no FromPyObject implementation for &OsStr because albeit possible on Unix, this would
// be impossible to implement on Windows. Hence it's omitted entirely
impl FromPyObject<'_> for OsString {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> {
let pystring = ob.downcast::<PyString>()?;
#[cfg(not(windows))]
{
// Decode from Python's lossless bytes string representation back into raw bytes
let fs_encoded_bytes = unsafe {
crate::Py::<crate::types::PyBytes>::from_owned_ptr(
ob.py(),
ffi::PyUnicode_EncodeFSDefault(pystring.as_ptr()),
)
};
// Create an OsStr view into the raw bytes from Python
#[cfg(target_os = "wasi")]
let os_str: &OsStr =
std::os::wasi::ffi::OsStrExt::from_bytes(fs_encoded_bytes.as_bytes(ob.py()));
#[cfg(not(target_os = "wasi"))]
let os_str: &OsStr =
std::os::unix::ffi::OsStrExt::from_bytes(fs_encoded_bytes.as_bytes(ob.py()));
Ok(os_str.to_os_string())
}
#[cfg(windows)]
{
use crate::types::string::PyStringMethods;
// Take the quick and easy shortcut if UTF-8
if let Ok(utf8_string) = pystring.to_cow() {
return Ok(utf8_string.into_owned().into());
}
// Get an owned allocated wide char buffer from PyString, which we have to deallocate
// ourselves
let size =
unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), std::ptr::null_mut(), 0) };
crate::err::error_on_minusone(ob.py(), size)?;
let mut buffer = vec![0; size as usize];
let bytes_read =
unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), buffer.as_mut_ptr(), size) };
assert_eq!(bytes_read, size);
// Copy wide char buffer into OsString
let os_string = std::os::windows::ffi::OsStringExt::from_wide(&buffer);
Ok(os_string)
}
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for &'_ OsStr {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl ToPyObject for Cow<'_, OsStr> {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Cow<'_, OsStr> {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Cow<'_, OsStr> {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl<'py> IntoPyObject<'py> for &Cow<'_, OsStr> {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(&**self).into_pyobject(py)
}
}
#[allow(deprecated)]
impl ToPyObject for OsString {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for OsString {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for OsString {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for &OsString {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for &OsString {
type Target = PyString;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
}
}
#[cfg(test)]
mod tests {
use crate::types::{PyAnyMethods, PyString, PyStringMethods};
use crate::{BoundObject, IntoPyObject, Python};
use std::fmt::Debug;
use std::{
borrow::Cow,
ffi::{OsStr, OsString},
};
#[test]
#[cfg(not(windows))]
fn test_non_utf8_conversion() {
Python::with_gil(|py| {
#[cfg(not(target_os = "wasi"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "wasi")]
use std::os::wasi::ffi::OsStrExt;
// this is not valid UTF-8
let payload = &[250, 251, 252, 253, 254, 255, 0, 255];
let os_str = OsStr::from_bytes(payload);
// do a roundtrip into Pythonland and back and compare
let py_str = os_str.into_pyobject(py).unwrap();
let os_str_2: OsString = py_str.extract().unwrap();
assert_eq!(os_str, os_str_2);
});
}
#[test]
fn test_intopyobject_roundtrip() {
Python::with_gil(|py| {
fn test_roundtrip<'py, T>(py: Python<'py>, obj: T)
where
T: IntoPyObject<'py> + AsRef<OsStr> + Debug + Clone,
T::Error: Debug,
{
let pyobject = obj.clone().into_pyobject(py).unwrap().into_any();
let pystring = pyobject.as_borrowed().downcast::<PyString>().unwrap();
assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
let roundtripped_obj: OsString = pystring.extract().unwrap();
assert_eq!(obj.as_ref(), roundtripped_obj.as_os_str());
}
let os_str = OsStr::new("Hello\0\n🐍");
test_roundtrip::<&OsStr>(py, os_str);
test_roundtrip::<Cow<'_, OsStr>>(py, Cow::Borrowed(os_str));
test_roundtrip::<Cow<'_, OsStr>>(py, Cow::Owned(os_str.to_os_string()));
test_roundtrip::<OsString>(py, os_str.to_os_string());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/ipaddr.rs | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use crate::conversion::IntoPyObject;
use crate::exceptions::PyValueError;
use crate::instance::Bound;
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
use crate::types::string::PyStringMethods;
use crate::types::PyType;
use crate::{intern, FromPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
impl FromPyObject<'_> for IpAddr {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
match obj.getattr(intern!(obj.py(), "packed")) {
Ok(packed) => {
if let Ok(packed) = packed.extract::<[u8; 4]>() {
Ok(IpAddr::V4(Ipv4Addr::from(packed)))
} else if let Ok(packed) = packed.extract::<[u8; 16]>() {
Ok(IpAddr::V6(Ipv6Addr::from(packed)))
} else {
Err(PyValueError::new_err("invalid packed length"))
}
}
Err(_) => {
// We don't have a .packed attribute, so we try to construct an IP from str().
obj.str()?.to_cow()?.parse().map_err(PyValueError::new_err)
}
}
}
}
#[allow(deprecated)]
impl ToPyObject for Ipv4Addr {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().unbind()
}
}
impl<'py> IntoPyObject<'py> for Ipv4Addr {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
static IPV4_ADDRESS: GILOnceCell<Py<PyType>> = GILOnceCell::new();
IPV4_ADDRESS
.import(py, "ipaddress", "IPv4Address")?
.call1((u32::from_be_bytes(self.octets()),))
}
}
impl<'py> IntoPyObject<'py> for &Ipv4Addr {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
#[allow(deprecated)]
impl ToPyObject for Ipv6Addr {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().unbind()
}
}
impl<'py> IntoPyObject<'py> for Ipv6Addr {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
static IPV6_ADDRESS: GILOnceCell<Py<PyType>> = GILOnceCell::new();
IPV6_ADDRESS
.import(py, "ipaddress", "IPv6Address")?
.call1((u128::from_be_bytes(self.octets()),))
}
}
impl<'py> IntoPyObject<'py> for &Ipv6Addr {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
#[allow(deprecated)]
impl ToPyObject for IpAddr {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for IpAddr {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().unbind()
}
}
impl<'py> IntoPyObject<'py> for IpAddr {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
match self {
IpAddr::V4(ip) => ip.into_pyobject(py),
IpAddr::V6(ip) => ip.into_pyobject(py),
}
}
}
impl<'py> IntoPyObject<'py> for &IpAddr {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
#[cfg(test)]
mod test_ipaddr {
use std::str::FromStr;
use crate::types::PyString;
use super::*;
#[test]
fn test_roundtrip() {
Python::with_gil(|py| {
fn roundtrip(py: Python<'_>, ip: &str) {
let ip = IpAddr::from_str(ip).unwrap();
let py_cls = if ip.is_ipv4() {
"IPv4Address"
} else {
"IPv6Address"
};
let pyobj = ip.into_pyobject(py).unwrap();
let repr = pyobj.repr().unwrap();
let repr = repr.to_string_lossy();
assert_eq!(repr, format!("{}('{}')", py_cls, ip));
let ip2: IpAddr = pyobj.extract().unwrap();
assert_eq!(ip, ip2);
}
roundtrip(py, "127.0.0.1");
roundtrip(py, "::1");
roundtrip(py, "0.0.0.0");
});
}
#[test]
fn test_from_pystring() {
Python::with_gil(|py| {
let py_str = PyString::new(py, "0:0:0:0:0:0:0:1");
let ip: IpAddr = py_str.extract().unwrap();
assert_eq!(ip, IpAddr::from_str("::1").unwrap());
let py_str = PyString::new(py, "invalid");
assert!(py_str.extract::<IpAddr>().is_err());
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/num.rs | use crate::conversion::private::Reference;
use crate::conversion::IntoPyObject;
use crate::ffi_ptr_ext::FfiPtrExt;
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::types::any::PyAnyMethods;
use crate::types::{PyBytes, PyInt};
use crate::{exceptions, ffi, Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::convert::Infallible;
use std::num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
};
use std::os::raw::c_long;
macro_rules! int_fits_larger_int {
($rust_type:ty, $larger_type:ty) => {
#[allow(deprecated)]
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for $rust_type {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for $rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(self as $larger_type).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<$larger_type>::type_output()
}
}
impl<'py> IntoPyObject<'py> for &$rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
<$larger_type>::type_output()
}
}
impl FromPyObject<'_> for $rust_type {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let val: $larger_type = obj.extract()?;
<$rust_type>::try_from(val)
.map_err(|e| exceptions::PyOverflowError::new_err(e.to_string()))
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
<$larger_type>::type_input()
}
}
};
}
macro_rules! extract_int {
($obj:ident, $error_val:expr, $pylong_as:expr) => {
extract_int!($obj, $error_val, $pylong_as, false)
};
($obj:ident, $error_val:expr, $pylong_as:expr, $force_index_call: literal) => {
// In python 3.8+ `PyLong_AsLong` and friends takes care of calling `PyNumber_Index`,
// however 3.8 & 3.9 do lossy conversion of floats, hence we only use the
// simplest logic for 3.10+ where that was fixed - python/cpython#82180.
// `PyLong_AsUnsignedLongLong` does not call `PyNumber_Index`, hence the `force_index_call` argument
// See https://github.com/PyO3/pyo3/pull/3742 for detials
if cfg!(Py_3_10) && !$force_index_call {
err_if_invalid_value($obj.py(), $error_val, unsafe { $pylong_as($obj.as_ptr()) })
} else if let Ok(long) = $obj.downcast::<crate::types::PyInt>() {
// fast path - checking for subclass of `int` just checks a bit in the type $object
err_if_invalid_value($obj.py(), $error_val, unsafe { $pylong_as(long.as_ptr()) })
} else {
unsafe {
let num = ffi::PyNumber_Index($obj.as_ptr()).assume_owned_or_err($obj.py())?;
err_if_invalid_value($obj.py(), $error_val, $pylong_as(num.as_ptr()))
}
}
};
}
macro_rules! int_convert_u64_or_i64 {
($rust_type:ty, $pylong_from_ll_or_ull:expr, $pylong_as_ll_or_ull:expr, $force_index_call:literal) => {
#[allow(deprecated)]
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for $rust_type {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for $rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
unsafe {
Ok($pylong_from_ll_or_ull(self)
.assume_owned(py)
.downcast_into_unchecked())
}
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl<'py> IntoPyObject<'py> for &$rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl FromPyObject<'_> for $rust_type {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<$rust_type> {
extract_int!(obj, !0, $pylong_as_ll_or_ull, $force_index_call)
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
};
}
macro_rules! int_fits_c_long {
($rust_type:ty) => {
#[allow(deprecated)]
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for $rust_type {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for $rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
unsafe {
Ok(ffi::PyLong_FromLong(self as c_long)
.assume_owned(py)
.downcast_into_unchecked())
}
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl<'py> IntoPyObject<'py> for &$rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl<'py> FromPyObject<'py> for $rust_type {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let val: c_long = extract_int!(obj, -1, ffi::PyLong_AsLong)?;
<$rust_type>::try_from(val)
.map_err(|e| exceptions::PyOverflowError::new_err(e.to_string()))
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
};
}
#[allow(deprecated)]
impl ToPyObject for u8 {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for u8 {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for u8 {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
unsafe {
Ok(ffi::PyLong_FromLong(self as c_long)
.assume_owned(py)
.downcast_into_unchecked())
}
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
#[inline]
fn owned_sequence_into_pyobject<I>(
iter: I,
py: Python<'py>,
_: crate::conversion::private::Token,
) -> Result<Bound<'py, PyAny>, PyErr>
where
I: AsRef<[u8]>,
{
Ok(PyBytes::new(py, iter.as_ref()).into_any())
}
}
impl<'py> IntoPyObject<'py> for &'_ u8 {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
u8::into_pyobject(*self, py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
#[inline]
fn borrowed_sequence_into_pyobject<I>(
iter: I,
py: Python<'py>,
_: crate::conversion::private::Token,
) -> Result<Bound<'py, PyAny>, PyErr>
where
// I: AsRef<[u8]>, but the compiler needs it expressed via the trait for some reason
I: AsRef<[<Self as Reference>::BaseType]>,
{
Ok(PyBytes::new(py, iter.as_ref()).into_any())
}
}
impl FromPyObject<'_> for u8 {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let val: c_long = extract_int!(obj, -1, ffi::PyLong_AsLong)?;
u8::try_from(val).map_err(|e| exceptions::PyOverflowError::new_err(e.to_string()))
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
int_fits_c_long!(i8);
int_fits_c_long!(i16);
int_fits_c_long!(u16);
int_fits_c_long!(i32);
// If c_long is 64-bits, we can use more types with int_fits_c_long!:
#[cfg(all(target_pointer_width = "64", not(target_os = "windows")))]
int_fits_c_long!(u32);
#[cfg(any(target_pointer_width = "32", target_os = "windows"))]
int_fits_larger_int!(u32, u64);
#[cfg(all(target_pointer_width = "64", not(target_os = "windows")))]
int_fits_c_long!(i64);
// manual implementation for i64 on systems with 32-bit long
#[cfg(any(target_pointer_width = "32", target_os = "windows"))]
int_convert_u64_or_i64!(i64, ffi::PyLong_FromLongLong, ffi::PyLong_AsLongLong, false);
#[cfg(all(target_pointer_width = "64", not(target_os = "windows")))]
int_fits_c_long!(isize);
#[cfg(any(target_pointer_width = "32", target_os = "windows"))]
int_fits_larger_int!(isize, i64);
int_fits_larger_int!(usize, u64);
// u64 has a manual implementation as it never fits into signed long
int_convert_u64_or_i64!(
u64,
ffi::PyLong_FromUnsignedLongLong,
ffi::PyLong_AsUnsignedLongLong,
true
);
#[cfg(all(not(Py_LIMITED_API), not(GraalPy)))]
mod fast_128bit_int_conversion {
use super::*;
// for 128bit Integers
macro_rules! int_convert_128 {
($rust_type: ty, $is_signed: literal) => {
#[allow(deprecated)]
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for $rust_type {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for $rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
#[cfg(not(Py_3_13))]
{
let bytes = self.to_le_bytes();
unsafe {
Ok(ffi::_PyLong_FromByteArray(
bytes.as_ptr().cast(),
bytes.len(),
1,
$is_signed.into(),
)
.assume_owned(py)
.downcast_into_unchecked())
}
}
#[cfg(Py_3_13)]
{
let bytes = self.to_ne_bytes();
if $is_signed {
unsafe {
Ok(ffi::PyLong_FromNativeBytes(
bytes.as_ptr().cast(),
bytes.len(),
ffi::Py_ASNATIVEBYTES_NATIVE_ENDIAN,
)
.assume_owned(py)
.downcast_into_unchecked())
}
} else {
unsafe {
Ok(ffi::PyLong_FromUnsignedNativeBytes(
bytes.as_ptr().cast(),
bytes.len(),
ffi::Py_ASNATIVEBYTES_NATIVE_ENDIAN,
)
.assume_owned(py)
.downcast_into_unchecked())
}
}
}
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl<'py> IntoPyObject<'py> for &$rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl FromPyObject<'_> for $rust_type {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<$rust_type> {
let num =
unsafe { ffi::PyNumber_Index(ob.as_ptr()).assume_owned_or_err(ob.py())? };
let mut buffer = [0u8; std::mem::size_of::<$rust_type>()];
#[cfg(not(Py_3_13))]
{
crate::err::error_on_minusone(ob.py(), unsafe {
ffi::_PyLong_AsByteArray(
num.as_ptr() as *mut ffi::PyLongObject,
buffer.as_mut_ptr(),
buffer.len(),
1,
$is_signed.into(),
)
})?;
Ok(<$rust_type>::from_le_bytes(buffer))
}
#[cfg(Py_3_13)]
{
let mut flags = ffi::Py_ASNATIVEBYTES_NATIVE_ENDIAN;
if !$is_signed {
flags |= ffi::Py_ASNATIVEBYTES_UNSIGNED_BUFFER
| ffi::Py_ASNATIVEBYTES_REJECT_NEGATIVE;
}
let actual_size: usize = unsafe {
ffi::PyLong_AsNativeBytes(
num.as_ptr(),
buffer.as_mut_ptr().cast(),
buffer
.len()
.try_into()
.expect("length of buffer fits in Py_ssize_t"),
flags,
)
}
.try_into()
.map_err(|_| PyErr::fetch(ob.py()))?;
if actual_size as usize > buffer.len() {
return Err(crate::exceptions::PyOverflowError::new_err(
"Python int larger than 128 bits",
));
}
Ok(<$rust_type>::from_ne_bytes(buffer))
}
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
};
}
int_convert_128!(i128, true);
int_convert_128!(u128, false);
}
// For ABI3 we implement the conversion manually.
#[cfg(any(Py_LIMITED_API, GraalPy))]
mod slow_128bit_int_conversion {
use super::*;
const SHIFT: usize = 64;
// for 128bit Integers
macro_rules! int_convert_128 {
($rust_type: ty, $half_type: ty) => {
#[allow(deprecated)]
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for $rust_type {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for $rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let lower = (self as u64).into_pyobject(py)?;
let upper = ((self >> SHIFT) as $half_type).into_pyobject(py)?;
let shift = SHIFT.into_pyobject(py)?;
unsafe {
let shifted =
ffi::PyNumber_Lshift(upper.as_ptr(), shift.as_ptr()).assume_owned(py);
Ok(ffi::PyNumber_Or(shifted.as_ptr(), lower.as_ptr())
.assume_owned(py)
.downcast_into_unchecked())
}
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl<'py> IntoPyObject<'py> for &$rust_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl FromPyObject<'_> for $rust_type {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<$rust_type> {
let py = ob.py();
unsafe {
let lower = err_if_invalid_value(
py,
-1 as _,
ffi::PyLong_AsUnsignedLongLongMask(ob.as_ptr()),
)? as $rust_type;
let shift = SHIFT.into_pyobject(py)?;
let shifted = PyObject::from_owned_ptr_or_err(
py,
ffi::PyNumber_Rshift(ob.as_ptr(), shift.as_ptr()),
)?;
let upper: $half_type = shifted.extract(py)?;
Ok((<$rust_type>::from(upper) << SHIFT) | lower)
}
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
};
}
int_convert_128!(i128, i64);
int_convert_128!(u128, u64);
}
fn err_if_invalid_value<T: PartialEq>(
py: Python<'_>,
invalid_value: T,
actual_value: T,
) -> PyResult<T> {
if actual_value == invalid_value {
if let Some(err) = PyErr::take(py) {
return Err(err);
}
}
Ok(actual_value)
}
macro_rules! nonzero_int_impl {
($nonzero_type:ty, $primitive_type:ty) => {
#[allow(deprecated)]
impl ToPyObject for $nonzero_type {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for $nonzero_type {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for $nonzero_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.get().into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl<'py> IntoPyObject<'py> for &$nonzero_type {
type Target = PyInt;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::builtin("int")
}
}
impl FromPyObject<'_> for $nonzero_type {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let val: $primitive_type = obj.extract()?;
<$nonzero_type>::try_from(val)
.map_err(|_| exceptions::PyValueError::new_err("invalid zero value"))
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
<$primitive_type>::type_input()
}
}
};
}
nonzero_int_impl!(NonZeroI8, i8);
nonzero_int_impl!(NonZeroI16, i16);
nonzero_int_impl!(NonZeroI32, i32);
nonzero_int_impl!(NonZeroI64, i64);
nonzero_int_impl!(NonZeroI128, i128);
nonzero_int_impl!(NonZeroIsize, isize);
nonzero_int_impl!(NonZeroU8, u8);
nonzero_int_impl!(NonZeroU16, u16);
nonzero_int_impl!(NonZeroU32, u32);
nonzero_int_impl!(NonZeroU64, u64);
nonzero_int_impl!(NonZeroU128, u128);
nonzero_int_impl!(NonZeroUsize, usize);
#[cfg(test)]
mod test_128bit_integers {
use super::*;
#[cfg(not(target_arch = "wasm32"))]
use crate::types::PyDict;
#[cfg(not(target_arch = "wasm32"))]
use crate::types::dict::PyDictMethods;
#[cfg(not(target_arch = "wasm32"))]
use proptest::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use std::ffi::CString;
#[cfg(not(target_arch = "wasm32"))]
proptest! {
#[test]
fn test_i128_roundtrip(x: i128) {
Python::with_gil(|py| {
let x_py = x.into_pyobject(py).unwrap();
let locals = PyDict::new(py);
locals.set_item("x_py", &x_py).unwrap();
py.run(&CString::new(format!("assert x_py == {}", x)).unwrap(), None, Some(&locals)).unwrap();
let roundtripped: i128 = x_py.extract().unwrap();
assert_eq!(x, roundtripped);
})
}
#[test]
fn test_nonzero_i128_roundtrip(
x in any::<i128>()
.prop_filter("Values must not be 0", |x| x != &0)
.prop_map(|x| NonZeroI128::new(x).unwrap())
) {
Python::with_gil(|py| {
let x_py = x.into_pyobject(py).unwrap();
let locals = PyDict::new(py);
locals.set_item("x_py", &x_py).unwrap();
py.run(&CString::new(format!("assert x_py == {}", x)).unwrap(), None, Some(&locals)).unwrap();
let roundtripped: NonZeroI128 = x_py.extract().unwrap();
assert_eq!(x, roundtripped);
})
}
}
#[cfg(not(target_arch = "wasm32"))]
proptest! {
#[test]
fn test_u128_roundtrip(x: u128) {
Python::with_gil(|py| {
let x_py = x.into_pyobject(py).unwrap();
let locals = PyDict::new(py);
locals.set_item("x_py", &x_py).unwrap();
py.run(&CString::new(format!("assert x_py == {}", x)).unwrap(), None, Some(&locals)).unwrap();
let roundtripped: u128 = x_py.extract().unwrap();
assert_eq!(x, roundtripped);
})
}
#[test]
fn test_nonzero_u128_roundtrip(
x in any::<u128>()
.prop_filter("Values must not be 0", |x| x != &0)
.prop_map(|x| NonZeroU128::new(x).unwrap())
) {
Python::with_gil(|py| {
let x_py = x.into_pyobject(py).unwrap();
let locals = PyDict::new(py);
locals.set_item("x_py", &x_py).unwrap();
py.run(&CString::new(format!("assert x_py == {}", x)).unwrap(), None, Some(&locals)).unwrap();
let roundtripped: NonZeroU128 = x_py.extract().unwrap();
assert_eq!(x, roundtripped);
})
}
}
#[test]
fn test_i128_max() {
Python::with_gil(|py| {
let v = i128::MAX;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<i128>().unwrap());
assert_eq!(v as u128, obj.extract::<u128>().unwrap());
assert!(obj.extract::<u64>().is_err());
})
}
#[test]
fn test_i128_min() {
Python::with_gil(|py| {
let v = i128::MIN;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<i128>().unwrap());
assert!(obj.extract::<i64>().is_err());
assert!(obj.extract::<u128>().is_err());
})
}
#[test]
fn test_u128_max() {
Python::with_gil(|py| {
let v = u128::MAX;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<u128>().unwrap());
assert!(obj.extract::<i128>().is_err());
})
}
#[test]
fn test_i128_overflow() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("(1 << 130) * -1"), None, None).unwrap();
let err = obj.extract::<i128>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyOverflowError>(py));
})
}
#[test]
fn test_u128_overflow() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("1 << 130"), None, None).unwrap();
let err = obj.extract::<u128>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyOverflowError>(py));
})
}
#[test]
fn test_nonzero_i128_max() {
Python::with_gil(|py| {
let v = NonZeroI128::new(i128::MAX).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroI128>().unwrap());
assert_eq!(
NonZeroU128::new(v.get() as u128).unwrap(),
obj.extract::<NonZeroU128>().unwrap()
);
assert!(obj.extract::<NonZeroU64>().is_err());
})
}
#[test]
fn test_nonzero_i128_min() {
Python::with_gil(|py| {
let v = NonZeroI128::new(i128::MIN).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroI128>().unwrap());
assert!(obj.extract::<NonZeroI64>().is_err());
assert!(obj.extract::<NonZeroU128>().is_err());
})
}
#[test]
fn test_nonzero_u128_max() {
Python::with_gil(|py| {
let v = NonZeroU128::new(u128::MAX).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroU128>().unwrap());
assert!(obj.extract::<NonZeroI128>().is_err());
})
}
#[test]
fn test_nonzero_i128_overflow() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("(1 << 130) * -1"), None, None).unwrap();
let err = obj.extract::<NonZeroI128>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyOverflowError>(py));
})
}
#[test]
fn test_nonzero_u128_overflow() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("1 << 130"), None, None).unwrap();
let err = obj.extract::<NonZeroU128>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyOverflowError>(py));
})
}
#[test]
fn test_nonzero_i128_zero_value() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("0"), None, None).unwrap();
let err = obj.extract::<NonZeroI128>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyValueError>(py));
})
}
#[test]
fn test_nonzero_u128_zero_value() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("0"), None, None).unwrap();
let err = obj.extract::<NonZeroU128>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyValueError>(py));
})
}
}
#[cfg(test)]
mod tests {
use crate::types::PyAnyMethods;
use crate::{IntoPyObject, Python};
use std::num::*;
#[test]
fn test_u32_max() {
Python::with_gil(|py| {
let v = u32::MAX;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<u32>().unwrap());
assert_eq!(u64::from(v), obj.extract::<u64>().unwrap());
assert!(obj.extract::<i32>().is_err());
});
}
#[test]
fn test_i64_max() {
Python::with_gil(|py| {
let v = i64::MAX;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<i64>().unwrap());
assert_eq!(v as u64, obj.extract::<u64>().unwrap());
assert!(obj.extract::<u32>().is_err());
});
}
#[test]
fn test_i64_min() {
Python::with_gil(|py| {
let v = i64::MIN;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<i64>().unwrap());
assert!(obj.extract::<i32>().is_err());
assert!(obj.extract::<u64>().is_err());
});
}
#[test]
fn test_u64_max() {
Python::with_gil(|py| {
let v = u64::MAX;
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<u64>().unwrap());
assert!(obj.extract::<i64>().is_err());
});
}
macro_rules! test_common (
($test_mod_name:ident, $t:ty) => (
mod $test_mod_name {
use crate::exceptions;
use crate::conversion::IntoPyObject;
use crate::types::PyAnyMethods;
use crate::Python;
#[test]
fn from_py_string_type_error() {
Python::with_gil(|py| {
let obj = ("123").into_pyobject(py).unwrap();
let err = obj.extract::<$t>().unwrap_err();
assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
});
}
#[test]
fn from_py_float_type_error() {
Python::with_gil(|py| {
let obj = (12.3f64).into_pyobject(py).unwrap();
let err = obj.extract::<$t>().unwrap_err();
assert!(err.is_instance_of::<exceptions::PyTypeError>(py));});
}
#[test]
fn to_py_object_and_back() {
Python::with_gil(|py| {
let val = 123 as $t;
let obj = val.into_pyobject(py).unwrap();
assert_eq!(obj.extract::<$t>().unwrap(), val as $t);});
}
}
)
);
test_common!(i8, i8);
test_common!(u8, u8);
test_common!(i16, i16);
test_common!(u16, u16);
test_common!(i32, i32);
test_common!(u32, u32);
test_common!(i64, i64);
test_common!(u64, u64);
test_common!(isize, isize);
test_common!(usize, usize);
test_common!(i128, i128);
test_common!(u128, u128);
#[test]
fn test_nonzero_u32_max() {
Python::with_gil(|py| {
let v = NonZeroU32::new(u32::MAX).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroU32>().unwrap());
assert_eq!(NonZeroU64::from(v), obj.extract::<NonZeroU64>().unwrap());
assert!(obj.extract::<NonZeroI32>().is_err());
});
}
#[test]
fn test_nonzero_i64_max() {
Python::with_gil(|py| {
let v = NonZeroI64::new(i64::MAX).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroI64>().unwrap());
assert_eq!(
NonZeroU64::new(v.get() as u64).unwrap(),
obj.extract::<NonZeroU64>().unwrap()
);
assert!(obj.extract::<NonZeroU32>().is_err());
});
}
#[test]
fn test_nonzero_i64_min() {
Python::with_gil(|py| {
let v = NonZeroI64::new(i64::MIN).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroI64>().unwrap());
assert!(obj.extract::<NonZeroI32>().is_err());
assert!(obj.extract::<NonZeroU64>().is_err());
});
}
#[test]
fn test_nonzero_u64_max() {
Python::with_gil(|py| {
let v = NonZeroU64::new(u64::MAX).unwrap();
let obj = v.into_pyobject(py).unwrap();
assert_eq!(v, obj.extract::<NonZeroU64>().unwrap());
assert!(obj.extract::<NonZeroI64>().is_err());
});
}
macro_rules! test_nonzero_common (
($test_mod_name:ident, $t:ty) => (
mod $test_mod_name {
use crate::exceptions;
use crate::conversion::IntoPyObject;
use crate::types::PyAnyMethods;
use crate::Python;
use std::num::*;
#[test]
fn from_py_string_type_error() {
Python::with_gil(|py| {
let obj = ("123").into_pyobject(py).unwrap();
let err = obj.extract::<$t>().unwrap_err();
assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
});
}
#[test]
fn from_py_float_type_error() {
Python::with_gil(|py| {
let obj = (12.3f64).into_pyobject(py).unwrap();
let err = obj.extract::<$t>().unwrap_err();
assert!(err.is_instance_of::<exceptions::PyTypeError>(py));});
}
#[test]
fn to_py_object_and_back() {
Python::with_gil(|py| {
let val = <$t>::new(123).unwrap();
let obj = val.into_pyobject(py).unwrap();
assert_eq!(obj.extract::<$t>().unwrap(), val);});
}
}
)
);
test_nonzero_common!(nonzero_i8, NonZeroI8);
test_nonzero_common!(nonzero_u8, NonZeroU8);
test_nonzero_common!(nonzero_i16, NonZeroI16);
test_nonzero_common!(nonzero_u16, NonZeroU16);
test_nonzero_common!(nonzero_i32, NonZeroI32);
test_nonzero_common!(nonzero_u32, NonZeroU32);
test_nonzero_common!(nonzero_i64, NonZeroI64);
test_nonzero_common!(nonzero_u64, NonZeroU64);
test_nonzero_common!(nonzero_isize, NonZeroIsize);
test_nonzero_common!(nonzero_usize, NonZeroUsize);
test_nonzero_common!(nonzero_i128, NonZeroI128);
test_nonzero_common!(nonzero_u128, NonZeroU128);
#[test]
fn test_i64_bool() {
Python::with_gil(|py| {
let obj = true.into_pyobject(py).unwrap();
assert_eq!(1, obj.extract::<i64>().unwrap());
let obj = false.into_pyobject(py).unwrap();
assert_eq!(0, obj.extract::<i64>().unwrap());
})
}
#[test]
fn test_i64_f64() {
Python::with_gil(|py| {
let obj = 12.34f64.into_pyobject(py).unwrap();
let err = obj.extract::<i64>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyTypeError>(py));
// with no remainder
let obj = 12f64.into_pyobject(py).unwrap();
let err = obj.extract::<i64>().unwrap_err();
assert!(err.is_instance_of::<crate::exceptions::PyTypeError>(py));
})
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/time.rs | use crate::conversion::IntoPyObject;
use crate::exceptions::{PyOverflowError, PyValueError};
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
#[cfg(Py_LIMITED_API)]
use crate::types::PyType;
#[cfg(not(Py_LIMITED_API))]
use crate::types::{timezone_utc, PyDateTime, PyDelta, PyDeltaAccess};
#[cfg(Py_LIMITED_API)]
use crate::Py;
use crate::{intern, Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
impl FromPyObject<'_> for Duration {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
#[cfg(not(Py_LIMITED_API))]
let (days, seconds, microseconds) = {
let delta = obj.downcast::<PyDelta>()?;
(
delta.get_days(),
delta.get_seconds(),
delta.get_microseconds(),
)
};
#[cfg(Py_LIMITED_API)]
let (days, seconds, microseconds): (i32, i32, i32) = {
(
obj.getattr(intern!(obj.py(), "days"))?.extract()?,
obj.getattr(intern!(obj.py(), "seconds"))?.extract()?,
obj.getattr(intern!(obj.py(), "microseconds"))?.extract()?,
)
};
// We cast
let days = u64::try_from(days).map_err(|_| {
PyValueError::new_err(
"It is not possible to convert a negative timedelta to a Rust Duration",
)
})?;
let seconds = u64::try_from(seconds).unwrap(); // 0 <= seconds < 3600*24
let microseconds = u32::try_from(microseconds).unwrap(); // 0 <= microseconds < 1000000
// We convert
let total_seconds = days * SECONDS_PER_DAY + seconds; // We casted from i32, this can't overflow
let nanoseconds = microseconds.checked_mul(1_000).unwrap(); // 0 <= microseconds < 1000000
Ok(Duration::new(total_seconds, nanoseconds))
}
}
#[allow(deprecated)]
impl ToPyObject for Duration {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Duration {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Duration {
#[cfg(not(Py_LIMITED_API))]
type Target = PyDelta;
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let days = self.as_secs() / SECONDS_PER_DAY;
let seconds = self.as_secs() % SECONDS_PER_DAY;
let microseconds = self.subsec_micros();
#[cfg(not(Py_LIMITED_API))]
{
PyDelta::new(
py,
days.try_into()?,
seconds.try_into().unwrap(),
microseconds.try_into().unwrap(),
false,
)
}
#[cfg(Py_LIMITED_API)]
{
static TIMEDELTA: GILOnceCell<Py<PyType>> = GILOnceCell::new();
TIMEDELTA
.import(py, "datetime", "timedelta")?
.call1((days, seconds, microseconds))
}
}
}
impl<'py> IntoPyObject<'py> for &Duration {
#[cfg(not(Py_LIMITED_API))]
type Target = PyDelta;
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
// Conversions between SystemTime and datetime do not rely on the floating point timestamp of the
// timestamp/fromtimestamp APIs to avoid possible precision loss but goes through the
// timedelta/std::time::Duration types by taking for reference point the UNIX epoch.
//
// TODO: it might be nice to investigate using timestamps anyway, at least when the datetime is a safe range.
impl FromPyObject<'_> for SystemTime {
fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
let duration_since_unix_epoch: Duration = obj
.call_method1(intern!(obj.py(), "__sub__"), (unix_epoch_py(obj.py())?,))?
.extract()?;
UNIX_EPOCH
.checked_add(duration_since_unix_epoch)
.ok_or_else(|| {
PyOverflowError::new_err("Overflow error when converting the time to Rust")
})
}
}
#[allow(deprecated)]
impl ToPyObject for SystemTime {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for SystemTime {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for SystemTime {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let duration_since_unix_epoch =
self.duration_since(UNIX_EPOCH).unwrap().into_pyobject(py)?;
unix_epoch_py(py)?
.bind(py)
.call_method1(intern!(py, "__add__"), (duration_since_unix_epoch,))
}
}
impl<'py> IntoPyObject<'py> for &SystemTime {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
fn unix_epoch_py(py: Python<'_>) -> PyResult<&PyObject> {
static UNIX_EPOCH: GILOnceCell<PyObject> = GILOnceCell::new();
UNIX_EPOCH.get_or_try_init(py, || {
#[cfg(not(Py_LIMITED_API))]
{
Ok::<_, PyErr>(
PyDateTime::new(py, 1970, 1, 1, 0, 0, 0, 0, Some(&timezone_utc(py)))?.into(),
)
}
#[cfg(Py_LIMITED_API)]
{
let datetime = py.import("datetime")?;
let utc = datetime.getattr("timezone")?.getattr("utc")?;
Ok::<_, PyErr>(
datetime
.getattr("datetime")?
.call1((1970, 1, 1, 0, 0, 0, 0, utc))
.unwrap()
.into(),
)
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::PyDict;
#[test]
fn test_duration_frompyobject() {
Python::with_gil(|py| {
assert_eq!(
new_timedelta(py, 0, 0, 0).extract::<Duration>().unwrap(),
Duration::new(0, 0)
);
assert_eq!(
new_timedelta(py, 1, 0, 0).extract::<Duration>().unwrap(),
Duration::new(86400, 0)
);
assert_eq!(
new_timedelta(py, 0, 1, 0).extract::<Duration>().unwrap(),
Duration::new(1, 0)
);
assert_eq!(
new_timedelta(py, 0, 0, 1).extract::<Duration>().unwrap(),
Duration::new(0, 1_000)
);
assert_eq!(
new_timedelta(py, 1, 1, 1).extract::<Duration>().unwrap(),
Duration::new(86401, 1_000)
);
assert_eq!(
timedelta_class(py)
.getattr("max")
.unwrap()
.extract::<Duration>()
.unwrap(),
Duration::new(86399999999999, 999999000)
);
});
}
#[test]
fn test_duration_frompyobject_negative() {
Python::with_gil(|py| {
assert_eq!(
new_timedelta(py, 0, -1, 0)
.extract::<Duration>()
.unwrap_err()
.to_string(),
"ValueError: It is not possible to convert a negative timedelta to a Rust Duration"
);
})
}
#[test]
fn test_duration_into_pyobject() {
Python::with_gil(|py| {
let assert_eq = |l: Bound<'_, PyAny>, r: Bound<'_, PyAny>| {
assert!(l.eq(r).unwrap());
};
assert_eq(
Duration::new(0, 0).into_pyobject(py).unwrap().into_any(),
new_timedelta(py, 0, 0, 0),
);
assert_eq(
Duration::new(86400, 0)
.into_pyobject(py)
.unwrap()
.into_any(),
new_timedelta(py, 1, 0, 0),
);
assert_eq(
Duration::new(1, 0).into_pyobject(py).unwrap().into_any(),
new_timedelta(py, 0, 1, 0),
);
assert_eq(
Duration::new(0, 1_000)
.into_pyobject(py)
.unwrap()
.into_any(),
new_timedelta(py, 0, 0, 1),
);
assert_eq(
Duration::new(0, 1).into_pyobject(py).unwrap().into_any(),
new_timedelta(py, 0, 0, 0),
);
assert_eq(
Duration::new(86401, 1_000)
.into_pyobject(py)
.unwrap()
.into_any(),
new_timedelta(py, 1, 1, 1),
);
assert_eq(
Duration::new(86399999999999, 999999000)
.into_pyobject(py)
.unwrap()
.into_any(),
timedelta_class(py).getattr("max").unwrap(),
);
});
}
#[test]
fn test_duration_into_pyobject_overflow() {
Python::with_gil(|py| {
assert!(Duration::MAX.into_pyobject(py).is_err());
})
}
#[test]
fn test_time_frompyobject() {
Python::with_gil(|py| {
assert_eq!(
new_datetime(py, 1970, 1, 1, 0, 0, 0, 0)
.extract::<SystemTime>()
.unwrap(),
UNIX_EPOCH
);
assert_eq!(
new_datetime(py, 2020, 2, 3, 4, 5, 6, 7)
.extract::<SystemTime>()
.unwrap(),
UNIX_EPOCH
.checked_add(Duration::new(1580702706, 7000))
.unwrap()
);
assert_eq!(
max_datetime(py).extract::<SystemTime>().unwrap(),
UNIX_EPOCH
.checked_add(Duration::new(253402300799, 999999000))
.unwrap()
);
});
}
#[test]
fn test_time_frompyobject_before_epoch() {
Python::with_gil(|py| {
assert_eq!(
new_datetime(py, 1950, 1, 1, 0, 0, 0, 0)
.extract::<SystemTime>()
.unwrap_err()
.to_string(),
"ValueError: It is not possible to convert a negative timedelta to a Rust Duration"
);
})
}
#[test]
fn test_time_intopyobject() {
Python::with_gil(|py| {
let assert_eq = |l: Bound<'_, PyAny>, r: Bound<'_, PyAny>| {
assert!(l.eq(r).unwrap());
};
assert_eq(
UNIX_EPOCH
.checked_add(Duration::new(1580702706, 7123))
.unwrap()
.into_pyobject(py)
.unwrap(),
new_datetime(py, 2020, 2, 3, 4, 5, 6, 7),
);
assert_eq(
UNIX_EPOCH
.checked_add(Duration::new(253402300799, 999999000))
.unwrap()
.into_pyobject(py)
.unwrap(),
max_datetime(py),
);
});
}
#[allow(clippy::too_many_arguments)]
fn new_datetime(
py: Python<'_>,
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
microsecond: u32,
) -> Bound<'_, PyAny> {
datetime_class(py)
.call1((
year,
month,
day,
hour,
minute,
second,
microsecond,
tz_utc(py),
))
.unwrap()
}
fn max_datetime(py: Python<'_>) -> Bound<'_, PyAny> {
let naive_max = datetime_class(py).getattr("max").unwrap();
let kargs = PyDict::new(py);
kargs.set_item("tzinfo", tz_utc(py)).unwrap();
naive_max.call_method("replace", (), Some(&kargs)).unwrap()
}
#[test]
fn test_time_intopyobject_overflow() {
let big_system_time = UNIX_EPOCH
.checked_add(Duration::new(300000000000, 0))
.unwrap();
Python::with_gil(|py| {
assert!(big_system_time.into_pyobject(py).is_err());
})
}
fn tz_utc(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime")
.unwrap()
.getattr("timezone")
.unwrap()
.getattr("utc")
.unwrap()
}
fn new_timedelta(
py: Python<'_>,
days: i32,
seconds: i32,
microseconds: i32,
) -> Bound<'_, PyAny> {
timedelta_class(py)
.call1((days, seconds, microseconds))
.unwrap()
}
fn datetime_class(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime").unwrap().getattr("datetime").unwrap()
}
fn timedelta_class(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime").unwrap().getattr("timedelta").unwrap()
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/mod.rs | mod array;
mod cell;
mod ipaddr;
mod map;
mod num;
mod option;
mod osstr;
mod path;
mod set;
mod slice;
mod string;
mod time;
mod vec;
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions | lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversions/std/option.rs | use crate::{
conversion::IntoPyObject, ffi, types::any::PyAnyMethods, AsPyPointer, Bound, BoundObject,
FromPyObject, PyAny, PyObject, PyResult, Python,
};
/// `Option::Some<T>` is converted like `T`.
/// `Option::None` is converted to Python `None`.
#[allow(deprecated)]
impl<T> crate::ToPyObject for Option<T>
where
T: crate::ToPyObject,
{
fn to_object(&self, py: Python<'_>) -> PyObject {
self.as_ref()
.map_or_else(|| py.None(), |val| val.to_object(py))
}
}
#[allow(deprecated)]
impl<T> crate::IntoPy<PyObject> for Option<T>
where
T: crate::IntoPy<PyObject>,
{
fn into_py(self, py: Python<'_>) -> PyObject {
self.map_or_else(|| py.None(), |val| val.into_py(py))
}
}
impl<'py, T> IntoPyObject<'py> for Option<T>
where
T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = T::Error;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.map_or_else(
|| Ok(py.None().into_bound(py)),
|val| {
val.into_pyobject(py)
.map(BoundObject::into_any)
.map(BoundObject::into_bound)
},
)
}
}
impl<'a, 'py, T> IntoPyObject<'py> for &'a Option<T>
where
&'a T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = <&'a T as IntoPyObject<'py>>::Error;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_ref().into_pyobject(py)
}
}
impl<'py, T> FromPyObject<'py> for Option<T>
where
T: FromPyObject<'py>,
{
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
if obj.is_none() {
Ok(None)
} else {
obj.extract().map(Some)
}
}
}
/// Convert `None` into a null pointer.
unsafe impl<T> AsPyPointer for Option<T>
where
T: AsPyPointer,
{
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
self.as_ref()
.map_or_else(std::ptr::null_mut, |t| t.as_ptr())
}
}
#[cfg(test)]
mod tests {
use crate::{PyObject, Python};
#[test]
fn test_option_as_ptr() {
Python::with_gil(|py| {
use crate::AsPyPointer;
let mut option: Option<PyObject> = None;
assert_eq!(option.as_ptr(), std::ptr::null_mut());
let none = py.None();
option = Some(none.clone_ref(py));
let ref_cnt = none.get_refcnt(py);
assert_eq!(option.as_ptr(), none.as_ptr());
// Ensure ref count not changed by as_ptr call
assert_eq!(none.get_refcnt(py), ref_cnt);
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/inspect/types.rs | //! Data types used to describe runtime Python types.
use std::borrow::Cow;
use std::fmt::{Display, Formatter};
/// Designation of a Python type.
///
/// This enum is used to handle advanced types, such as types with generics.
/// Its [`Display`] implementation can be used to convert to the type hint notation (e.g. `List[int]`).
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TypeInfo {
/// The type `typing.Any`, which represents any possible value (unknown type).
Any,
/// The type `typing.None`.
None,
/// The type `typing.NoReturn`, which represents functions that never return (they can still panic / throw, similar to `never` in Rust).
NoReturn,
/// The type `typing.Callable`.
///
/// The first argument represents the parameters of the callable:
/// - `Some` of a vector of types to represent the signature,
/// - `None` if the signature is unknown (allows any number of arguments with type `Any`).
///
/// The second argument represents the return type.
Callable(Option<Vec<TypeInfo>>, Box<TypeInfo>),
/// The type `typing.tuple`.
///
/// The argument represents the contents of the tuple:
/// - `Some` of a vector of types to represent the accepted types,
/// - `Some` of an empty vector for the empty tuple,
/// - `None` if the number and type of accepted values is unknown.
///
/// If the number of accepted values is unknown, but their type is, use [`Self::UnsizedTypedTuple`].
Tuple(Option<Vec<TypeInfo>>),
/// The type `typing.Tuple`.
///
/// Use this variant to represent a tuple of unknown size but of known types.
///
/// If the type is unknown, or if the number of elements is known, use [`Self::Tuple`].
UnsizedTypedTuple(Box<TypeInfo>),
/// A Python class.
Class {
/// The module this class comes from.
module: ModuleName,
/// The name of this class, as it appears in a type hint.
name: Cow<'static, str>,
/// The generics accepted by this class (empty vector if this class is not generic).
type_vars: Vec<TypeInfo>,
},
}
/// Declares which module a type is a part of.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ModuleName {
/// The type is built-in: it doesn't need to be imported.
Builtin,
/// The type is in the current module: it doesn't need to be imported in this module, but needs to be imported in others.
CurrentModule,
/// The type is in the specified module.
Module(Cow<'static, str>),
}
impl TypeInfo {
/// Returns the module in which a type is declared.
///
/// Returns `None` if the type is declared in the current module.
pub fn module_name(&self) -> Option<&str> {
match self {
TypeInfo::Any
| TypeInfo::None
| TypeInfo::NoReturn
| TypeInfo::Callable(_, _)
| TypeInfo::Tuple(_)
| TypeInfo::UnsizedTypedTuple(_) => Some("typing"),
TypeInfo::Class { module, .. } => match module {
ModuleName::Builtin => Some("builtins"),
ModuleName::CurrentModule => None,
ModuleName::Module(name) => Some(name),
},
}
}
/// Returns the name of a type.
///
/// The name of a type is the part of the hint that is not generic (e.g. `List` instead of `List[int]`).
pub fn name(&self) -> Cow<'_, str> {
Cow::from(match self {
TypeInfo::Any => "Any",
TypeInfo::None => "None",
TypeInfo::NoReturn => "NoReturn",
TypeInfo::Callable(_, _) => "Callable",
TypeInfo::Tuple(_) => "Tuple",
TypeInfo::UnsizedTypedTuple(_) => "Tuple",
TypeInfo::Class { name, .. } => name,
})
}
}
// Utilities for easily instantiating TypeInfo structures for built-in/common types.
impl TypeInfo {
/// The Python `Optional` type.
pub fn optional_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Optional"),
type_vars: vec![t],
}
}
/// The Python `Union` type.
pub fn union_of(types: &[TypeInfo]) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Union"),
type_vars: types.to_vec(),
}
}
/// The Python `List` type.
pub fn list_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("List"),
type_vars: vec![t],
}
}
/// The Python `Sequence` type.
pub fn sequence_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Sequence"),
type_vars: vec![t],
}
}
/// The Python `Set` type.
pub fn set_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Set"),
type_vars: vec![t],
}
}
/// The Python `FrozenSet` type.
pub fn frozen_set_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("FrozenSet"),
type_vars: vec![t],
}
}
/// The Python `Iterable` type.
pub fn iterable_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Iterable"),
type_vars: vec![t],
}
}
/// The Python `Iterator` type.
pub fn iterator_of(t: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Iterator"),
type_vars: vec![t],
}
}
/// The Python `Dict` type.
pub fn dict_of(k: TypeInfo, v: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Dict"),
type_vars: vec![k, v],
}
}
/// The Python `Mapping` type.
pub fn mapping_of(k: TypeInfo, v: TypeInfo) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Module(Cow::from("typing")),
name: Cow::from("Mapping"),
type_vars: vec![k, v],
}
}
/// Convenience factory for non-generic builtins (e.g. `int`).
pub fn builtin(name: &'static str) -> TypeInfo {
TypeInfo::Class {
module: ModuleName::Builtin,
name: Cow::from(name),
type_vars: vec![],
}
}
}
impl Display for TypeInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
TypeInfo::Any | TypeInfo::None | TypeInfo::NoReturn => write!(f, "{}", self.name()),
TypeInfo::Callable(input, output) => {
write!(f, "Callable[")?;
if let Some(input) = input {
write!(f, "[")?;
let mut comma = false;
for arg in input {
if comma {
write!(f, ", ")?;
}
write!(f, "{}", arg)?;
comma = true;
}
write!(f, "]")?;
} else {
write!(f, "...")?;
}
write!(f, ", {}]", output)
}
TypeInfo::Tuple(types) => {
write!(f, "Tuple[")?;
if let Some(types) = types {
if types.is_empty() {
write!(f, "()")?;
} else {
let mut comma = false;
for t in types {
if comma {
write!(f, ", ")?;
}
write!(f, "{}", t)?;
comma = true;
}
}
} else {
write!(f, "...")?;
}
write!(f, "]")
}
TypeInfo::UnsizedTypedTuple(t) => write!(f, "Tuple[{}, ...]", t),
TypeInfo::Class {
name, type_vars, ..
} => {
write!(f, "{}", name)?;
if !type_vars.is_empty() {
write!(f, "[")?;
let mut comma = false;
for var in type_vars {
if comma {
write!(f, ", ")?;
}
write!(f, "{}", var)?;
comma = true;
}
write!(f, "]")
} else {
Ok(())
}
}
}
}
}
#[cfg(test)]
mod test {
use std::borrow::Cow;
use crate::inspect::types::{ModuleName, TypeInfo};
#[track_caller]
pub fn assert_display(t: &TypeInfo, expected: &str) {
assert_eq!(format!("{}", t), expected)
}
#[test]
fn basic() {
assert_display(&TypeInfo::Any, "Any");
assert_display(&TypeInfo::None, "None");
assert_display(&TypeInfo::NoReturn, "NoReturn");
assert_display(&TypeInfo::builtin("int"), "int");
}
#[test]
fn callable() {
let any_to_int = TypeInfo::Callable(None, Box::new(TypeInfo::builtin("int")));
assert_display(&any_to_int, "Callable[..., int]");
let sum = TypeInfo::Callable(
Some(vec![TypeInfo::builtin("int"), TypeInfo::builtin("int")]),
Box::new(TypeInfo::builtin("int")),
);
assert_display(&sum, "Callable[[int, int], int]");
}
#[test]
fn tuple() {
let any = TypeInfo::Tuple(None);
assert_display(&any, "Tuple[...]");
let triple = TypeInfo::Tuple(Some(vec![
TypeInfo::builtin("int"),
TypeInfo::builtin("str"),
TypeInfo::builtin("bool"),
]));
assert_display(&triple, "Tuple[int, str, bool]");
let empty = TypeInfo::Tuple(Some(vec![]));
assert_display(&empty, "Tuple[()]");
let typed = TypeInfo::UnsizedTypedTuple(Box::new(TypeInfo::builtin("bool")));
assert_display(&typed, "Tuple[bool, ...]");
}
#[test]
fn class() {
let class1 = TypeInfo::Class {
module: ModuleName::CurrentModule,
name: Cow::from("MyClass"),
type_vars: vec![],
};
assert_display(&class1, "MyClass");
let class2 = TypeInfo::Class {
module: ModuleName::CurrentModule,
name: Cow::from("MyClass"),
type_vars: vec![TypeInfo::builtin("int"), TypeInfo::builtin("bool")],
};
assert_display(&class2, "MyClass[int, bool]");
}
#[test]
fn collections() {
let int = TypeInfo::builtin("int");
let bool = TypeInfo::builtin("bool");
let str = TypeInfo::builtin("str");
let list = TypeInfo::list_of(int.clone());
assert_display(&list, "List[int]");
let sequence = TypeInfo::sequence_of(bool.clone());
assert_display(&sequence, "Sequence[bool]");
let optional = TypeInfo::optional_of(str.clone());
assert_display(&optional, "Optional[str]");
let iterable = TypeInfo::iterable_of(int.clone());
assert_display(&iterable, "Iterable[int]");
let iterator = TypeInfo::iterator_of(bool);
assert_display(&iterator, "Iterator[bool]");
let dict = TypeInfo::dict_of(int.clone(), str.clone());
assert_display(&dict, "Dict[int, str]");
let mapping = TypeInfo::mapping_of(int, str.clone());
assert_display(&mapping, "Mapping[int, str]");
let set = TypeInfo::set_of(str.clone());
assert_display(&set, "Set[str]");
let frozen_set = TypeInfo::frozen_set_of(str);
assert_display(&frozen_set, "FrozenSet[str]");
}
#[test]
fn complicated() {
let int = TypeInfo::builtin("int");
assert_display(&int, "int");
let bool = TypeInfo::builtin("bool");
assert_display(&bool, "bool");
let str = TypeInfo::builtin("str");
assert_display(&str, "str");
let any = TypeInfo::Any;
assert_display(&any, "Any");
let params = TypeInfo::union_of(&[int.clone(), str]);
assert_display(¶ms, "Union[int, str]");
let func = TypeInfo::Callable(Some(vec![params, any]), Box::new(bool));
assert_display(&func, "Callable[[Union[int, str], Any], bool]");
let dict = TypeInfo::mapping_of(int, func);
assert_display(
&dict,
"Mapping[int, Callable[[Union[int, str], Any], bool]]",
);
}
}
#[cfg(test)]
mod conversion {
use std::collections::{HashMap, HashSet};
use crate::inspect::types::test::assert_display;
use crate::{FromPyObject, IntoPyObject};
#[test]
fn unsigned_int() {
assert_display(&usize::type_output(), "int");
assert_display(&usize::type_input(), "int");
assert_display(&u8::type_output(), "int");
assert_display(&u8::type_input(), "int");
assert_display(&u16::type_output(), "int");
assert_display(&u16::type_input(), "int");
assert_display(&u32::type_output(), "int");
assert_display(&u32::type_input(), "int");
assert_display(&u64::type_output(), "int");
assert_display(&u64::type_input(), "int");
}
#[test]
fn signed_int() {
assert_display(&isize::type_output(), "int");
assert_display(&isize::type_input(), "int");
assert_display(&i8::type_output(), "int");
assert_display(&i8::type_input(), "int");
assert_display(&i16::type_output(), "int");
assert_display(&i16::type_input(), "int");
assert_display(&i32::type_output(), "int");
assert_display(&i32::type_input(), "int");
assert_display(&i64::type_output(), "int");
assert_display(&i64::type_input(), "int");
}
#[test]
fn float() {
assert_display(&f32::type_output(), "float");
assert_display(&f32::type_input(), "float");
assert_display(&f64::type_output(), "float");
assert_display(&f64::type_input(), "float");
}
#[test]
fn bool() {
assert_display(&bool::type_output(), "bool");
assert_display(&bool::type_input(), "bool");
}
#[test]
fn text() {
assert_display(&String::type_output(), "str");
assert_display(&String::type_input(), "str");
assert_display(&<&[u8]>::type_output(), "Union[bytes, List[int]]");
assert_display(&<&[String]>::type_output(), "Union[bytes, List[str]]");
assert_display(
&<&[u8] as crate::conversion::FromPyObjectBound>::type_input(),
"bytes",
);
}
#[test]
fn collections() {
assert_display(&<Vec<usize>>::type_output(), "List[int]");
assert_display(&<Vec<usize>>::type_input(), "Sequence[int]");
assert_display(&<HashSet<usize>>::type_output(), "Set[int]");
assert_display(&<HashSet<usize>>::type_input(), "Set[int]");
assert_display(&<HashMap<usize, f32>>::type_output(), "Dict[int, float]");
assert_display(&<HashMap<usize, f32>>::type_input(), "Mapping[int, float]");
assert_display(&<(usize, f32)>::type_input(), "Tuple[int, float]");
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/inspect/mod.rs | //! Runtime inspection of objects exposed to Python.
//!
//! Tracking issue: <https://github.com/PyO3/pyo3/issues/2454>.
pub mod types;
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/ffi/tests.rs | use crate::ffi::{self, *};
use crate::types::any::PyAnyMethods;
use crate::Python;
#[cfg(all(not(Py_LIMITED_API), any(not(PyPy), feature = "macros")))]
use crate::types::PyString;
#[cfg(not(Py_LIMITED_API))]
use crate::{types::PyDict, Bound, PyAny};
#[cfg(not(any(Py_3_12, Py_LIMITED_API)))]
use libc::wchar_t;
#[cfg(not(Py_LIMITED_API))]
#[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons
#[test]
fn test_datetime_fromtimestamp() {
use crate::IntoPyObject;
Python::with_gil(|py| {
let args = (100,).into_pyobject(py).unwrap();
let dt = unsafe {
PyDateTime_IMPORT();
Bound::from_owned_ptr(py, PyDateTime_FromTimestamp(args.as_ptr()))
};
let locals = PyDict::new(py);
locals.set_item("dt", dt).unwrap();
py.run(
ffi::c_str!("import datetime; assert dt == datetime.datetime.fromtimestamp(100)"),
None,
Some(&locals),
)
.unwrap();
})
}
#[cfg(not(Py_LIMITED_API))]
#[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons
#[test]
fn test_date_fromtimestamp() {
use crate::IntoPyObject;
Python::with_gil(|py| {
let args = (100,).into_pyobject(py).unwrap();
let dt = unsafe {
PyDateTime_IMPORT();
Bound::from_owned_ptr(py, PyDate_FromTimestamp(args.as_ptr()))
};
let locals = PyDict::new(py);
locals.set_item("dt", dt).unwrap();
py.run(
ffi::c_str!("import datetime; assert dt == datetime.date.fromtimestamp(100)"),
None,
Some(&locals),
)
.unwrap();
})
}
#[cfg(not(Py_LIMITED_API))]
#[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons
#[test]
fn test_utc_timezone() {
Python::with_gil(|py| {
let utc_timezone: Bound<'_, PyAny> = unsafe {
PyDateTime_IMPORT();
Bound::from_borrowed_ptr(py, PyDateTime_TimeZone_UTC())
};
let locals = PyDict::new(py);
locals.set_item("utc_timezone", utc_timezone).unwrap();
py.run(
ffi::c_str!("import datetime; assert utc_timezone is datetime.timezone.utc"),
None,
Some(&locals),
)
.unwrap();
})
}
#[test]
#[cfg(not(Py_LIMITED_API))]
#[cfg(feature = "macros")]
#[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons
fn test_timezone_from_offset() {
use crate::{ffi_ptr_ext::FfiPtrExt, types::PyDelta};
Python::with_gil(|py| {
let delta = PyDelta::new(py, 0, 100, 0, false).unwrap();
let tz = unsafe { PyTimeZone_FromOffset(delta.as_ptr()).assume_owned(py) };
crate::py_run!(
py,
tz,
"import datetime; assert tz == datetime.timezone(datetime.timedelta(seconds=100))"
);
})
}
#[test]
#[cfg(not(Py_LIMITED_API))]
#[cfg(feature = "macros")]
#[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons
fn test_timezone_from_offset_and_name() {
use crate::{ffi_ptr_ext::FfiPtrExt, types::PyDelta};
Python::with_gil(|py| {
let delta = PyDelta::new(py, 0, 100, 0, false).unwrap();
let tzname = PyString::new(py, "testtz");
let tz = unsafe {
PyTimeZone_FromOffsetAndName(delta.as_ptr(), tzname.as_ptr()).assume_owned(py)
};
crate::py_run!(
py,
tz,
"import datetime; assert tz == datetime.timezone(datetime.timedelta(seconds=100), 'testtz')"
);
})
}
#[test]
#[cfg(not(Py_LIMITED_API))]
fn ascii_object_bitfield() {
let ob_base: PyObject = unsafe { std::mem::zeroed() };
let mut o = PyASCIIObject {
ob_base,
length: 0,
#[cfg(not(PyPy))]
hash: 0,
state: 0u32,
#[cfg(not(Py_3_12))]
wstr: std::ptr::null_mut() as *mut wchar_t,
};
unsafe {
assert_eq!(o.interned(), 0);
assert_eq!(o.kind(), 0);
assert_eq!(o.compact(), 0);
assert_eq!(o.ascii(), 0);
#[cfg(not(Py_3_12))]
assert_eq!(o.ready(), 0);
let interned_count = if cfg!(Py_3_12) { 2 } else { 4 };
for i in 0..interned_count {
o.set_interned(i);
assert_eq!(o.interned(), i);
}
for i in 0..8 {
o.set_kind(i);
assert_eq!(o.kind(), i);
}
o.set_compact(1);
assert_eq!(o.compact(), 1);
o.set_ascii(1);
assert_eq!(o.ascii(), 1);
#[cfg(not(Py_3_12))]
o.set_ready(1);
#[cfg(not(Py_3_12))]
assert_eq!(o.ready(), 1);
}
}
#[test]
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
fn ascii() {
Python::with_gil(|py| {
// This test relies on implementation details of PyString.
let s = PyString::new(py, "hello, world");
let ptr = s.as_ptr();
unsafe {
let ascii_ptr = ptr as *mut PyASCIIObject;
let ascii = ascii_ptr.as_ref().unwrap();
assert_eq!(ascii.interned(), 0);
assert_eq!(ascii.kind(), PyUnicode_1BYTE_KIND);
assert_eq!(ascii.compact(), 1);
assert_eq!(ascii.ascii(), 1);
#[cfg(not(Py_3_12))]
assert_eq!(ascii.ready(), 1);
assert_eq!(PyUnicode_IS_ASCII(ptr), 1);
assert_eq!(PyUnicode_IS_COMPACT(ptr), 1);
assert_eq!(PyUnicode_IS_COMPACT_ASCII(ptr), 1);
assert!(!PyUnicode_1BYTE_DATA(ptr).is_null());
// 2 and 4 byte macros return nonsense for this string instance.
assert_eq!(PyUnicode_KIND(ptr), PyUnicode_1BYTE_KIND);
assert!(!_PyUnicode_COMPACT_DATA(ptr).is_null());
// _PyUnicode_NONCOMPACT_DATA isn't valid for compact strings.
assert!(!PyUnicode_DATA(ptr).is_null());
assert_eq!(PyUnicode_GET_LENGTH(ptr), s.len().unwrap() as Py_ssize_t);
assert_eq!(PyUnicode_IS_READY(ptr), 1);
// This has potential to mutate object. But it should be a no-op since
// we're already ready.
assert_eq!(PyUnicode_READY(ptr), 0);
}
})
}
#[test]
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
fn ucs4() {
Python::with_gil(|py| {
let s = "哈哈🐈";
let py_string = PyString::new(py, s);
let ptr = py_string.as_ptr();
unsafe {
let ascii_ptr = ptr as *mut PyASCIIObject;
let ascii = ascii_ptr.as_ref().unwrap();
assert_eq!(ascii.interned(), 0);
assert_eq!(ascii.kind(), PyUnicode_4BYTE_KIND);
assert_eq!(ascii.compact(), 1);
assert_eq!(ascii.ascii(), 0);
#[cfg(not(Py_3_12))]
assert_eq!(ascii.ready(), 1);
assert_eq!(PyUnicode_IS_ASCII(ptr), 0);
assert_eq!(PyUnicode_IS_COMPACT(ptr), 1);
assert_eq!(PyUnicode_IS_COMPACT_ASCII(ptr), 0);
assert!(!PyUnicode_4BYTE_DATA(ptr).is_null());
assert_eq!(PyUnicode_KIND(ptr), PyUnicode_4BYTE_KIND);
assert!(!_PyUnicode_COMPACT_DATA(ptr).is_null());
// _PyUnicode_NONCOMPACT_DATA isn't valid for compact strings.
assert!(!PyUnicode_DATA(ptr).is_null());
assert_eq!(
PyUnicode_GET_LENGTH(ptr),
py_string.len().unwrap() as Py_ssize_t
);
assert_eq!(PyUnicode_IS_READY(ptr), 1);
// This has potential to mutate object. But it should be a no-op since
// we're already ready.
assert_eq!(PyUnicode_READY(ptr), 0);
}
})
}
#[test]
#[cfg(not(Py_LIMITED_API))]
#[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons
#[cfg(not(PyPy))]
fn test_get_tzinfo() {
use crate::types::timezone_utc;
crate::Python::with_gil(|py| {
use crate::types::{PyDateTime, PyTime};
let utc = &timezone_utc(py);
let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, Some(utc)).unwrap();
assert!(
unsafe { Bound::from_borrowed_ptr(py, PyDateTime_DATE_GET_TZINFO(dt.as_ptr())) }
.is(utc)
);
let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, None).unwrap();
assert!(
unsafe { Bound::from_borrowed_ptr(py, PyDateTime_DATE_GET_TZINFO(dt.as_ptr())) }
.is_none()
);
let t = PyTime::new(py, 0, 0, 0, 0, Some(utc)).unwrap();
assert!(
unsafe { Bound::from_borrowed_ptr(py, PyDateTime_TIME_GET_TZINFO(t.as_ptr())) }.is(utc)
);
let t = PyTime::new(py, 0, 0, 0, 0, None).unwrap();
assert!(
unsafe { Bound::from_borrowed_ptr(py, PyDateTime_TIME_GET_TZINFO(t.as_ptr())) }
.is_none()
);
})
}
#[test]
fn test_inc_dec_ref() {
Python::with_gil(|py| {
let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap();
let ref_count = obj.get_refcnt();
let ptr = obj.as_ptr();
unsafe { Py_INCREF(ptr) };
assert_eq!(obj.get_refcnt(), ref_count + 1);
unsafe { Py_DECREF(ptr) };
assert_eq!(obj.get_refcnt(), ref_count);
})
}
#[test]
#[cfg(Py_3_12)]
fn test_inc_dec_ref_immortal() {
Python::with_gil(|py| {
let obj = py.None();
let ref_count = obj.get_refcnt(py);
let ptr = obj.as_ptr();
unsafe { Py_INCREF(ptr) };
assert_eq!(obj.get_refcnt(py), ref_count);
unsafe { Py_DECREF(ptr) };
assert_eq!(obj.get_refcnt(py), ref_count);
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/src | lc_public_repos/langsmith-sdk/vendor/pyo3/src/ffi/mod.rs | //! Raw FFI declarations for Python's C API.
//!
//! This module provides low level bindings to the Python interpreter.
//! It is meant for advanced users only - regular PyO3 users shouldn't
//! need to interact with this module at all.
//!
//! The contents of this module are not documented here, as it would entail
//! basically copying the documentation from CPython. Consult the [Python/C API Reference
//! Manual][capi] for up-to-date documentation.
//!
//! # Safety
//!
//! The functions in this module lack individual safety documentation, but
//! generally the following apply:
//! - Pointer arguments have to point to a valid Python object of the correct type,
//! although null pointers are sometimes valid input.
//! - The vast majority can only be used safely while the GIL is held.
//! - Some functions have additional safety requirements, consult the
//! [Python/C API Reference Manual][capi] for more information.
//!
//! [capi]: https://docs.python.org/3/c-api/index.html
#[cfg(test)]
mod tests;
// reexport raw bindings exposed in pyo3_ffi
pub use pyo3_ffi::*;
/// Helper to enable #\[pymethods\] to see the workaround for __ipow__ on Python 3.7
#[doc(hidden)]
pub use crate::impl_::pymethods::ipowfunc;
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/book.toml | [book]
title = "PyO3 user guide"
description = "PyO3 user guide"
author = "PyO3 Project and Contributors"
[preprocessor.pyo3_version]
command = "python3 guide/pyo3_version.py"
[output.html]
git-repository-url = "https://github.com/PyO3/pyo3/tree/main/guide"
edit-url-template = "https://github.com/PyO3/pyo3/edit/main/guide/{path}"
playground.runnable = false
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/pyo3_version.py | """Simple mdbook preprocessor to inject pyo3 version into the guide.
It will replace:
- {{#PYO3_VERSION_TAG}} with the contents of the PYO3_VERSION_TAG environment var
- {{#PYO3_DOCS_URL}} with the location of docs (e.g. 'https://docs.rs/pyo3/0.13.2')
- {{#PYO3_CRATE_VERSION}} with a relevant toml snippet (e.g. 'version = "0.13.2"')
Tested against mdbook 0.4.10.
"""
import json
import os
import sys
# Set PYO3_VERSION in CI to build the correct version into links
PYO3_VERSION_TAG = os.environ.get("PYO3_VERSION_TAG", "main")
if PYO3_VERSION_TAG == "main":
PYO3_DOCS_URL = "https://pyo3.rs/main/doc"
PYO3_DOCS_VERSION = "latest"
PYO3_CRATE_VERSION = 'git = "https://github.com/pyo3/pyo3"'
else:
# v0.13.2 -> 0.13.2
version = PYO3_VERSION_TAG.lstrip("v")
PYO3_DOCS_URL = f"https://docs.rs/pyo3/{version}"
PYO3_DOCS_VERSION = version
PYO3_CRATE_VERSION = f'version = "{version}"'
def replace_section_content(section):
if not isinstance(section, dict) or "Chapter" not in section:
return
# Replace raw and url-encoded forms
section["Chapter"]["content"] = (
section["Chapter"]["content"]
.replace("{{#PYO3_VERSION_TAG}}", PYO3_VERSION_TAG)
.replace("{{#PYO3_DOCS_URL}}", PYO3_DOCS_URL)
.replace("{{#PYO3_DOCS_VERSION}}", PYO3_DOCS_VERSION)
.replace("{{#PYO3_CRATE_VERSION}}", PYO3_CRATE_VERSION)
)
for sub_item in section["Chapter"]["sub_items"]:
replace_section_content(sub_item)
for line in sys.stdin:
if line:
[context, book] = json.loads(line)
for section in book["sections"]:
replace_section_content(section)
json.dump(book, fp=sys.stdout)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/pyclass-parameters.md | `#[pyclass]` can be used with the following parameters:
| Parameter | Description |
| :- | :- |
| `constructor` | This is currently only allowed on [variants of complex enums][params-constructor]. It allows customization of the generated class constructor for each variant. It uses the same syntax and supports the same options as the `signature` attribute of functions and methods. |
| <span style="white-space: pre">`crate = "some::path"`</span> | Path to import the `pyo3` crate, if it's not accessible at `::pyo3`. |
| `dict` | Gives instances of this class an empty `__dict__` to store custom attributes. |
| `eq` | Implements `__eq__` using the `PartialEq` implementation of the underlying Rust datatype. |
| `eq_int` | Implements `__eq__` using `__int__` for simple enums. |
| <span style="white-space: pre">`extends = BaseType`</span> | Use a custom baseclass. Defaults to [`PyAny`][params-1] |
| <span style="white-space: pre">`freelist = N`</span> | Implements a [free list][params-2] of size N. This can improve performance for types that are often created and deleted in quick succession. Profile your code to see whether `freelist` is right for you. |
| <span style="white-space: pre">`frozen`</span> | Declares that your pyclass is immutable. It removes the borrow checker overhead when retrieving a shared reference to the Rust struct, but disables the ability to get a mutable reference. |
| `get_all` | Generates getters for all fields of the pyclass. |
| `hash` | Implements `__hash__` using the `Hash` implementation of the underlying Rust datatype. |
| `mapping` | Inform PyO3 that this class is a [`Mapping`][params-mapping], and so leave its implementation of sequence C-API slots empty. |
| <span style="white-space: pre">`module = "module_name"`</span> | Python code will see the class as being defined in this module. Defaults to `builtins`. |
| <span style="white-space: pre">`name = "python_name"`</span> | Sets the name that Python sees this class as. Defaults to the name of the Rust struct. |
| `ord` | Implements `__lt__`, `__gt__`, `__le__`, & `__ge__` using the `PartialOrd` implementation of the underlying Rust datatype. *Requires `eq`* |
| `rename_all = "renaming_rule"` | Applies renaming rules to every getters and setters of a struct, or every variants of an enum. Possible values are: "camelCase", "kebab-case", "lowercase", "PascalCase", "SCREAMING-KEBAB-CASE", "SCREAMING_SNAKE_CASE", "snake_case", "UPPERCASE". |
| `sequence` | Inform PyO3 that this class is a [`Sequence`][params-sequence], and so leave its C-API mapping length slot empty. |
| `set_all` | Generates setters for all fields of the pyclass. |
| `str` | Implements `__str__` using the `Display` implementation of the underlying Rust datatype or by passing an optional format string `str="<format string>"`. *Note: The optional format string is only allowed for structs. `name` and `rename_all` are incompatible with the optional format string. Additional details can be found in the discussion on this [PR](https://github.com/PyO3/pyo3/pull/4233).* |
| `subclass` | Allows other Python classes and `#[pyclass]` to inherit from this class. Enums cannot be subclassed. |
| <span style="white-space: pre">`text_signature = "(arg1, arg2, ...)"`</span> | Sets the text signature for the Python class' `__new__` method. |
| `unsendable` | Required if your struct is not [`Send`][params-3]. Rather than using `unsendable`, consider implementing your struct in a threadsafe way by e.g. substituting [`Rc`][params-4] with [`Arc`][params-5]. By using `unsendable`, your class will panic when accessed by another thread. Also note the Python's GC is multi-threaded and while unsendable classes will not be traversed on foreign threads to avoid UB, this can lead to memory leaks. |
| `weakref` | Allows this class to be [weakly referenceable][params-6]. |
All of these parameters can either be passed directly on the `#[pyclass(...)]` annotation, or as one or
more accompanying `#[pyo3(...)]` annotations, e.g.:
```rust,ignore
// Argument supplied directly to the `#[pyclass]` annotation.
#[pyclass(name = "SomeName", subclass)]
struct MyClass {}
// Argument supplied as a separate annotation.
#[pyclass]
#[pyo3(name = "SomeName", subclass)]
struct MyClass {}
```
[params-1]: https://docs.rs/pyo3/latest/pyo3/types/struct.PyAny.html
[params-2]: https://en.wikipedia.org/wiki/Free_list
[params-3]: https://doc.rust-lang.org/std/marker/trait.Send.html
[params-4]: https://doc.rust-lang.org/std/rc/struct.Rc.html
[params-5]: https://doc.rust-lang.org/std/sync/struct.Arc.html
[params-6]: https://docs.python.org/3/library/weakref.html
[params-constructor]: https://pyo3.rs/latest/class.html#complex-enums
[params-mapping]: https://pyo3.rs/latest/class/protocols.html#mapping--sequence-types
[params-sequence]: https://pyo3.rs/latest/class/protocols.html#mapping--sequence-types
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/python-typing-hints.md | # Typing and IDE hints for your Python package
PyO3 provides an easy to use interface to code native Python libraries in Rust. The accompanying Maturin allows you to build and publish them as a package. Yet, for a better user experience, Python libraries should provide typing hints and documentation for all public entities, so that IDEs can show them during development and type analyzing tools such as `mypy` can use them to properly verify the code.
Currently the best solution for the problem is to manually maintain `*.pyi` files and ship them along with the package.
There is a sketch of a roadmap towards completing [the `experimental-inspect` feature](./features.md#experimental-inspect) which may eventually lead to automatic type annotations generated by PyO3. This needs more testing and implementation, please see [issue #2454](https://github.com/PyO3/pyo3/issues/2454).
## Introduction to `pyi` files
`pyi` files (an abbreviation for `Python Interface`) are called "stub files" in most of the documentation related to them. A very good definition of what it is can be found in [old MyPy documentation](https://github.com/python/mypy/wiki/Creating-Stubs-For-Python-Modules):
> A stubs file only contains a description of the public interface of the module without any implementations.
There is also [extensive documentation on type stubs on the official Python typing documentation](https://typing.readthedocs.io/en/latest/source/stubs.html).
Most Python developers probably already encountered them when trying to use their IDE's "Go to Definition" function on any builtin type. For example, the definitions of a few standard exceptions look like this:
```python
class BaseException(object):
args: Tuple[Any, ...]
__cause__: BaseException | None
__context__: BaseException | None
__suppress_context__: bool
__traceback__: TracebackType | None
def __init__(self, *args: object) -> None: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def with_traceback(self: _TBE, tb: TracebackType | None) -> _TBE: ...
class SystemExit(BaseException):
code: int
class Exception(BaseException): ...
class StopIteration(Exception):
value: Any
```
As we can see, those are not full definitions containing implementation, but just a description of the interface. It is usually all that the user of the library needs.
### What do the PEPs say?
At the time of writing this documentation, the `pyi` files are referenced in three PEPs.
[PEP8 - Style Guide for Python Code - #Function Annotations](https://www.python.org/dev/peps/pep-0008/#function-annotations) (last point) recommends all third party library creators to provide stub files as the source of knowledge about the package for type checker tools.
> (...) it is expected that users of third party library packages may want to run type checkers over those packages. For this purpose [PEP 484](https://www.python.org/dev/peps/pep-0484) recommends the use of stub files: .pyi files that are read by the type checker in preference of the corresponding .py files. (...)
[PEP484 - Type Hints - #Stub Files](https://www.python.org/dev/peps/pep-0484/#stub-files) defines stub files as follows.
> Stub files are files containing type hints that are only for use by the type checker, not at runtime.
It contains a specification for them (highly recommended reading, since it contains at least one thing that is not used in normal Python code) and also some general information about where to store the stub files.
[PEP561 - Distributing and Packaging Type Information](https://www.python.org/dev/peps/pep-0561/) describes in detail how to build packages that will enable type checking. In particular it contains information about how the stub files must be distributed in order for type checkers to use them.
## How to do it?
[PEP561](https://www.python.org/dev/peps/pep-0561/) recognizes three ways of distributing type information:
* `inline` - the typing is placed directly in source (`py`) files;
* `separate package with stub files` - the typing is placed in `pyi` files distributed in their own, separate package;
* `in-package stub files` - the typing is placed in `pyi` files distributed in the same package as source files.
The first way is tricky with PyO3 since we do not have `py` files. When it has been investigated and necessary changes are implemented, this document will be updated.
The second way is easy to do, and the whole work can be fully separated from the main library code. The example repo for the package with stub files can be found in [PEP561 references section](https://www.python.org/dev/peps/pep-0561/#references): [Stub package repository](https://github.com/ethanhs/stub-package)
The third way is described below.
### Including `pyi` files in your PyO3/Maturin build package
When source files are in the same package as stub files, they should be placed next to each other. We need a way to do that with Maturin. Also, in order to mark our package as typing-enabled we need to add an empty file named `py.typed` to the package.
#### If you do not have other Python files
If you do not need to add any other Python files apart from `pyi` to the package, Maturin provides a way to do most of the work for you. As documented in the [Maturin Guide](https://github.com/PyO3/maturin/#mixed-rustpython-projects), the only thing you need to do is to create a stub file for your module named `<module_name>.pyi` in your project root and Maturin will do the rest.
```text
my-rust-project/
├── Cargo.toml
├── my_project.pyi # <<< add type stubs for Rust functions in the my_project module here
├── pyproject.toml
└── src
└── lib.rs
```
For an example `pyi` file see the [`my_project.pyi` content](#my_projectpyi-content) section.
#### If you need other Python files
If you need to add other Python files apart from `pyi` to the package, you can do it also, but that requires some more work. Maturin provides an easy way to add files to a package ([documentation](https://github.com/PyO3/maturin/blob/0dee40510083c03607834c821eea76964140a126/Readme.md#mixed-rustpython-projects)). You just need to create a folder with the name of your module next to the `Cargo.toml` file (for customization see documentation linked above).
The folder structure would be:
```text
my-project
├── Cargo.toml
├── my_project
│ ├── __init__.py
│ ├── my_project.pyi
│ ├── other_python_file.py
│ └── py.typed
├── pyproject.toml
├── Readme.md
└── src
└── lib.rs
```
Let's go a little bit more into detail regarding the files inside the package folder.
##### `__init__.py` content
As we now specify our own package content, we have to provide the `__init__.py` file, so the folder is treated as a package and we can import things from it. We can always use the same content that Maturin creates for us if we do not specify a Python source folder. For PyO3 bindings it would be:
```python
from .my_project import *
```
That way everything that is exposed by our native module can be imported directly from the package.
##### `py.typed` requirement
As stated in [PEP561](https://www.python.org/dev/peps/pep-0561/):
> Package maintainers who wish to support type checking of their code MUST add a marker file named py.typed to their package supporting typing. This marker applies recursively: if a top-level package includes it, all its sub-packages MUST support type checking as well.
If we do not include that file, some IDEs might still use our `pyi` files to show hints, but the type checkers might not. MyPy will raise an error in this situation:
```text
error: Skipping analyzing "my_project": found module but no type hints or library stubs
```
The file is just a marker file, so it should be empty.
##### `my_project.pyi` content
Our module stub file. This document does not aim at describing how to write them, since you can find a lot of documentation on it, starting from the already quoted [PEP484](https://www.python.org/dev/peps/pep-0484/#stub-files).
The example can look like this:
```python
class Car:
"""
A class representing a car.
:param body_type: the name of body type, e.g. hatchback, sedan
:param horsepower: power of the engine in horsepower
"""
def __init__(self, body_type: str, horsepower: int) -> None: ...
@classmethod
def from_unique_name(cls, name: str) -> 'Car':
"""
Creates a Car based on unique name
:param name: model name of a car to be created
:return: a Car instance with default data
"""
def best_color(self) -> str:
"""
Gets the best color for the car.
:return: the name of the color our great algorithm thinks is the best for this car
"""
```
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/module.md | # Python modules
You can create a module using `#[pymodule]`:
```rust
use pyo3::prelude::*;
#[pyfunction]
fn double(x: usize) -> usize {
x * 2
}
/// This module is implemented in Rust.
#[pymodule]
fn my_extension(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(double, m)?)
}
```
The `#[pymodule]` procedural macro takes care of exporting the initialization function of your
module to Python.
The module's name defaults to the name of the Rust function. You can override the module name by
using `#[pyo3(name = "custom_name")]`:
```rust
use pyo3::prelude::*;
#[pyfunction]
fn double(x: usize) -> usize {
x * 2
}
#[pymodule(name = "custom_name")]
fn my_extension(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(double, m)?)
}
```
The name of the module must match the name of the `.so` or `.pyd`
file. Otherwise, you will get an import error in Python with the following message:
`ImportError: dynamic module does not define module export function (PyInit_name_of_your_module)`
To import the module, either:
- copy the shared library as described in [Manual builds](building-and-distribution.md#manual-builds), or
- use a tool, e.g. `maturin develop` with [maturin](https://github.com/PyO3/maturin) or
`python setup.py develop` with [setuptools-rust](https://github.com/PyO3/setuptools-rust).
## Documentation
The [Rust doc comments](https://doc.rust-lang.org/stable/book/ch03-04-comments.html) of the module
initialization function will be applied automatically as the Python docstring of your module.
For example, building off of the above code, this will print `This module is implemented in Rust.`:
```python
import my_extension
print(my_extension.__doc__)
```
## Python submodules
You can create a module hierarchy within a single extension module by using
[`Bound<'_, PyModule>::add_submodule()`]({{#PYO3_DOCS_URL}}/pyo3/prelude/trait.PyModuleMethods.html#tymethod.add_submodule).
For example, you could define the modules `parent_module` and `parent_module.child_module`.
```rust
use pyo3::prelude::*;
#[pymodule]
fn parent_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
register_child_module(m)?;
Ok(())
}
fn register_child_module(parent_module: &Bound<'_, PyModule>) -> PyResult<()> {
let child_module = PyModule::new(parent_module.py(), "child_module")?;
child_module.add_function(wrap_pyfunction!(func, &child_module)?)?;
parent_module.add_submodule(&child_module)
}
#[pyfunction]
fn func() -> String {
"func".to_string()
}
# Python::with_gil(|py| {
# use pyo3::wrap_pymodule;
# use pyo3::types::IntoPyDict;
# use pyo3::ffi::c_str;
# let parent_module = wrap_pymodule!(parent_module)(py);
# let ctx = [("parent_module", parent_module)].into_py_dict(py).unwrap();
#
# py.run(c_str!("assert parent_module.child_module.func() == 'func'"), None, Some(&ctx)).unwrap();
# })
```
Note that this does not define a package, so this won’t allow Python code to directly import
submodules by using `from parent_module import child_module`. For more information, see
[#759](https://github.com/PyO3/pyo3/issues/759) and
[#1517](https://github.com/PyO3/pyo3/issues/1517#issuecomment-808664021).
It is not necessary to add `#[pymodule]` on nested modules, which is only required on the top-level module.
## Declarative modules
Another syntax based on Rust inline modules is also available to declare modules.
For example:
```rust
# mod declarative_module_test {
use pyo3::prelude::*;
#[pyfunction]
fn double(x: usize) -> usize {
x * 2
}
#[pymodule]
mod my_extension {
use super::*;
#[pymodule_export]
use super::double; // Exports the double function as part of the module
#[pyfunction] // This will be part of the module
fn triple(x: usize) -> usize {
x * 3
}
#[pyclass] // This will be part of the module
struct Unit;
#[pymodule]
mod submodule {
// This is a submodule
}
#[pymodule_init]
fn init(m: &Bound<'_, PyModule>) -> PyResult<()> {
// Arbitrary code to run at the module initialization
m.add("double2", m.getattr("double")?)
}
}
# }
```
The `#[pymodule]` macro automatically sets the `module` attribute of the `#[pyclass]` macros declared inside of it with its name.
For nested modules, the name of the parent module is automatically added.
In the following example, the `Unit` class will have for `module` `my_extension.submodule` because it is properly nested
but the `Ext` class will have for `module` the default `builtins` because it not nested.
```rust
# mod declarative_module_module_attr_test {
use pyo3::prelude::*;
#[pyclass]
struct Ext;
#[pymodule]
mod my_extension {
use super::*;
#[pymodule_export]
use super::Ext;
#[pymodule]
mod submodule {
use super::*;
// This is a submodule
#[pyclass] // This will be part of the module
struct Unit;
}
}
# }
```
It is possible to customize the `module` value for a `#[pymodule]` with the `#[pyo3(module = "MY_MODULE")]` option.
You can provide the `submodule` argument to `pymodule()` for modules that are not top-level modules -- it is automatically set for modules nested inside of a `#[pymodule]`.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/building-and-distribution.md | # Building and distribution
This chapter of the guide goes into detail on how to build and distribute projects using PyO3. The way to achieve this is very different depending on whether the project is a Python module implemented in Rust, or a Rust binary embedding Python. For both types of project there are also common problems such as the Python version to build for and the [linker](https://en.wikipedia.org/wiki/Linker_(computing)) arguments to use.
The material in this chapter is intended for users who have already read the PyO3 [README](./index.md). It covers in turn the choices that can be made for Python modules and for Rust binaries. There is also a section at the end about cross-compiling projects using PyO3.
There is an additional sub-chapter dedicated to [supporting multiple Python versions](./building-and-distribution/multiple-python-versions.md).
## Configuring the Python version
PyO3 uses a build script (backed by the [`pyo3-build-config`] crate) to determine the Python version and set the correct linker arguments. By default it will attempt to use the following in order:
- Any active Python virtualenv.
- The `python` executable (if it's a Python 3 interpreter).
- The `python3` executable.
You can override the Python interpreter by setting the `PYO3_PYTHON` environment variable, e.g. `PYO3_PYTHON=python3.7`, `PYO3_PYTHON=/usr/bin/python3.9`, or even a PyPy interpreter `PYO3_PYTHON=pypy3`.
Once the Python interpreter is located, `pyo3-build-config` executes it to query the information in the `sysconfig` module which is needed to configure the rest of the compilation.
To validate the configuration which PyO3 will use, you can run a compilation with the environment variable `PYO3_PRINT_CONFIG=1` set. An example output of doing this is shown below:
```console
$ PYO3_PRINT_CONFIG=1 cargo build
Compiling pyo3 v0.14.1 (/home/david/dev/pyo3)
error: failed to run custom build command for `pyo3 v0.14.1 (/home/david/dev/pyo3)`
Caused by:
process didn't exit successfully: `/home/david/dev/pyo3/target/debug/build/pyo3-7a8cf4fe22e959b7/build-script-build` (exit status: 101)
--- stdout
cargo:rerun-if-env-changed=PYO3_CROSS
cargo:rerun-if-env-changed=PYO3_CROSS_LIB_DIR
cargo:rerun-if-env-changed=PYO3_CROSS_PYTHON_VERSION
cargo:rerun-if-env-changed=PYO3_PRINT_CONFIG
-- PYO3_PRINT_CONFIG=1 is set, printing configuration and halting compile --
implementation=CPython
version=3.8
shared=true
abi3=false
lib_name=python3.8
lib_dir=/usr/lib
executable=/usr/bin/python
pointer_width=64
build_flags=
suppress_build_script_link_lines=false
```
The `PYO3_ENVIRONMENT_SIGNATURE` environment variable can be used to trigger rebuilds when its value changes, it has no other effect.
### Advanced: config files
If you save the above output config from `PYO3_PRINT_CONFIG` to a file, it is possible to manually override the contents and feed it back into PyO3 using the `PYO3_CONFIG_FILE` env var.
If your build environment is unusual enough that PyO3's regular configuration detection doesn't work, using a config file like this will give you the flexibility to make PyO3 work for you. To see the full set of options supported, see the documentation for the [`InterpreterConfig` struct](https://docs.rs/pyo3-build-config/{{#PYO3_DOCS_VERSION}}/pyo3_build_config/struct.InterpreterConfig.html).
## Building Python extension modules
Python extension modules need to be compiled differently depending on the OS (and architecture) that they are being compiled for. As well as multiple OSes (and architectures), there are also many different Python versions which are actively supported. Packages uploaded to [PyPI](https://pypi.org/) usually want to upload prebuilt "wheels" covering many OS/arch/version combinations so that users on all these different platforms don't have to compile the package themselves. Package vendors can opt-in to the "abi3" limited Python API which allows their wheels to be used on multiple Python versions, reducing the number of wheels they need to compile, but restricts the functionality they can use.
There are many ways to go about this: it is possible to use `cargo` to build the extension module (along with some manual work, which varies with OS). The PyO3 ecosystem has two packaging tools, [`maturin`] and [`setuptools-rust`], which abstract over the OS difference and also support building wheels for PyPI upload.
PyO3 has some Cargo features to configure projects for building Python extension modules:
- The `extension-module` feature, which must be enabled when building Python extension modules.
- The `abi3` feature and its version-specific `abi3-pyXY` companions, which are used to opt-in to the limited Python API in order to support multiple Python versions in a single wheel.
This section describes each of these packaging tools before describing how to build manually without them. It then proceeds with an explanation of the `extension-module` feature. Finally, there is a section describing PyO3's `abi3` features.
### Packaging tools
The PyO3 ecosystem has two main choices to abstract the process of developing Python extension modules:
- [`maturin`] is a command-line tool to build, package and upload Python modules. It makes opinionated choices about project layout meaning it needs very little configuration. This makes it a great choice for users who are building a Python extension from scratch and don't need flexibility.
- [`setuptools-rust`] is an add-on for `setuptools` which adds extra keyword arguments to the `setup.py` configuration file. It requires more configuration than `maturin`, however this gives additional flexibility for users adding Rust to an existing Python package that can't satisfy `maturin`'s constraints.
Consult each project's documentation for full details on how to get started using them and how to upload wheels to PyPI. It should be noted that while `maturin` is able to build [manylinux](https://github.com/pypa/manylinux)-compliant wheels out-of-the-box, `setuptools-rust` requires a bit more effort, [relying on Docker](https://setuptools-rust.readthedocs.io/en/latest/building_wheels.html) for this purpose.
There are also [`maturin-starter`] and [`setuptools-rust-starter`] examples in the PyO3 repository.
### Manual builds
To build a PyO3-based Python extension manually, start by running `cargo build` as normal in a library project which uses PyO3's `extension-module` feature and has the [`cdylib` crate type](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-crate-type-field).
Once built, symlink (or copy) and rename the shared library from Cargo's `target/` directory to your desired output directory:
- on macOS, rename `libyour_module.dylib` to `your_module.so`.
- on Windows, rename `libyour_module.dll` to `your_module.pyd`.
- on Linux, rename `libyour_module.so` to `your_module.so`.
You can then open a Python shell in the output directory and you'll be able to run `import your_module`.
If you're packaging your library for redistribution, you should indicated the Python interpreter your library is compiled for by including the [platform tag](#platform-tags) in its name. This prevents incompatible interpreters from trying to import your library. If you're compiling for PyPy you *must* include the platform tag, or PyPy will ignore the module.
#### Bazel builds
To use PyO3 with bazel one needs to manually configure PyO3, PyO3-ffi and PyO3-macros. In particular, one needs to make sure that it is compiled with the right python flags for the version you intend to use.
For example see:
1. [github.com/abrisco/rules_pyo3](https://github.com/abrisco/rules_pyo3) -- General rules for building extension modules.
2. [github.com/OliverFM/pytorch_with_gazelle](https://github.com/OliverFM/pytorch_with_gazelle) -- for a minimal example of a repo that can use PyO3, PyTorch and Gazelle to generate python Build files.
3. [github.com/TheButlah/rules_pyo3](https://github.com/TheButlah/rules_pyo3) -- is somewhat dated.
#### Platform tags
Rather than using just the `.so` or `.pyd` extension suggested above (depending on OS), you can prefix the shared library extension with a platform tag to indicate the interpreter it is compatible with. You can query your interpreter's platform tag from the `sysconfig` module. Some example outputs of this are seen below:
```bash
# CPython 3.10 on macOS
.cpython-310-darwin.so
# PyPy 7.3 (Python 3.9) on Linux
$ python -c 'import sysconfig; print(sysconfig.get_config_var("EXT_SUFFIX"))'
.pypy39-pp73-x86_64-linux-gnu.so
```
So, for example, a valid module library name on CPython 3.10 for macOS is `your_module.cpython-310-darwin.so`, and its equivalent when compiled for PyPy 7.3 on Linux would be `your_module.pypy38-pp73-x86_64-linux-gnu.so`.
See [PEP 3149](https://peps.python.org/pep-3149/) for more background on platform tags.
#### macOS
On macOS, because the `extension-module` feature disables linking to `libpython` ([see the next section](#the-extension-module-feature)), some additional linker arguments need to be set. `maturin` and `setuptools-rust` both pass these arguments for PyO3 automatically, but projects using manual builds will need to set these directly in order to support macOS.
The easiest way to set the correct linker arguments is to add a [`build.rs`](https://doc.rust-lang.org/cargo/reference/build-scripts.html) with the following content:
```rust,ignore
fn main() {
pyo3_build_config::add_extension_module_link_args();
}
```
Remember to also add `pyo3-build-config` to the `build-dependencies` section in `Cargo.toml`.
An alternative to using `pyo3-build-config` is add the following to a cargo configuration file (e.g. `.cargo/config.toml`):
```toml
[target.x86_64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]
[target.aarch64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]
```
Using the MacOS system python3 (`/usr/bin/python3`, as opposed to python installed via homebrew, pyenv, nix, etc.) may result in runtime errors such as `Library not loaded: @rpath/Python3.framework/Versions/3.8/Python3`. These can be resolved with another addition to `.cargo/config.toml`:
```toml
[build]
rustflags = [
"-C", "link-args=-Wl,-rpath,/Library/Developer/CommandLineTools/Library/Frameworks",
]
```
Alternatively, one can include in `build.rs`:
```rust
fn main() {
println!(
"cargo:rustc-link-arg=-Wl,-rpath,/Library/Developer/CommandLineTools/Library/Frameworks"
);
}
```
For more discussion on and workarounds for MacOS linking problems [see this issue](https://github.com/PyO3/pyo3/issues/1800#issuecomment-906786649).
Finally, don't forget that on MacOS the `extension-module` feature will cause `cargo test` to fail without the `--no-default-features` flag (see [the FAQ](https://pyo3.rs/main/faq.html#i-cant-run-cargo-test-or-i-cant-build-in-a-cargo-workspace-im-having-linker-issues-like-symbol-not-found-or-undefined-reference-to-_pyexc_systemerror)).
### The `extension-module` feature
PyO3's `extension-module` feature is used to disable [linking](https://en.wikipedia.org/wiki/Linker_(computing)) to `libpython` on Unix targets.
This is necessary because by default PyO3 links to `libpython`. This makes binaries, tests, and examples "just work". However, Python extensions on Unix must not link to libpython for [manylinux](https://www.python.org/dev/peps/pep-0513/) compliance.
The downside of not linking to `libpython` is that binaries, tests, and examples (which usually embed Python) will fail to build. If you have an extension module as well as other outputs in a single project, you need to use optional Cargo features to disable the `extension-module` when you're not building the extension module. See [the FAQ](faq.md#i-cant-run-cargo-test-or-i-cant-build-in-a-cargo-workspace-im-having-linker-issues-like-symbol-not-found-or-undefined-reference-to-_pyexc_systemerror) for an example workaround.
### `Py_LIMITED_API`/`abi3`
By default, Python extension modules can only be used with the same Python version they were compiled against. For example, an extension module built for Python 3.5 can't be imported in Python 3.8. [PEP 384](https://www.python.org/dev/peps/pep-0384/) introduced the idea of the limited Python API, which would have a stable ABI enabling extension modules built with it to be used against multiple Python versions. This is also known as `abi3`.
The advantage of building extension modules using the limited Python API is that package vendors only need to build and distribute a single copy (for each OS / architecture), and users can install it on all Python versions from the [minimum version](#minimum-python-version-for-abi3) and up. The downside of this is that PyO3 can't use optimizations which rely on being compiled against a known exact Python version. It's up to you to decide whether this matters for your extension module. It's also possible to design your extension module such that you can distribute `abi3` wheels but allow users compiling from source to benefit from additional optimizations - see the [support for multiple python versions](./building-and-distribution/multiple-python-versions.md) section of this guide, in particular the `#[cfg(Py_LIMITED_API)]` flag.
There are three steps involved in making use of `abi3` when building Python packages as wheels:
1. Enable the `abi3` feature in `pyo3`. This ensures `pyo3` only calls Python C-API functions which are part of the stable API, and on Windows also ensures that the project links against the correct shared object (no special behavior is required on other platforms):
```toml
[dependencies]
pyo3 = { {{#PYO3_CRATE_VERSION}}, features = ["abi3"] }
```
2. Ensure that the built shared objects are correctly marked as `abi3`. This is accomplished by telling your build system that you're using the limited API. [`maturin`] >= 0.9.0 and [`setuptools-rust`] >= 0.11.4 support `abi3` wheels.
See the [corresponding](https://github.com/PyO3/maturin/pull/353) [PRs](https://github.com/PyO3/setuptools-rust/pull/82) for more.
3. Ensure that the `.whl` is correctly marked as `abi3`. For projects using `setuptools`, this is accomplished by passing `--py-limited-api=cp3x` (where `x` is the minimum Python version supported by the wheel, e.g. `--py-limited-api=cp35` for Python 3.5) to `setup.py bdist_wheel`.
#### Minimum Python version for `abi3`
Because a single `abi3` wheel can be used with many different Python versions, PyO3 has feature flags `abi3-py37`, `abi3-py38`, `abi3-py39` etc. to set the minimum required Python version for your `abi3` wheel.
For example, if you set the `abi3-py37` feature, your extension wheel can be used on all Python 3 versions from Python 3.7 and up. `maturin` and `setuptools-rust` will give the wheel a name like `my-extension-1.0-cp37-abi3-manylinux2020_x86_64.whl`.
As your extension module may be run with multiple different Python versions you may occasionally find you need to check the Python version at runtime to customize behavior. See [the relevant section of this guide](./building-and-distribution/multiple-python-versions.md#checking-the-python-version-at-runtime) on supporting multiple Python versions at runtime.
PyO3 is only able to link your extension module to abi3 version up to and including your host Python version. E.g., if you set `abi3-py38` and try to compile the crate with a host of Python 3.7, the build will fail.
> Note: If you set more that one of these `abi3` version feature flags the lowest version always wins. For example, with both `abi3-py37` and `abi3-py38` set, PyO3 would build a wheel which supports Python 3.7 and up.
#### Building `abi3` extensions without a Python interpreter
As an advanced feature, you can build PyO3 wheel without calling Python interpreter with the environment variable `PYO3_NO_PYTHON` set.
Also, if the build host Python interpreter is not found or is too old or otherwise unusable,
PyO3 will still attempt to compile `abi3` extension modules after displaying a warning message.
On Unix-like systems this works unconditionally; on Windows you must also set the `RUSTFLAGS` environment variable
to contain `-L native=/path/to/python/libs` so that the linker can find `python3.lib`.
If the `python3.dll` import library is not available, an experimental `generate-import-lib` crate
feature may be enabled, and the required library will be created and used by PyO3 automatically.
*Note*: MSVC targets require LLVM binutils (`llvm-dlltool`) to be available in `PATH` for
the automatic import library generation feature to work.
#### Missing features
Due to limitations in the Python API, there are a few `pyo3` features that do
not work when compiling for `abi3`. These are:
- `#[pyo3(text_signature = "...")]` does not work on classes until Python 3.10 or greater.
- The `dict` and `weakref` options on classes are not supported until Python 3.9 or greater.
- The buffer API is not supported until Python 3.11 or greater.
- Optimizations which rely on knowledge of the exact Python version compiled against.
## Embedding Python in Rust
If you want to embed the Python interpreter inside a Rust program, there are two modes in which this can be done: dynamically and statically. We'll cover each of these modes in the following sections. Each of them affect how you must distribute your program. Instead of learning how to do this yourself, you might want to consider using a project like [PyOxidizer] to ship your application and all of its dependencies in a single file.
PyO3 automatically switches between the two linking modes depending on whether the Python distribution you have configured PyO3 to use ([see above](#configuring-the-python-version)) contains a shared library or a static library. The static library is most often seen in Python distributions compiled from source without the `--enable-shared` configuration option.
### Dynamically embedding the Python interpreter
Embedding the Python interpreter dynamically is much easier than doing so statically. This is done by linking your program against a Python shared library (such as `libpython.3.9.so` on UNIX, or `python39.dll` on Windows). The implementation of the Python interpreter resides inside the shared library. This means that when the OS runs your Rust program it also needs to be able to find the Python shared library.
This mode of embedding works well for Rust tests which need access to the Python interpreter. It is also great for Rust software which is installed inside a Python virtualenv, because the virtualenv sets up appropriate environment variables to locate the correct Python shared library.
For distributing your program to non-technical users, you will have to consider including the Python shared library in your distribution as well as setting up wrapper scripts to set the right environment variables (such as `LD_LIBRARY_PATH` on UNIX, or `PATH` on Windows).
Note that PyPy cannot be embedded in Rust (or any other software). Support for this is tracked on the [PyPy issue tracker](https://github.com/pypy/pypy/issues/3836).
### Statically embedding the Python interpreter
Embedding the Python interpreter statically means including the contents of a Python static library directly inside your Rust binary. This means that to distribute your program you only need to ship your binary file: it contains the Python interpreter inside the binary!
On Windows static linking is almost never done, so Python distributions don't usually include a static library. The information below applies only to UNIX.
The Python static library is usually called `libpython.a`.
Static linking has a lot of complications, listed below. For these reasons PyO3 does not yet have first-class support for this embedding mode. See [issue 416 on PyO3's GitHub](https://github.com/PyO3/pyo3/issues/416) for more information and to discuss any issues you encounter.
The [`auto-initialize`](features.md#auto-initialize) feature is deliberately disabled when embedding the interpreter statically because this is often unintentionally done by new users to PyO3 running test programs. Trying out PyO3 is much easier using dynamic embedding.
The known complications are:
- To import compiled extension modules (such as other Rust extension modules, or those written in C), your binary must have the correct linker flags set during compilation to export the original contents of `libpython.a` so that extensions can use them (e.g. `-Wl,--export-dynamic`).
- The C compiler and flags which were used to create `libpython.a` must be compatible with your Rust compiler and flags, else you will experience compilation failures.
Significantly different compiler versions may see errors like this:
```text
lto1: fatal error: bytecode stream in file 'rust-numpy/target/release/deps/libpyo3-6a7fb2ed970dbf26.rlib' generated with LTO version 6.0 instead of the expected 6.2
```
Mismatching flags may lead to errors like this:
```text
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/libpython3.9.a(zlibmodule.o): relocation R_X86_64_32 against `.data' can not be used when making a PIE object; recompile with -fPIE
```
If you encounter these or other complications when linking the interpreter statically, discuss them on [issue 416 on PyO3's GitHub](https://github.com/PyO3/pyo3/issues/416). It is hoped that eventually that discussion will contain enough information and solutions that PyO3 can offer first-class support for static embedding.
### Import your module when embedding the Python interpreter
When you run your Rust binary with an embedded interpreter, any `#[pymodule]` created modules won't be accessible to import unless added to a table called `PyImport_Inittab` before the embedded interpreter is initialized. This will cause Python statements in your embedded interpreter such as `import your_new_module` to fail. You can call the macro [`append_to_inittab`]({{#PYO3_DOCS_URL}}/pyo3/macro.append_to_inittab.html) with your module before initializing the Python interpreter to add the module function into that table. (The Python interpreter will be initialized by calling `prepare_freethreaded_python`, `with_embedded_python_interpreter`, or `Python::with_gil` with the [`auto-initialize`](features.md#auto-initialize) feature enabled.)
## Cross Compiling
Thanks to Rust's great cross-compilation support, cross-compiling using PyO3 is relatively straightforward. To get started, you'll need a few pieces of software:
* A toolchain for your target.
* The appropriate options in your Cargo `.config` for the platform you're targeting and the toolchain you are using.
* A Python interpreter that's already been compiled for your target (optional when building "abi3" extension modules).
* A Python interpreter that is built for your host and available through the `PATH` or setting the [`PYO3_PYTHON`](#configuring-the-python-version) variable (optional when building "abi3" extension modules).
After you've obtained the above, you can build a cross-compiled PyO3 module by using Cargo's `--target` flag. PyO3's build script will detect that you are attempting a cross-compile based on your host machine and the desired target.
When cross-compiling, PyO3's build script cannot execute the target Python interpreter to query the configuration, so there are a few additional environment variables you may need to set:
* `PYO3_CROSS`: If present this variable forces PyO3 to configure as a cross-compilation.
* `PYO3_CROSS_LIB_DIR`: This variable can be set to the directory containing the target's libpython DSO and the associated `_sysconfigdata*.py` file for Unix-like targets, or the Python DLL import libraries for the Windows target. This variable is only needed when the output binary must link to libpython explicitly (e.g. when targeting Windows and Android or embedding a Python interpreter), or when it is absolutely required to get the interpreter configuration from `_sysconfigdata*.py`.
* `PYO3_CROSS_PYTHON_VERSION`: Major and minor version (e.g. 3.9) of the target Python installation. This variable is only needed if PyO3 cannot determine the version to target from `abi3-py3*` features, or if `PYO3_CROSS_LIB_DIR` is not set, or if there are multiple versions of Python present in `PYO3_CROSS_LIB_DIR`.
* `PYO3_CROSS_PYTHON_IMPLEMENTATION`: Python implementation name ("CPython" or "PyPy") of the target Python installation. CPython is assumed by default when this variable is not set, unless `PYO3_CROSS_LIB_DIR` is set for a Unix-like target and PyO3 can get the interpreter configuration from `_sysconfigdata*.py`.
An experimental `pyo3` crate feature `generate-import-lib` enables the user to cross-compile
extension modules for Windows targets without setting the `PYO3_CROSS_LIB_DIR` environment
variable or providing any Windows Python library files. It uses an external [`python3-dll-a`] crate
to generate import libraries for the Python DLL for MinGW-w64 and MSVC compile targets.
`python3-dll-a` uses the binutils `dlltool` program to generate DLL import libraries for MinGW-w64 targets.
It is possible to override the default `dlltool` command name for the cross target
by setting `PYO3_MINGW_DLLTOOL` environment variable.
*Note*: MSVC targets require LLVM binutils or MSVC build tools to be available on the host system.
More specifically, `python3-dll-a` requires `llvm-dlltool` or `lib.exe` executable to be present in `PATH` when
targeting `*-pc-windows-msvc`. The Zig compiler executable can be used in place of `llvm-dlltool` when the `ZIG_COMMAND`
environment variable is set to the installed Zig program name (`"zig"` or `"python -m ziglang"`).
An example might look like the following (assuming your target's sysroot is at `/home/pyo3/cross/sysroot` and that your target is `armv7`):
```sh
export PYO3_CROSS_LIB_DIR="/home/pyo3/cross/sysroot/usr/lib"
cargo build --target armv7-unknown-linux-gnueabihf
```
If there are multiple python versions at the cross lib directory and you cannot set a more precise location to include both the `libpython` DSO and `_sysconfigdata*.py` files, you can set the required version:
```sh
export PYO3_CROSS_PYTHON_VERSION=3.8
export PYO3_CROSS_LIB_DIR="/home/pyo3/cross/sysroot/usr/lib"
cargo build --target armv7-unknown-linux-gnueabihf
```
Or another example with the same sys root but building for Windows:
```sh
export PYO3_CROSS_PYTHON_VERSION=3.9
export PYO3_CROSS_LIB_DIR="/home/pyo3/cross/sysroot/usr/lib"
cargo build --target x86_64-pc-windows-gnu
```
Any of the `abi3-py3*` features can be enabled instead of setting `PYO3_CROSS_PYTHON_VERSION` in the above examples.
`PYO3_CROSS_LIB_DIR` can often be omitted when cross compiling extension modules for Unix and macOS targets,
or when cross compiling extension modules for Windows and the experimental `generate-import-lib`
crate feature is enabled.
The following resources may also be useful for cross-compiling:
- [github.com/japaric/rust-cross](https://github.com/japaric/rust-cross) is a primer on cross compiling Rust.
- [github.com/rust-embedded/cross](https://github.com/rust-embedded/cross) uses Docker to make Rust cross-compilation easier.
[`pyo3-build-config`]: https://github.com/PyO3/pyo3/tree/main/pyo3-build-config
[`maturin-starter`]: https://github.com/PyO3/pyo3/tree/main/examples/maturin-starter
[`setuptools-rust-starter`]: https://github.com/PyO3/pyo3/tree/main/examples/setuptools-rust-starter
[`maturin`]: https://github.com/PyO3/maturin
[`setuptools-rust`]: https://github.com/PyO3/setuptools-rust
[PyOxidizer]: https://github.com/indygreg/PyOxidizer
[`python3-dll-a`]: https://docs.rs/python3-dll-a/latest/python3_dll_a/
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/changelog.md | {{#include ../../CHANGELOG.md}}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/contributing.md | {{#include ../../Contributing.md}}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/trait-bounds.md | # Using in Python a Rust function with trait bounds
PyO3 allows for easy conversion from Rust to Python for certain functions and classes (see the [conversion table](conversions/tables.md)).
However, it is not always straightforward to convert Rust code that requires a given trait implementation as an argument.
This tutorial explains how to convert a Rust function that takes a trait as argument for use in Python with classes implementing the same methods as the trait.
Why is this useful?
### Pros
- Make your Rust code available to Python users
- Code complex algorithms in Rust with the help of the borrow checker
### Cons
- Not as fast as native Rust (type conversion has to be performed and one part of the code runs in Python)
- You need to adapt your code to expose it
## Example
Let's work with the following basic example of an implementation of a optimization solver operating on a given model.
Let's say we have a function `solve` that operates on a model and mutates its state.
The argument of the function can be any model that implements the `Model` trait :
```rust
# #![allow(dead_code)]
pub trait Model {
fn set_variables(&mut self, inputs: &Vec<f64>);
fn compute(&mut self);
fn get_results(&self) -> Vec<f64>;
}
pub fn solve<T: Model>(model: &mut T) {
println!("Magic solver that mutates the model into a resolved state");
}
```
Let's assume we have the following constraints:
- We cannot change that code as it runs on many Rust models.
- We also have many Python models that cannot be solved as this solver is not available in that language.
Rewriting it in Python would be cumbersome and error-prone, as everything is already available in Rust.
How could we expose this solver to Python thanks to PyO3 ?
## Implementation of the trait bounds for the Python class
If a Python class implements the same three methods as the `Model` trait, it seems logical it could be adapted to use the solver.
However, it is not possible to pass a `PyObject` to it as it does not implement the Rust trait (even if the Python model has the required methods).
In order to implement the trait, we must write a wrapper around the calls in Rust to the Python model.
The method signatures must be the same as the trait, keeping in mind that the Rust trait cannot be changed for the purpose of making the code available in Python.
The Python model we want to expose is the following one, which already contains all the required methods:
```python
class Model:
def set_variables(self, inputs):
self.inputs = inputs
def compute(self):
self.results = [elt**2 - 3 for elt in self.inputs]
def get_results(self):
return self.results
```
The following wrapper will call the Python model from Rust, using a struct to hold the model as a `PyAny` object:
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
use pyo3::types::PyList;
# pub trait Model {
# fn set_variables(&mut self, inputs: &Vec<f64>);
# fn compute(&mut self);
# fn get_results(&self) -> Vec<f64>;
# }
struct UserModel {
model: Py<PyAny>,
}
impl Model for UserModel {
fn set_variables(&mut self, var: &Vec<f64>) {
println!("Rust calling Python to set the variables");
Python::with_gil(|py| {
self.model
.bind(py)
.call_method("set_variables", (PyList::new(py, var).unwrap(),), None)
.unwrap();
})
}
fn get_results(&self) -> Vec<f64> {
println!("Rust calling Python to get the results");
Python::with_gil(|py| {
self.model
.bind(py)
.call_method("get_results", (), None)
.unwrap()
.extract()
.unwrap()
})
}
fn compute(&mut self) {
println!("Rust calling Python to perform the computation");
Python::with_gil(|py| {
self.model
.bind(py)
.call_method("compute", (), None)
.unwrap();
})
}
}
```
Now that this bit is implemented, let's expose the model wrapper to Python.
Let's add the PyO3 annotations and add a constructor:
```rust
# #![allow(dead_code)]
# pub trait Model {
# fn set_variables(&mut self, inputs: &Vec<f64>);
# fn compute(&mut self);
# fn get_results(&self) -> Vec<f64>;
# }
# use pyo3::prelude::*;
#[pyclass]
struct UserModel {
model: Py<PyAny>,
}
#[pymodule]
fn trait_exposure(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<UserModel>()?;
Ok(())
}
#[pymethods]
impl UserModel {
#[new]
pub fn new(model: Py<PyAny>) -> Self {
UserModel { model }
}
}
```
Now we add the PyO3 annotations to the trait implementation:
```rust,ignore
#[pymethods]
impl Model for UserModel {
// the previous trait implementation
}
```
However, the previous code will not compile. The compilation error is the following one:
`error: #[pymethods] cannot be used on trait impl blocks`
That's a bummer!
However, we can write a second wrapper around these functions to call them directly.
This wrapper will also perform the type conversions between Python and Rust.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::PyList;
#
# pub trait Model {
# fn set_variables(&mut self, inputs: &Vec<f64>);
# fn compute(&mut self);
# fn get_results(&self) -> Vec<f64>;
# }
#
# #[pyclass]
# struct UserModel {
# model: Py<PyAny>,
# }
#
# impl Model for UserModel {
# fn set_variables(&mut self, var: &Vec<f64>) {
# println!("Rust calling Python to set the variables");
# Python::with_gil(|py| {
# self.model.bind(py)
# .call_method("set_variables", (PyList::new(py, var).unwrap(),), None)
# .unwrap();
# })
# }
#
# fn get_results(&self) -> Vec<f64> {
# println!("Rust calling Python to get the results");
# Python::with_gil(|py| {
# self.model
# .bind(py)
# .call_method("get_results", (), None)
# .unwrap()
# .extract()
# .unwrap()
# })
# }
#
# fn compute(&mut self) {
# println!("Rust calling Python to perform the computation");
# Python::with_gil(|py| {
# self.model
# .bind(py)
# .call_method("compute", (), None)
# .unwrap();
# })
#
# }
# }
#[pymethods]
impl UserModel {
pub fn set_variables(&mut self, var: Vec<f64>) {
println!("Set variables from Python calling Rust");
Model::set_variables(self, &var)
}
pub fn get_results(&mut self) -> Vec<f64> {
println!("Get results from Python calling Rust");
Model::get_results(self)
}
pub fn compute(&mut self) {
println!("Compute from Python calling Rust");
Model::compute(self)
}
}
```
This wrapper handles the type conversion between the PyO3 requirements and the trait.
In order to meet PyO3 requirements, this wrapper must:
- return an object of type `PyResult`
- use only values, not references in the method signatures
Let's run the file python file:
```python
class Model:
def set_variables(self, inputs):
self.inputs = inputs
def compute(self):
self.results = [elt**2 - 3 for elt in self.inputs]
def get_results(self):
return self.results
if __name__=="__main__":
import trait_exposure
myModel = Model()
my_rust_model = trait_exposure.UserModel(myModel)
my_rust_model.set_variables([2.0])
print("Print value from Python: ", myModel.inputs)
my_rust_model.compute()
print("Print value from Python through Rust: ", my_rust_model.get_results())
print("Print value directly from Python: ", myModel.get_results())
```
This outputs:
```block
Set variables from Python calling Rust
Set variables from Rust calling Python
Print value from Python: [2.0]
Compute from Python calling Rust
Compute from Rust calling Python
Get results from Python calling Rust
Get results from Rust calling Python
Print value from Python through Rust: [1.0]
Print value directly from Python: [1.0]
```
We have now successfully exposed a Rust model that implements the `Model` trait to Python!
We will now expose the `solve` function, but before, let's talk about types errors.
## Type errors in Python
What happens if you have type errors when using Python and how can you improve the error messages?
### Wrong types in Python function arguments
Let's assume in the first case that you will use in your Python file `my_rust_model.set_variables(2.0)` instead of `my_rust_model.set_variables([2.0])`.
The Rust signature expects a vector, which corresponds to a list in Python.
What happens if instead of a vector, we pass a single value ?
At the execution of Python, we get :
```block
File "main.py", line 15, in <module>
my_rust_model.set_variables(2)
TypeError
```
It is a type error and Python points to it, so it's easy to identify and solve.
### Wrong types in Python method signatures
Let's assume now that the return type of one of the methods of our Model class is wrong, for example the `get_results` method that is expected to return a `Vec<f64>` in Rust, a list in Python.
```python
class Model:
def set_variables(self, inputs):
self.inputs = inputs
def compute(self):
self.results = [elt**2 -3 for elt in self.inputs]
def get_results(self):
return self.results[0]
#return self.results <-- this is the expected output
```
This call results in the following panic:
```block
pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value: PyErr { type: Py(0x10dcf79f0, PhantomData) }
```
This error code is not helpful for a Python user that does not know anything about Rust, or someone that does not know PyO3 was used to interface the Rust code.
However, as we are responsible for making the Rust code available to Python, we can do something about it.
The issue is that we called `unwrap` anywhere we could, and therefore any panic from PyO3 will be directly forwarded to the end user.
Let's modify the code performing the type conversion to give a helpful error message to the Python user:
We used in our `get_results` method the following call that performs the type conversion:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::PyList;
#
# pub trait Model {
# fn set_variables(&mut self, inputs: &Vec<f64>);
# fn compute(&mut self);
# fn get_results(&self) -> Vec<f64>;
# }
#
# #[pyclass]
# struct UserModel {
# model: Py<PyAny>,
# }
impl Model for UserModel {
fn get_results(&self) -> Vec<f64> {
println!("Rust calling Python to get the results");
Python::with_gil(|py| {
self.model
.bind(py)
.call_method("get_results", (), None)
.unwrap()
.extract()
.unwrap()
})
}
# fn set_variables(&mut self, var: &Vec<f64>) {
# println!("Rust calling Python to set the variables");
# Python::with_gil(|py| {
# self.model.bind(py)
# .call_method("set_variables", (PyList::new(py, var).unwrap(),), None)
# .unwrap();
# })
# }
#
# fn compute(&mut self) {
# println!("Rust calling Python to perform the computation");
# Python::with_gil(|py| {
# self.model
# .bind(py)
# .call_method("compute", (), None)
# .unwrap();
# })
# }
}
```
Let's break it down in order to perform better error handling:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::PyList;
#
# pub trait Model {
# fn set_variables(&mut self, inputs: &Vec<f64>);
# fn compute(&mut self);
# fn get_results(&self) -> Vec<f64>;
# }
#
# #[pyclass]
# struct UserModel {
# model: Py<PyAny>,
# }
impl Model for UserModel {
fn get_results(&self) -> Vec<f64> {
println!("Get results from Rust calling Python");
Python::with_gil(|py| {
let py_result: Bound<'_, PyAny> = self
.model
.bind(py)
.call_method("get_results", (), None)
.unwrap();
if py_result.get_type().name().unwrap() != "list" {
panic!(
"Expected a list for the get_results() method signature, got {}",
py_result.get_type().name().unwrap()
);
}
py_result.extract()
})
.unwrap()
}
# fn set_variables(&mut self, var: &Vec<f64>) {
# println!("Rust calling Python to set the variables");
# Python::with_gil(|py| {
# let py_model = self.model.bind(py)
# .call_method("set_variables", (PyList::new(py, var).unwrap(),), None)
# .unwrap();
# })
# }
#
# fn compute(&mut self) {
# println!("Rust calling Python to perform the computation");
# Python::with_gil(|py| {
# self.model
# .bind(py)
# .call_method("compute", (), None)
# .unwrap();
# })
# }
}
```
By doing so, you catch the result of the Python computation and check its type in order to be able to deliver a better error message before performing the unwrapping.
Of course, it does not cover all the possible wrong outputs:
the user could return a list of strings instead of a list of floats.
In this case, a runtime panic would still occur due to PyO3, but with an error message much more difficult to decipher for non-rust user.
It is up to the developer exposing the rust code to decide how much effort to invest into Python type error handling and improved error messages.
## The final code
Now let's expose the `solve()` function to make it available from Python.
It is not possible to directly expose the `solve` function to Python, as the type conversion cannot be performed.
It requires an object implementing the `Model` trait as input.
However, the `UserModel` already implements this trait.
Because of this, we can write a function wrapper that takes the `UserModel`--which has already been exposed to Python--as an argument in order to call the core function `solve`.
It is also required to make the struct public.
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
use pyo3::types::PyList;
pub trait Model {
fn set_variables(&mut self, var: &Vec<f64>);
fn get_results(&self) -> Vec<f64>;
fn compute(&mut self);
}
pub fn solve<T: Model>(model: &mut T) {
println!("Magic solver that mutates the model into a resolved state");
}
#[pyfunction]
#[pyo3(name = "solve")]
pub fn solve_wrapper(model: &mut UserModel) {
solve(model);
}
#[pyclass]
pub struct UserModel {
model: Py<PyAny>,
}
#[pymodule]
fn trait_exposure(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<UserModel>()?;
m.add_function(wrap_pyfunction!(solve_wrapper, m)?)?;
Ok(())
}
#[pymethods]
impl UserModel {
#[new]
pub fn new(model: Py<PyAny>) -> Self {
UserModel { model }
}
pub fn set_variables(&mut self, var: Vec<f64>) {
println!("Set variables from Python calling Rust");
Model::set_variables(self, &var)
}
pub fn get_results(&mut self) -> Vec<f64> {
println!("Get results from Python calling Rust");
Model::get_results(self)
}
pub fn compute(&mut self) {
Model::compute(self)
}
}
impl Model for UserModel {
fn set_variables(&mut self, var: &Vec<f64>) {
println!("Rust calling Python to set the variables");
Python::with_gil(|py| {
self.model
.bind(py)
.call_method("set_variables", (PyList::new(py, var).unwrap(),), None)
.unwrap();
})
}
fn get_results(&self) -> Vec<f64> {
println!("Get results from Rust calling Python");
Python::with_gil(|py| {
let py_result: Bound<'_, PyAny> = self
.model
.bind(py)
.call_method("get_results", (), None)
.unwrap();
if py_result.get_type().name().unwrap() != "list" {
panic!(
"Expected a list for the get_results() method signature, got {}",
py_result.get_type().name().unwrap()
);
}
py_result.extract()
})
.unwrap()
}
fn compute(&mut self) {
println!("Rust calling Python to perform the computation");
Python::with_gil(|py| {
self.model
.bind(py)
.call_method("compute", (), None)
.unwrap();
})
}
}
```
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/function.md | # Python functions
The `#[pyfunction]` attribute is used to define a Python function from a Rust function. Once defined, the function needs to be added to a [module](./module.md) using the `wrap_pyfunction!` macro.
The following example defines a function called `double` in a Python module called `my_extension`:
```rust
use pyo3::prelude::*;
#[pyfunction]
fn double(x: usize) -> usize {
x * 2
}
#[pymodule]
fn my_extension(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(double, m)?)
}
```
This chapter of the guide explains full usage of the `#[pyfunction]` attribute. In this first section, the following topics are covered:
- [Function options](#function-options)
- [`#[pyo3(name = "...")]`](#name)
- [`#[pyo3(signature = (...))]`](#signature)
- [`#[pyo3(text_signature = "...")]`](#text_signature)
- [`#[pyo3(pass_module)]`](#pass_module)
- [Per-argument options](#per-argument-options)
- [Advanced function patterns](#advanced-function-patterns)
- [`#[pyfn]` shorthand](#pyfn-shorthand)
There are also additional sections on the following topics:
- [Function Signatures](./function/signature.md)
## Function options
The `#[pyo3]` attribute can be used to modify properties of the generated Python function. It can take any combination of the following options:
- <a id="name"></a> `#[pyo3(name = "...")]`
Overrides the name exposed to Python.
In the following example, the Rust function `no_args_py` will be added to the Python module
`module_with_functions` as the Python function `no_args`:
```rust
use pyo3::prelude::*;
#[pyfunction]
#[pyo3(name = "no_args")]
fn no_args_py() -> usize {
42
}
#[pymodule]
fn module_with_functions(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(no_args_py, m)?)
}
# Python::with_gil(|py| {
# let m = pyo3::wrap_pymodule!(module_with_functions)(py);
# assert!(m.getattr(py, "no_args").is_ok());
# assert!(m.getattr(py, "no_args_py").is_err());
# });
```
- <a id="signature"></a> `#[pyo3(signature = (...))]`
Defines the function signature in Python. See [Function Signatures](./function/signature.md).
- <a id="text_signature"></a> `#[pyo3(text_signature = "...")]`
Overrides the PyO3-generated function signature visible in Python tooling (such as via [`inspect.signature`]). See the [corresponding topic in the Function Signatures subchapter](./function/signature.md#making-the-function-signature-available-to-python).
- <a id="pass_module" ></a> `#[pyo3(pass_module)]`
Set this option to make PyO3 pass the containing module as the first argument to the function. It is then possible to use the module in the function body. The first argument **must** be of type `&Bound<'_, PyModule>`, `Bound<'_, PyModule>`, or `Py<PyModule>`.
The following example creates a function `pyfunction_with_module` which returns the containing module's name (i.e. `module_with_fn`):
```rust
use pyo3::prelude::*;
use pyo3::types::PyString;
#[pyfunction]
#[pyo3(pass_module)]
fn pyfunction_with_module<'py>(
module: &Bound<'py, PyModule>,
) -> PyResult<Bound<'py, PyString>> {
module.name()
}
#[pymodule]
fn module_with_fn(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(pyfunction_with_module, m)?)
}
```
## Per-argument options
The `#[pyo3]` attribute can be used on individual arguments to modify properties of them in the generated function. It can take any combination of the following options:
- <a id="from_py_with"></a> `#[pyo3(from_py_with = "...")]`
Set this on an option to specify a custom function to convert the function argument from Python to the desired Rust type, instead of using the default `FromPyObject` extraction. The function signature must be `fn(&Bound<'_, PyAny>) -> PyResult<T>` where `T` is the Rust type of the argument.
The following example uses `from_py_with` to convert the input Python object to its length:
```rust
use pyo3::prelude::*;
fn get_length(obj: &Bound<'_, PyAny>) -> PyResult<usize> {
obj.len()
}
#[pyfunction]
fn object_length(#[pyo3(from_py_with = "get_length")] argument: usize) -> usize {
argument
}
# Python::with_gil(|py| {
# let f = pyo3::wrap_pyfunction!(object_length)(py).unwrap();
# assert_eq!(f.call1((vec![1, 2, 3],)).unwrap().extract::<usize>().unwrap(), 3);
# });
```
## Advanced function patterns
### Calling Python functions in Rust
You can pass Python `def`'d functions and built-in functions to Rust functions [`PyFunction`]
corresponds to regular Python functions while [`PyCFunction`] describes built-ins such as
`repr()`.
You can also use [`Bound<'_, PyAny>::is_callable`] to check if you have a callable object. `is_callable`
will return `true` for functions (including lambdas), methods and objects with a `__call__` method.
You can call the object with [`Bound<'_, PyAny>::call`] with the args as first parameter and the kwargs
(or `None`) as second parameter. There are also [`Bound<'_, PyAny>::call0`] with no args and
[`Bound<'_, PyAny>::call1`] with only positional args.
### Calling Rust functions in Python
The ways to convert a Rust function into a Python object vary depending on the function:
- Named functions, e.g. `fn foo()`: add `#[pyfunction]` and then use [`wrap_pyfunction!`] to get the corresponding [`PyCFunction`].
- Anonymous functions (or closures), e.g. `foo: fn()` either:
- use a `#[pyclass]` struct which stores the function as a field and implement `__call__` to call the stored function.
- use `PyCFunction::new_closure` to create an object directly from the function.
[`Bound<'_, PyAny>::is_callable`]: {{#PYO3_DOCS_URL}}/pyo3/prelude/trait.PyAnyMethods.html#tymethod.is_callable
[`Bound<'_, PyAny>::call`]: {{#PYO3_DOCS_URL}}/pyo3/prelude/trait.PyAnyMethods.html#tymethod.call
[`Bound<'_, PyAny>::call0`]: {{#PYO3_DOCS_URL}}/pyo3/prelude/trait.PyAnyMethods.html#tymethod.call0
[`Bound<'_, PyAny>::call1`]: {{#PYO3_DOCS_URL}}/pyo3/prelude/trait.PyAnyMethods.html#tymethod.call1
[`wrap_pyfunction!`]: {{#PYO3_DOCS_URL}}/pyo3/macro.wrap_pyfunction.html
[`PyFunction`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyFunction.html
[`PyCFunction`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyCFunction.html
### Accessing the FFI functions
In order to make Rust functions callable from Python, PyO3 generates an `extern "C"`
function whose exact signature depends on the Rust signature. (PyO3 chooses the optimal
Python argument passing convention.) It then embeds the call to the Rust function inside this
FFI-wrapper function. This wrapper handles extraction of the regular arguments and the keyword
arguments from the input `PyObject`s.
The `wrap_pyfunction` macro can be used to directly get a `Bound<PyCFunction>` given a
`#[pyfunction]` and a `Bound<PyModule>`: `wrap_pyfunction!(rust_fun, module)`.
## `#[pyfn]` shorthand
There is a shorthand to `#[pyfunction]` and `wrap_pymodule!`: the function can be placed inside the module definition and
annotated with `#[pyfn]`. To simplify PyO3, it is expected that `#[pyfn]` may be removed in a future release (See [#694](https://github.com/PyO3/pyo3/issues/694)).
An example of `#[pyfn]` is below:
```rust
use pyo3::prelude::*;
#[pymodule]
fn my_extension(m: &Bound<'_, PyModule>) -> PyResult<()> {
#[pyfn(m)]
fn double(x: usize) -> usize {
x * 2
}
Ok(())
}
```
`#[pyfn(m)]` is just syntactic sugar for `#[pyfunction]`, and takes all the same options
documented in the rest of this chapter. The code above is expanded to the following:
```rust
use pyo3::prelude::*;
#[pymodule]
fn my_extension(m: &Bound<'_, PyModule>) -> PyResult<()> {
#[pyfunction]
fn double(x: usize) -> usize {
x * 2
}
m.add_function(wrap_pyfunction!(double, m)?)
}
```
[`inspect.signature`]: https://docs.python.org/3/library/inspect.html#inspect.signature
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/parallelism.md | # Parallelism
CPython has the infamous [Global Interpreter Lock](https://docs.python.org/3/glossary.html#term-global-interpreter-lock), which prevents several threads from executing Python bytecode in parallel. This makes threading in Python a bad fit for [CPU-bound](https://en.wikipedia.org/wiki/CPU-bound) tasks and often forces developers to accept the overhead of multiprocessing.
In PyO3 parallelism can be easily achieved in Rust-only code. Let's take a look at our [word-count](https://github.com/PyO3/pyo3/blob/main/examples/word-count/src/lib.rs) example, where we have a `search` function that utilizes the [rayon](https://github.com/rayon-rs/rayon) crate to count words in parallel.
```rust,no_run
# #![allow(dead_code)]
use pyo3::prelude::*;
// These traits let us use `par_lines` and `map`.
use rayon::str::ParallelString;
use rayon::iter::ParallelIterator;
/// Count the occurrences of needle in line, case insensitive
fn count_line(line: &str, needle: &str) -> usize {
let mut total = 0;
for word in line.split(' ') {
if word == needle {
total += 1;
}
}
total
}
#[pyfunction]
fn search(contents: &str, needle: &str) -> usize {
contents
.par_lines()
.map(|line| count_line(line, needle))
.sum()
}
```
But let's assume you have a long running Rust function which you would like to execute several times in parallel. For the sake of example let's take a sequential version of the word count:
```rust,no_run
# #![allow(dead_code)]
# fn count_line(line: &str, needle: &str) -> usize {
# let mut total = 0;
# for word in line.split(' ') {
# if word == needle {
# total += 1;
# }
# }
# total
# }
#
fn search_sequential(contents: &str, needle: &str) -> usize {
contents.lines().map(|line| count_line(line, needle)).sum()
}
```
To enable parallel execution of this function, the [`Python::allow_threads`] method can be used to temporarily release the GIL, thus allowing other Python threads to run. We then have a function exposed to the Python runtime which calls `search_sequential` inside a closure passed to [`Python::allow_threads`] to enable true parallelism:
```rust,no_run
# #![allow(dead_code)]
# use pyo3::prelude::*;
#
# fn count_line(line: &str, needle: &str) -> usize {
# let mut total = 0;
# for word in line.split(' ') {
# if word == needle {
# total += 1;
# }
# }
# total
# }
#
# fn search_sequential(contents: &str, needle: &str) -> usize {
# contents.lines().map(|line| count_line(line, needle)).sum()
# }
#[pyfunction]
fn search_sequential_allow_threads(py: Python<'_>, contents: &str, needle: &str) -> usize {
py.allow_threads(|| search_sequential(contents, needle))
}
```
Now Python threads can use more than one CPU core, resolving the limitation which usually makes multi-threading in Python only good for IO-bound tasks:
```Python
from concurrent.futures import ThreadPoolExecutor
from word_count import search_sequential_allow_threads
executor = ThreadPoolExecutor(max_workers=2)
future_1 = executor.submit(
word_count.search_sequential_allow_threads, contents, needle
)
future_2 = executor.submit(
word_count.search_sequential_allow_threads, contents, needle
)
result_1 = future_1.result()
result_2 = future_2.result()
```
## Benchmark
Let's benchmark the `word-count` example to verify that we really did unlock parallelism with PyO3.
We are using `pytest-benchmark` to benchmark four word count functions:
1. Pure Python version
2. Rust parallel version
3. Rust sequential version
4. Rust sequential version executed twice with two Python threads
The benchmark script can be found [here](https://github.com/PyO3/pyo3/blob/main/examples/word-count/tests/test_word_count.py), and we can run `nox` in the `word-count` folder to benchmark these functions.
While the results of the benchmark of course depend on your machine, the relative results should be similar to this (mid 2020):
```text
-------------------------------------------------------------------------------------------------- benchmark: 4 tests -------------------------------------------------------------------------------------------------
Name (time in ms) Min Max Mean StdDev Median IQR Outliers OPS Rounds Iterations
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
test_word_count_rust_parallel 1.7315 (1.0) 4.6495 (1.0) 1.9972 (1.0) 0.4299 (1.0) 1.8142 (1.0) 0.2049 (1.0) 40;46 500.6943 (1.0) 375 1
test_word_count_rust_sequential 7.3348 (4.24) 10.3556 (2.23) 8.0035 (4.01) 0.7785 (1.81) 7.5597 (4.17) 0.8641 (4.22) 26;5 124.9457 (0.25) 121 1
test_word_count_rust_sequential_twice_with_threads 7.9839 (4.61) 10.3065 (2.22) 8.4511 (4.23) 0.4709 (1.10) 8.2457 (4.55) 0.3927 (1.92) 17;17 118.3274 (0.24) 114 1
test_word_count_python_sequential 27.3985 (15.82) 45.4527 (9.78) 28.9604 (14.50) 4.1449 (9.64) 27.5781 (15.20) 0.4638 (2.26) 3;5 34.5299 (0.07) 35 1
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
```
You can see that the Python threaded version is not much slower than the Rust sequential version, which means compared to an execution on a single CPU core the speed has doubled.
[`Python::allow_threads`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.allow_threads
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/function-calls.md | # Calling Python functions
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/conversions.md | # Type conversions
In this portion of the guide we'll talk about the mapping of Python types to Rust types offered by PyO3, as well as the traits available to perform conversions between them.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/debugging.md | # Debugging
## Macros
PyO3's attributes (`#[pyclass]`, `#[pymodule]`, etc.) are [procedural macros](https://doc.rust-lang.org/reference/procedural-macros.html), which means that they rewrite the source of the annotated item. You can view the generated source with the following command, which also expands a few other things:
```bash
cargo rustc --profile=check -- -Z unstable-options --pretty=expanded > expanded.rs; rustfmt expanded.rs
```
(You might need to install [rustfmt](https://github.com/rust-lang-nursery/rustfmt) if you don't already have it.)
You can also debug classic `!`-macros by adding `-Z trace-macros`:
```bash
cargo rustc --profile=check -- -Z unstable-options --pretty=expanded -Z trace-macros > expanded.rs; rustfmt expanded.rs
```
Note that those commands require using the nightly build of rust and may occasionally have bugs. See [cargo expand](https://github.com/dtolnay/cargo-expand) for a more elaborate and stable version of those commands.
## Running with Valgrind
Valgrind is a tool to detect memory management bugs such as memory leaks.
You first need to install a debug build of Python, otherwise Valgrind won't produce usable results. In Ubuntu there's e.g. a `python3-dbg` package.
Activate an environment with the debug interpreter and recompile. If you're on Linux, use `ldd` with the name of your binary and check that you're linking e.g. `libpython3.7d.so.1.0` instead of `libpython3.7.so.1.0`.
[Download the suppressions file for CPython](https://raw.githubusercontent.com/python/cpython/master/Misc/valgrind-python.supp).
Run Valgrind with `valgrind --suppressions=valgrind-python.supp ./my-command --with-options`
## Getting a stacktrace
The best start to investigate a crash such as an segmentation fault is a backtrace. You can set `RUST_BACKTRACE=1` as an environment variable to get the stack trace on a `panic!`. Alternatively you can use a debugger such as `gdb` to explore the issue. Rust provides a wrapper, `rust-gdb`, which has pretty-printers for inspecting Rust variables. Since PyO3 uses `cdylib` for Python shared objects, it does not receive the pretty-print debug hooks in `rust-gdb` ([rust-lang/rust#96365](https://github.com/rust-lang/rust/issues/96365)). The mentioned issue contains a workaround for enabling pretty-printers in this case.
* Link against a debug build of python as described in the previous chapter
* Run `rust-gdb <my-binary>`
* Set a breakpoint (`b`) on `rust_panic` if you are investigating a `panic!`
* Enter `r` to run
* After the crash occurred, enter `bt` or `bt full` to print the stacktrace
Often it is helpful to run a small piece of Python code to exercise a section of Rust.
```console
rust-gdb --args python -c "import my_package; my_package.sum_to_string(1, 2)"
```
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/advanced.md | # Advanced topics
## FFI
PyO3 exposes much of Python's C API through the `ffi` module.
The C API is naturally unsafe and requires you to manage reference counts, errors and specific invariants yourself. Please refer to the [C API Reference Manual](https://docs.python.org/3/c-api/) and [The Rustonomicon](https://doc.rust-lang.org/nightly/nomicon/ffi.html) before using any function from that API.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/types.md | # Python object types
PyO3 offers two main sets of types to interact with Python objects. This section of the guide expands into detail about these types and how to choose which to use.
The first set of types are the [smart pointers][smart-pointers] which all Python objects are wrapped in. These are `Py<T>`, `Bound<'py, T>`, and `Borrowed<'a, 'py, T>`. The [first section below](#pyo3s-smart-pointers) expands on each of these in detail and why there are three of them.
The second set of types are types which fill in the generic parameter `T` of the smart pointers. The most common is `PyAny`, which represents any Python object (similar to Python's `typing.Any`). There are also concrete types for many Python built-in types, such as `PyList`, `PyDict`, and `PyTuple`. User defined `#[pyclass]` types also fit this category. The [second section below](#concrete-python-types) expands on how to use these types.
## PyO3's smart pointers
PyO3's API offers three generic smart pointers: `Py<T>`, `Bound<'py, T>` and `Borrowed<'a, 'py, T>`. For each of these the type parameter `T` will be filled by a [concrete Python type](#concrete-python-types). For example, a Python list object can be represented by `Py<PyList>`, `Bound<'py, PyList>`, and `Borrowed<'a, 'py, PyList>`.
These smart pointers behave differently due to their lifetime parameters. `Py<T>` has no lifetime parameters, `Bound<'py, T>` has [the `'py` lifetime](./python-from-rust.md#the-py-lifetime) as a parameter, and `Borrowed<'a, 'py, T>` has the `'py` lifetime plus an additional lifetime `'a` to denote the lifetime it is borrowing data for. (You can read more about these lifetimes in the subsections below).
Python objects are reference counted, like [`std::sync::Arc`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html). A major reason for these smart pointers is to bring Python's reference counting to a Rust API.
The recommendation of when to use each of these smart pointers is as follows:
- Use `Bound<'py, T>` for as much as possible, as it offers the most efficient and complete API.
- Use `Py<T>` mostly just for storage inside Rust `struct`s which do not want to or can't add a lifetime parameter for `Bound<'py, T>`.
- `Borrowed<'a, 'py, T>` is almost never used. It is occasionally present at the boundary between Rust and the Python interpreter, for example when borrowing data from Python tuples (which is safe because they are immutable).
The sections below also explain these smart pointers in a little more detail.
### `Py<T>` (and `PyObject`)
[`Py<T>`][Py] is the foundational smart pointer in PyO3's API. The type parameter `T` denotes the type of the Python object. Very frequently this is `PyAny`, meaning any Python object. This is so common that `Py<PyAny>` has a type alias `PyObject`.
Because `Py<T>` is not bound to [the `'py` lifetime](./python-from-rust.md#the-py-lifetime), it is the type to use when storing a Python object inside a Rust `struct` or `enum` which do not want to have a lifetime parameter. In particular, [`#[pyclass]`][pyclass] types are not permitted to have a lifetime, so `Py<T>` is the correct type to store Python objects inside them.
The lack of binding to the `'py` lifetime also carries drawbacks:
- Almost all methods on `Py<T>` require a `Python<'py>` token as the first argument
- Other functionality, such as [`Drop`][Drop], needs to check at runtime for attachment to the Python GIL, at a small performance cost
Because of the drawbacks `Bound<'py, T>` is preferred for many of PyO3's APIs. In particular, `Bound<'py, T>` is better for function arguments.
To convert a `Py<T>` into a `Bound<'py, T>`, the `Py::bind` and `Py::into_bound` methods are available. `Bound<'py, T>` can be converted back into `Py<T>` using [`Bound::unbind`].
### `Bound<'py, T>`
[`Bound<'py, T>`][Bound] is the counterpart to `Py<T>` which is also bound to the `'py` lifetime. It can be thought of as equivalent to the Rust tuple `(Python<'py>, Py<T>)`.
By having the binding to the `'py` lifetime, `Bound<'py, T>` can offer the complete PyO3 API at maximum efficiency. This means that `Bound<'py, T>` should usually be used whenever carrying this lifetime is acceptable, and `Py<T>` otherwise.
`Bound<'py, T>` engages in Python reference counting. This means that `Bound<'py, T>` owns a Python object. Rust code which just wants to borrow a Python object should use a shared reference `&Bound<'py, T>`. Just like `std::sync::Arc`, using `.clone()` and `drop()` will cheaply increment and decrement the reference count of the object (just in this case, the reference counting is implemented by the Python interpreter itself).
To give an example of how `Bound<'py, T>` is PyO3's primary API type, consider the following Python code:
```python
def example():
x = list() # create a Python list
x.append(1) # append the integer 1 to it
y = x # create a second reference to the list
del x # delete the original reference
```
Using PyO3's API, and in particular `Bound<'py, PyList>`, this code translates into the following Rust code:
```rust
use pyo3::prelude::*;
use pyo3::types::PyList;
fn example<'py>(py: Python<'py>) -> PyResult<()> {
let x: Bound<'py, PyList> = PyList::empty(py);
x.append(1)?;
let y: Bound<'py, PyList> = x.clone(); // y is a new reference to the same list
drop(x); // release the original reference x
Ok(())
}
# Python::with_gil(example).unwrap();
```
Or, without the type annotations:
```rust
use pyo3::prelude::*;
use pyo3::types::PyList;
fn example(py: Python<'_>) -> PyResult<()> {
let x = PyList::empty(py);
x.append(1)?;
let y = x.clone();
drop(x);
Ok(())
}
# Python::with_gil(example).unwrap();
```
#### Function argument lifetimes
Because the `'py` lifetime often appears in many function arguments as part of the `Bound<'py, T>` smart pointer, the Rust compiler will often require annotations of input and output lifetimes. This occurs when the function output has at least one lifetime, and there is more than one lifetime present on the inputs.
To demonstrate, consider this function which takes accepts Python objects and applies the [Python `+` operation][PyAnyMethods::add] to them:
```rust,compile_fail
# use pyo3::prelude::*;
fn add(left: &'_ Bound<'_, PyAny>, right: &'_ Bound<'_, PyAny>) -> PyResult<Bound<'_, PyAny>> {
left.add(right)
}
```
Because the Python `+` operation might raise an exception, this function returns `PyResult<Bound<'_, PyAny>>`. It doesn't need ownership of the inputs, so it takes `&Bound<'_, PyAny>` shared references. To demonstrate the point, all lifetimes have used the wildcard `'_` to allow the Rust compiler to attempt to infer them. Because there are four input lifetimes (two lifetimes of the shared references, and two `'py` lifetimes unnamed inside the `Bound<'_, PyAny>` pointers), the compiler cannot reason about which must be connected to the output.
The correct way to solve this is to add the `'py` lifetime as a parameter for the function, and name all the `'py` lifetimes inside the `Bound<'py, PyAny>` smart pointers. For the shared references, it's also fine to reduce `&'_` to just `&`. The working end result is below:
```rust
# use pyo3::prelude::*;
fn add<'py>(
left: &Bound<'py, PyAny>,
right: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
left.add(right)
}
# Python::with_gil(|py| {
# let s = pyo3::types::PyString::new(py, "s");
# assert!(add(&s, &s).unwrap().eq("ss").unwrap());
# })
```
If naming the `'py` lifetime adds unwanted complexity to the function signature, it is also acceptable to return `PyObject` (aka `Py<PyAny>`), which has no lifetime. The cost is instead paid by a slight increase in implementation complexity, as seen by the introduction of a call to [`Bound::unbind`]:
```rust
# use pyo3::prelude::*;
fn add(left: &Bound<'_, PyAny>, right: &Bound<'_, PyAny>) -> PyResult<PyObject> {
let output: Bound<'_, PyAny> = left.add(right)?;
Ok(output.unbind())
}
# Python::with_gil(|py| {
# let s = pyo3::types::PyString::new(py, "s");
# assert!(add(&s, &s).unwrap().bind(py).eq("ss").unwrap());
# })
```
### `Borrowed<'a, 'py, T>`
[`Borrowed<'a, 'py, T>`][Borrowed] is an advanced type used just occasionally at the edge of interaction with the Python interpreter. It can be thought of as analogous to the shared reference `&'a Bound<'py, T>`. The difference is that `Borrowed<'a, 'py, T>` is just a smart pointer rather than a reference-to-a-smart-pointer, which is a helpful reduction in indirection in specific interactions with the Python interpreter.
`Borrowed<'a, 'py, T>` dereferences to `Bound<'py, T>`, so all methods on `Bound<'py, T>` are available on `Borrowed<'a, 'py, T>`.
An example where `Borrowed<'a, 'py, T>` is used is in [`PyTupleMethods::get_borrowed_item`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyTupleMethods.html#tymethod.get_item):
```rust
use pyo3::prelude::*;
use pyo3::types::PyTuple;
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
// Create a new tuple with the elements (0, 1, 2)
let t = PyTuple::new(py, [0, 1, 2])?;
for i in 0..=2 {
let entry: Borrowed<'_, 'py, PyAny> = t.get_borrowed_item(i)?;
// `PyAnyMethods::extract` is available on `Borrowed`
// via the dereference to `Bound`
let value: usize = entry.extract()?;
assert_eq!(i, value);
}
# Ok(())
# }
# Python::with_gil(example).unwrap();
```
### Casting between smart pointer types
To convert between `Py<T>` and `Bound<'py, T>` use the `bind()` / `into_bound()` methods. Use the `as_unbound()` / `unbind()` methods to go back from `Bound<'py, T>` to `Py<T>`.
```rust,ignore
let obj: Py<PyAny> = ...;
let bound: &Bound<'py, PyAny> = obj.bind(py);
let bound: Bound<'py, PyAny> = obj.into_bound(py);
let obj: &Py<PyAny> = bound.as_unbound();
let obj: Py<PyAny> = bound.unbind();
```
To convert between `Bound<'py, T>` and `Borrowed<'a, 'py, T>` use the `as_borrowed()` method. `Borrowed<'a, 'py, T>` has a deref coercion to `Bound<'py, T>`. Use the `to_owned()` method to increment the Python reference count and to create a new `Bound<'py, T>` from the `Borrowed<'a, 'py, T>`.
```rust,ignore
let bound: Bound<'py, PyAny> = ...;
let borrowed: Borrowed<'_, 'py, PyAny> = bound.as_borrowed();
// deref coercion
let bound: &Bound<'py, PyAny> = &borrowed;
// create a new Bound by increase the Python reference count
let bound: Bound<'py, PyAny> = borrowed.to_owned();
```
To convert between `Py<T>` and `Borrowed<'a, 'py, T>` use the `bind_borrowed()` method. Use either `as_unbound()` or `.to_owned().unbind()` to go back to `Py<T>` from `Borrowed<'a, 'py, T>`, via `Bound<'py, T>`.
```rust,ignore
let obj: Py<PyAny> = ...;
let borrowed: Borrowed<'_, 'py, PyAny> = bound.as_borrowed();
// via deref coercion to Bound and then using Bound::as_unbound
let obj: &Py<PyAny> = borrowed.as_unbound();
// via a new Bound by increasing the Python reference count, and unbind it
let obj: Py<PyAny> = borrowed.to_owned().unbind().
```
## Concrete Python types
In all of `Py<T>`, `Bound<'py, T>`, and `Borrowed<'a, 'py, T>`, the type parameter `T` denotes the type of the Python object referred to by the smart pointer.
This parameter `T` can be filled by:
- [`PyAny`][PyAny], which represents any Python object,
- Native Python types such as `PyList`, `PyTuple`, and `PyDict`, and
- [`#[pyclass]`][pyclass] types defined from Rust
The following subsections covers some further detail about how to work with these types:
- the APIs that are available for these concrete types,
- how to cast `Bound<'py, T>` to a specific concrete type, and
- how to get Rust data out of a `Bound<'py, T>`.
### Using APIs for concrete Python types
Each concrete Python type such as `PyAny`, `PyTuple` and `PyDict` exposes its API on the corresponding bound smart pointer `Bound<'py, PyAny>`, `Bound<'py, PyTuple>` and `Bound<'py, PyDict>`.
Each type's API is exposed as a trait: [`PyAnyMethods`], [`PyTupleMethods`], [`PyDictMethods`], and so on for all concrete types. Using traits rather than associated methods on the `Bound` smart pointer is done for a couple of reasons:
- Clarity of documentation: each trait gets its own documentation page in the PyO3 API docs. If all methods were on the `Bound` smart pointer directly, the vast majority of PyO3's API would be on a single, extremely long, documentation page.
- Consistency: downstream code implementing Rust APIs for existing Python types can also follow this pattern of using a trait. Downstream code would not be allowed to add new associated methods directly on the `Bound` type.
- Future design: it is hoped that a future Rust with [arbitrary self types](https://github.com/rust-lang/rust/issues/44874) will remove the need for these traits in favour of placing the methods directly on `PyAny`, `PyTuple`, `PyDict`, and so on.
These traits are all included in the `pyo3::prelude` module, so with the glob import `use pyo3::prelude::*` the full PyO3 API is made available to downstream code.
The following function accesses the first item in the input Python list, using the `.get_item()` method from the `PyListMethods` trait:
```rust
use pyo3::prelude::*;
use pyo3::types::PyList;
fn get_first_item<'py>(list: &Bound<'py, PyList>) -> PyResult<Bound<'py, PyAny>> {
list.get_item(0)
}
# Python::with_gil(|py| {
# let l = PyList::new(py, ["hello world"]).unwrap();
# assert!(get_first_item(&l).unwrap().eq("hello world").unwrap());
# })
```
### Casting between Python object types
To cast `Bound<'py, T>` smart pointers to some other type, use the [`.downcast()`][PyAnyMethods::downcast] family of functions. This converts `&Bound<'py, T>` to a different `&Bound<'py, U>`, without transferring ownership. There is also [`.downcast_into()`][PyAnyMethods::downcast_into] to convert `Bound<'py, T>` to `Bound<'py, U>` with transfer of ownership. These methods are available for all types `T` which implement the [`PyTypeCheck`] trait.
Casting to `Bound<'py, PyAny>` can be done with `.as_any()` or `.into_any()`.
For example, the following snippet shows how to cast `Bound<'py, PyAny>` to `Bound<'py, PyTuple>`:
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyTuple;
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
// create a new Python `tuple`, and use `.into_any()` to erase the type
let obj: Bound<'py, PyAny> = PyTuple::empty(py).into_any();
// use `.downcast()` to cast to `PyTuple` without transferring ownership
let _: &Bound<'py, PyTuple> = obj.downcast()?;
// use `.downcast_into()` to cast to `PyTuple` with transfer of ownership
let _: Bound<'py, PyTuple> = obj.downcast_into()?;
# Ok(())
# }
# Python::with_gil(example).unwrap()
```
Custom [`#[pyclass]`][pyclass] types implement [`PyTypeCheck`], so `.downcast()` also works for these types. The snippet below is the same as the snippet above casting instead to a custom type `MyClass`:
```rust
use pyo3::prelude::*;
#[pyclass]
struct MyClass {}
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
// create a new Python `tuple`, and use `.into_any()` to erase the type
let obj: Bound<'py, PyAny> = Bound::new(py, MyClass {})?.into_any();
// use `.downcast()` to cast to `MyClass` without transferring ownership
let _: &Bound<'py, MyClass> = obj.downcast()?;
// use `.downcast_into()` to cast to `MyClass` with transfer of ownership
let _: Bound<'py, MyClass> = obj.downcast_into()?;
# Ok(())
# }
# Python::with_gil(example).unwrap()
```
### Extracting Rust data from Python objects
To extract Rust data from Python objects, use [`.extract()`][PyAnyMethods::extract] instead of `.downcast()`. This method is available for all types which implement the [`FromPyObject`] trait.
For example, the following snippet extracts a Rust tuple of integers from a Python tuple:
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyTuple;
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
// create a new Python `tuple`, and use `.into_any()` to erase the type
let obj: Bound<'py, PyAny> = PyTuple::new(py, [1, 2, 3])?.into_any();
// extracting the Python `tuple` to a rust `(i32, i32, i32)` tuple
let (x, y, z) = obj.extract::<(i32, i32, i32)>()?;
assert_eq!((x, y, z), (1, 2, 3));
# Ok(())
# }
# Python::with_gil(example).unwrap()
```
To avoid copying data, [`#[pyclass]`][pyclass] types can directly reference Rust data stored within the Python objects without needing to `.extract()`. See the [corresponding documentation in the class section of the guide](./class.md#bound-and-interior-mutability)
for more detail.
[Bound]: {{#PYO3_DOCS_URL}}/pyo3/struct.Bound.html
[`Bound::unbind`]: {{#PYO3_DOCS_URL}}/pyo3/struct.Bound.html#method.unbind
[Py]: {{#PYO3_DOCS_URL}}/pyo3/struct.Py.html
[PyAnyMethods::add]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.add
[PyAnyMethods::extract]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.extract
[PyAnyMethods::downcast]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.downcast
[PyAnyMethods::downcast_into]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.downcast_into
[`PyTypeCheck`]: {{#PYO3_DOCS_URL}}/pyo3/type_object/trait.PyTypeCheck.html
[`PyAnyMethods`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html
[`PyDictMethods`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyDictMethods.html
[`PyTupleMethods`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyTupleMethods.html
[pyclass]: class.md
[Borrowed]: {{#PYO3_DOCS_URL}}/pyo3/struct.Borrowed.html
[Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html
[eval]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.eval
[clone_ref]: {{#PYO3_DOCS_URL}}/pyo3/struct.Py.html#method.clone_ref
[pyo3::types]: {{#PYO3_DOCS_URL}}/pyo3/types/index.html
[PyAny]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyAny.html
[PyList_append]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyList.html#method.append
[RefCell]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
[smart-pointers]: https://doc.rust-lang.org/book/ch15-00-smart-pointers.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/rust-from-python.md | # Using Rust from Python
This chapter of the guide is dedicated to explaining how to wrap Rust code into Python objects.
PyO3 uses Rust's "procedural macros" to provide a powerful yet simple API to denote what Rust code should map into Python objects.
PyO3 can create three types of Python objects:
- Python modules, via the `#[pymodule]` macro
- Python functions, via the `#[pyfunction]` macro
- Python classes, via the `#[pyclass]` macro (plus `#[pymethods]` to define methods for those classes)
The following subchapters go through each of these in turn.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/performance.md | # Performance
To achieve the best possible performance, it is useful to be aware of several tricks and sharp edges concerning PyO3's API.
## `extract` versus `downcast`
Pythonic API implemented using PyO3 are often polymorphic, i.e. they will accept `&Bound<'_, PyAny>` and try to turn this into multiple more concrete types to which the requested operation is applied. This often leads to chains of calls to `extract`, e.g.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::{exceptions::PyTypeError, types::PyList};
fn frobnicate_list<'py>(list: &Bound<'_, PyList>) -> PyResult<Bound<'py, PyAny>> {
todo!()
}
fn frobnicate_vec<'py>(vec: Vec<Bound<'py, PyAny>>) -> PyResult<Bound<'py, PyAny>> {
todo!()
}
#[pyfunction]
fn frobnicate<'py>(value: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
if let Ok(list) = value.extract::<Bound<'_, PyList>>() {
frobnicate_list(&list)
} else if let Ok(vec) = value.extract::<Vec<Bound<'_, PyAny>>>() {
frobnicate_vec(vec)
} else {
Err(PyTypeError::new_err("Cannot frobnicate that type."))
}
}
```
This suboptimal as the `FromPyObject<T>` trait requires `extract` to have a `Result<T, PyErr>` return type. For native types like `PyList`, it faster to use `downcast` (which `extract` calls internally) when the error value is ignored. This avoids the costly conversion of a `PyDowncastError` to a `PyErr` required to fulfil the `FromPyObject` contract, i.e.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::{exceptions::PyTypeError, types::PyList};
# fn frobnicate_list<'py>(list: &Bound<'_, PyList>) -> PyResult<Bound<'py, PyAny>> { todo!() }
# fn frobnicate_vec<'py>(vec: Vec<Bound<'py, PyAny>>) -> PyResult<Bound<'py, PyAny>> { todo!() }
#
#[pyfunction]
fn frobnicate<'py>(value: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
// Use `downcast` instead of `extract` as turning `PyDowncastError` into `PyErr` is quite costly.
if let Ok(list) = value.downcast::<PyList>() {
frobnicate_list(list)
} else if let Ok(vec) = value.extract::<Vec<Bound<'_, PyAny>>>() {
frobnicate_vec(vec)
} else {
Err(PyTypeError::new_err("Cannot frobnicate that type."))
}
}
```
## Access to Bound implies access to GIL token
Calling `Python::with_gil` is effectively a no-op when the GIL is already held, but checking that this is the case still has a cost. If an existing GIL token can not be accessed, for example when implementing a pre-existing trait, but a GIL-bound reference is available, this cost can be avoided by exploiting that access to GIL-bound reference gives zero-cost access to a GIL token via `Bound::py`.
For example, instead of writing
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::PyList;
struct Foo(Py<PyList>);
struct FooBound<'py>(Bound<'py, PyList>);
impl PartialEq<Foo> for FooBound<'_> {
fn eq(&self, other: &Foo) -> bool {
Python::with_gil(|py| {
let len = other.0.bind(py).len();
self.0.len() == len
})
}
}
```
use the more efficient
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::PyList;
# struct Foo(Py<PyList>);
# struct FooBound<'py>(Bound<'py, PyList>);
#
impl PartialEq<Foo> for FooBound<'_> {
fn eq(&self, other: &Foo) -> bool {
// Access to `&Bound<'py, PyAny>` implies access to `Python<'py>`.
let py = self.0.py();
let len = other.0.bind(py).len();
self.0.len() == len
}
}
```
## Disable the global reference pool
PyO3 uses global mutable state to keep track of deferred reference count updates implied by `impl<T> Drop for Py<T>` being called without the GIL being held. The necessary synchronization to obtain and apply these reference count updates when PyO3-based code next acquires the GIL is somewhat expensive and can become a significant part of the cost of crossing the Python-Rust boundary.
This functionality can be avoided by setting the `pyo3_disable_reference_pool` conditional compilation flag. This removes the global reference pool and the associated costs completely. However, it does _not_ remove the `Drop` implementation for `Py<T>` which is necessary to interoperate with existing Rust code written without PyO3-based code in mind. To stay compatible with the wider Rust ecosystem in these cases, we keep the implementation but abort when `Drop` is called without the GIL being held. If `pyo3_leak_on_drop_without_reference_pool` is additionally enabled, objects dropped without the GIL being held will be leaked instead which is always sound but might have determinal effects like resource exhaustion in the long term.
This limitation is important to keep in mind when this setting is used, especially when embedding Python code into a Rust application as it is quite easy to accidentally drop a `Py<T>` (or types containing it like `PyErr`, `PyBackedStr` or `PyBackedBytes`) returned from `Python::with_gil` without making sure to re-acquire the GIL beforehand. For example, the following code
```rust,ignore
# use pyo3::prelude::*;
# use pyo3::types::PyList;
let numbers: Py<PyList> = Python::with_gil(|py| PyList::empty(py).unbind());
Python::with_gil(|py| {
numbers.bind(py).append(23).unwrap();
});
Python::with_gil(|py| {
numbers.bind(py).append(42).unwrap();
});
```
will abort if the list not explicitly disposed via
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyList;
let numbers: Py<PyList> = Python::with_gil(|py| PyList::empty(py).unbind());
Python::with_gil(|py| {
numbers.bind(py).append(23).unwrap();
});
Python::with_gil(|py| {
numbers.bind(py).append(42).unwrap();
});
Python::with_gil(move |py| {
drop(numbers);
});
```
[conditional-compilation]: https://doc.rust-lang.org/reference/conditional-compilation.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/faq.md | # Frequently Asked Questions and troubleshooting
Sorry that you're having trouble using PyO3. If you can't find the answer to your problem in the list below, you can also reach out for help on [GitHub Discussions](https://github.com/PyO3/pyo3/discussions) and on [Discord](https://discord.gg/33kcChzH7f).
## I'm experiencing deadlocks using PyO3 with `std::sync::OnceLock`, `std::sync::LazyLock`, `lazy_static`, and `once_cell`!
`OnceLock`, `LazyLock`, and their thirdparty predecessors use blocking to ensure only one thread ever initializes them. Because the Python GIL is an additional lock this can lead to deadlocks in the following way:
1. A thread (thread A) which has acquired the Python GIL starts initialization of a `OnceLock` value.
2. The initialization code calls some Python API which temporarily releases the GIL e.g. `Python::import`.
3. Another thread (thread B) acquires the Python GIL and attempts to access the same `OnceLock` value.
4. Thread B is blocked, because it waits for `OnceLock`'s initialization to lock to release.
5. Thread A is blocked, because it waits to re-acquire the GIL which thread B still holds.
6. Deadlock.
PyO3 provides a struct [`GILOnceCell`] which implements a single-initialization API based on these types that relies on the GIL for locking. If the GIL is released or there is no GIL, then this type allows the initialization function to race but ensures that the data is only ever initialized once. If you need to ensure that the initialization function is called once and only once, you can make use of the [`OnceExt`] and [`OnceLockExt`] extension traits that enable using the standard library types for this purpose but provide new methods for these types that avoid the risk of deadlocking with the Python GIL. This means they can be used in place of other choices when you are experiencing the deadlock described above. See the documentation for [`GILOnceCell`] and [`OnceExt`] for further details and an example how to use them.
[`GILOnceCell`]: {{#PYO3_DOCS_URL}}/pyo3/sync/struct.GILOnceCell.html
[`OnceExt`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceExt.html
[`OnceLockExt`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceLockExt.html
## I can't run `cargo test`; or I can't build in a Cargo workspace: I'm having linker issues like "Symbol not found" or "Undefined reference to _PyExc_SystemError"!
Currently, [#340](https://github.com/PyO3/pyo3/issues/340) causes `cargo test` to fail with linking errors when the `extension-module` feature is activated. Linking errors can also happen when building in a cargo workspace where a different crate also uses PyO3 (see [#2521](https://github.com/PyO3/pyo3/issues/2521)). For now, there are three ways we can work around these issues.
1. Make the `extension-module` feature optional. Build with `maturin develop --features "extension-module"`
```toml
[dependencies.pyo3]
{{#PYO3_CRATE_VERSION}}
[features]
extension-module = ["pyo3/extension-module"]
```
2. Make the `extension-module` feature optional and default. Run tests with `cargo test --no-default-features`:
```toml
[dependencies.pyo3]
{{#PYO3_CRATE_VERSION}}
[features]
extension-module = ["pyo3/extension-module"]
default = ["extension-module"]
```
3. If you are using a [`pyproject.toml`](https://maturin.rs/metadata.html) file to control maturin settings, add the following section:
```toml
[tool.maturin]
features = ["pyo3/extension-module"]
# Or for maturin 0.12:
# cargo-extra-args = ["--features", "pyo3/extension-module"]
```
## I can't run `cargo test`: my crate cannot be found for tests in `tests/` directory!
The Rust book suggests to [put integration tests inside a `tests/` directory](https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests).
For a PyO3 `extension-module` project where the `crate-type` is set to `"cdylib"` in your `Cargo.toml`,
the compiler won't be able to find your crate and will display errors such as `E0432` or `E0463`:
```text
error[E0432]: unresolved import `my_crate`
--> tests/test_my_crate.rs:1:5
|
1 | use my_crate;
| ^^^^^^^^^^^^ no external crate `my_crate`
```
The best solution is to make your crate types include both `rlib` and `cdylib`:
```toml
# Cargo.toml
[lib]
crate-type = ["cdylib", "rlib"]
```
## Ctrl-C doesn't do anything while my Rust code is executing!
This is because Ctrl-C raises a SIGINT signal, which is handled by the calling Python process by simply setting a flag to action upon later. This flag isn't checked while Rust code called from Python is executing, only once control returns to the Python interpreter.
You can give the Python interpreter a chance to process the signal properly by calling `Python::check_signals`. It's good practice to call this function regularly if you have a long-running Rust function so that your users can cancel it.
## `#[pyo3(get)]` clones my field!
You may have a nested struct similar to this:
```rust
# use pyo3::prelude::*;
#[pyclass]
#[derive(Clone)]
struct Inner {/* fields omitted */}
#[pyclass]
struct Outer {
#[pyo3(get)]
inner: Inner,
}
#[pymethods]
impl Outer {
#[new]
fn __new__() -> Self {
Self { inner: Inner {} }
}
}
```
When Python code accesses `Outer`'s field, PyO3 will return a new object on every access (note that their addresses are different):
```python
outer = Outer()
a = outer.inner
b = outer.inner
assert a is b, f"a: {a}\nb: {b}"
```
```text
AssertionError: a: <builtins.Inner object at 0x00000238FFB9C7B0>
b: <builtins.Inner object at 0x00000238FFB9C830>
```
This can be especially confusing if the field is mutable, as getting the field and then mutating it won't persist - you'll just get a fresh clone of the original on the next access. Unfortunately Python and Rust don't agree about ownership - if PyO3 gave out references to (possibly) temporary Rust objects to Python code, Python code could then keep that reference alive indefinitely. Therefore returning Rust objects requires cloning.
If you don't want that cloning to happen, a workaround is to allocate the field on the Python heap and store a reference to that, by using [`Py<...>`]({{#PYO3_DOCS_URL}}/pyo3/struct.Py.html):
```rust
# use pyo3::prelude::*;
#[pyclass]
struct Inner {/* fields omitted */}
#[pyclass]
struct Outer {
inner: Py<Inner>,
}
#[pymethods]
impl Outer {
#[new]
fn __new__(py: Python<'_>) -> PyResult<Self> {
Ok(Self {
inner: Py::new(py, Inner {})?,
})
}
#[getter]
fn inner(&self, py: Python<'_>) -> Py<Inner> {
self.inner.clone_ref(py)
}
}
```
This time `a` and `b` *are* the same object:
```python
outer = Outer()
a = outer.inner
b = outer.inner
assert a is b, f"a: {a}\nb: {b}"
print(f"a: {a}\nb: {b}")
```
```text
a: <builtins.Inner object at 0x0000020044FCC670>
b: <builtins.Inner object at 0x0000020044FCC670>
```
The downside to this approach is that any Rust code working on the `Outer` struct now has to acquire the GIL to do anything with its field.
## I want to use the `pyo3` crate re-exported from dependency but the proc-macros fail!
All PyO3 proc-macros (`#[pyclass]`, `#[pyfunction]`, `#[derive(FromPyObject)]`
and so on) expect the `pyo3` crate to be available under that name in your crate
root, which is the normal situation when `pyo3` is a direct dependency of your
crate.
However, when the dependency is renamed, or your crate only indirectly depends
on `pyo3`, you need to let the macro code know where to find the crate. This is
done with the `crate` attribute:
```rust
# use pyo3::prelude::*;
# pub extern crate pyo3;
# mod reexported { pub use ::pyo3; }
# #[allow(dead_code)]
#[pyclass]
#[pyo3(crate = "reexported::pyo3")]
struct MyClass;
```
## I'm trying to call Python from Rust but I get `STATUS_DLL_NOT_FOUND` or `STATUS_ENTRYPOINT_NOT_FOUND`!
This happens on Windows when linking to the python DLL fails or the wrong one is linked. The Python DLL on Windows will usually be called something like:
- `python3X.dll` for Python 3.X, e.g. `python310.dll` for Python 3.10
- `python3.dll` when using PyO3's `abi3` feature
The DLL needs to be locatable using the [Windows DLL search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order#standard-search-order-for-unpackaged-apps). Some ways to achieve this are:
- Put the Python DLL in the same folder as your build artifacts
- Add the directory containing the Python DLL to your `PATH` environment variable, for example `C:\Users\<You>\AppData\Local\Programs\Python\Python310`
- If this happens when you are *distributing* your program, consider using [PyOxidizer](https://github.com/indygreg/PyOxidizer) to package it with your binary.
If the wrong DLL is linked it is possible that this happened because another program added itself and its own Python DLLs to `PATH`. Rearrange your `PATH` variables to give the correct DLL priority.
> **Note**: Changes to `PATH` (or any other environment variable) are not visible to existing shells. Restart it for changes to take effect.
For advanced troubleshooting, [Dependency Walker](https://www.dependencywalker.com/) can be used to diagnose linking errors.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/getting-started.md | # Installation
To get started using PyO3 you will need three things: a Rust toolchain, a Python environment, and a way to build. We'll cover each of these below.
> If you'd like to chat to the PyO3 maintainers and other PyO3 users, consider joining the [PyO3 Discord server](https://discord.gg/33kcChzH7f). We're keen to hear about your experience getting started, so we can make PyO3 as accessible as possible for everyone!
## Rust
First, make sure you have Rust installed on your system. If you haven't already done so, try following the instructions [here](https://www.rust-lang.org/tools/install). PyO3 runs on both the `stable` and `nightly` versions so you can choose whichever one fits you best. The minimum required Rust version is 1.63.
If you can run `rustc --version` and the version is new enough you're good to go!
## Python
To use PyO3, you need at least Python 3.7. While you can simply use the default Python interpreter on your system, it is recommended to use a virtual environment.
## Virtualenvs
While you can use any virtualenv manager you like, we recommend the use of `pyenv` in particular if you want to develop or test for multiple different Python versions, so that is what the examples in this book will use. The installation instructions for `pyenv` can be found [here](https://github.com/pyenv/pyenv#getting-pyenv). (Note: To get the `pyenv activate` and `pyenv virtualenv` commands, you will also need to install the [`pyenv-virtualenv`](https://github.com/pyenv/pyenv-virtualenv) plugin. The [pyenv installer](https://github.com/pyenv/pyenv-installer#installation--update--uninstallation) will install both together.)
It can be useful to keep the sources used when installing using `pyenv` so that future debugging can see the original source files. This can be done by passing the `--keep` flag as part of the `pyenv install` command.
For example:
```bash
pyenv install 3.12 --keep
```
### Building
There are a number of build and Python package management systems such as [`setuptools-rust`](https://github.com/PyO3/setuptools-rust) or [manually](./building-and-distribution.md#manual-builds). We recommend the use of `maturin`, which you can install [here](https://maturin.rs/installation.html). It is developed to work with PyO3 and provides the most "batteries included" experience, especially if you are aiming to publish to PyPI. `maturin` is just a Python package, so you can add it in the same way you already install Python packages.
System Python:
```bash
pip install maturin --user
```
pipx:
```bash
pipx install maturin
```
pyenv:
```bash
pyenv activate pyo3
pip install maturin
```
poetry:
```bash
poetry add -G dev maturin
```
After installation, you can run `maturin --version` to check that you have correctly installed it.
# Starting a new project
First you should create the folder and virtual environment that are going to contain your new project. Here we will use the recommended `pyenv`:
```bash
mkdir pyo3-example
cd pyo3-example
pyenv virtualenv pyo3
pyenv local pyo3
```
After this, you should install your build manager. In this example, we will use `maturin`. After you've activated your virtualenv, add `maturin` to it:
```bash
pip install maturin
```
Now you can initialize the new project:
```bash
maturin init
```
If `maturin` is already installed, you can create a new project using that directly as well:
```bash
maturin new -b pyo3 pyo3-example
cd pyo3-example
pyenv virtualenv pyo3
pyenv local pyo3
```
# Adding to an existing project
Sadly, `maturin` cannot currently be run in existing projects, so if you want to use Python in an existing project you basically have two options:
1. Create a new project as above and move your existing code into that project
2. Manually edit your project configuration as necessary
If you opt for the second option, here are the things you need to pay attention to:
## Cargo.toml
Make sure that the Rust crate you want to be able to access from Python is compiled into a library. You can have a binary output as well, but the code you want to access from Python has to be in the library part. Also, make sure that the crate type is `cdylib` and add PyO3 as a dependency as so:
```toml
# If you already have [package] information in `Cargo.toml`, you can ignore
# this section!
[package]
# `name` here is name of the package.
name = "pyo3_start"
# these are good defaults:
version = "0.1.0"
edition = "2021"
[lib]
# The name of the native library. This is the name which will be used in Python to import the
# library (i.e. `import string_sum`). If you change this, you must also change the name of the
# `#[pymodule]` in `src/lib.rs`.
name = "pyo3_example"
# "cdylib" is necessary to produce a shared library for Python to import from.
crate-type = ["cdylib"]
[dependencies]
pyo3 = { {{#PYO3_CRATE_VERSION}}, features = ["extension-module"] }
```
## pyproject.toml
You should also create a `pyproject.toml` with the following contents:
```toml
[build-system]
requires = ["maturin>=1,<2"]
build-backend = "maturin"
[project]
name = "pyo3_example"
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
```
## Running code
After this you can setup Rust code to be available in Python as below; for example, you can place this code in `src/lib.rs`:
```rust
use pyo3::prelude::*;
/// Formats the sum of two numbers as string.
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
/// A Python module implemented in Rust. The name of this function must match
/// the `lib.name` setting in the `Cargo.toml`, else Python will not be able to
/// import the module.
#[pymodule]
fn pyo3_example(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)
}
```
Now you can run `maturin develop` to prepare the Python package, after which you can use it like so:
```bash
$ maturin develop
# lots of progress output as maturin runs the compilation...
$ python
>>> import pyo3_example
>>> pyo3_example.sum_as_string(5, 20)
'25'
```
For more instructions on how to use Python code from Rust, see the [Python from Rust](python-from-rust.md) page.
## Maturin Import Hook
In development, any changes in the code would require running `maturin develop` before testing. To streamline the development process, you may want to install [Maturin Import Hook](https://github.com/PyO3/maturin-import-hook) which will run `maturin develop` automatically when the library with code changes is being imported.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/SUMMARY.md | # Summary
[Introduction](index.md)
---
- [Getting started](getting-started.md)
- [Using Rust from Python](rust-from-python.md)
- [Python modules](module.md)
- [Python functions](function.md)
- [Function signatures](function/signature.md)
- [Error handling](function/error-handling.md)
- [Python classes](class.md)
- [Class customizations](class/protocols.md)
- [Basic object customization](class/object.md)
- [Emulating numeric types](class/numeric.md)
- [Emulating callable objects](class/call.md)
- [Calling Python from Rust](python-from-rust.md)
- [Python object types](types.md)
- [Python exceptions](exception.md)
- [Calling Python functions](python-from-rust/function-calls.md)
- [Executing existing Python code](python-from-rust/calling-existing-code.md)
- [Type conversions](conversions.md)
- [Mapping of Rust types to Python types](conversions/tables.md)
- [Conversion traits](conversions/traits.md)
- [Using `async` and `await`](async-await.md)
- [Parallelism](parallelism.md)
- [Supporting Free-Threaded Python](free-threading.md)
- [Debugging](debugging.md)
- [Features reference](features.md)
- [Performance](performance.md)
- [Advanced topics](advanced.md)
- [Building and distribution](building-and-distribution.md)
- [Supporting multiple Python versions](building-and-distribution/multiple-python-versions.md)
- [Useful crates](ecosystem.md)
- [Logging](ecosystem/logging.md)
- [Using `async` and `await`](ecosystem/async-await.md)
- [FAQ and troubleshooting](faq.md)
---
[Appendix A: Migration guide](migration.md)
[Appendix B: Trait bounds](trait-bounds.md)
[Appendix C: Python typing hints](python-typing-hints.md)
[CHANGELOG](changelog.md)
---
[Contributing](contributing.md)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/exception.md | # Python exceptions
## Defining a new exception
Use the [`create_exception!`] macro:
```rust
use pyo3::create_exception;
create_exception!(module, MyError, pyo3::exceptions::PyException);
```
* `module` is the name of the containing module.
* `MyError` is the name of the new exception type.
For example:
```rust
use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::types::IntoPyDict;
use pyo3::exceptions::PyException;
create_exception!(mymodule, CustomError, PyException);
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let ctx = [("CustomError", py.get_type::<CustomError>())].into_py_dict(py)?;
pyo3::py_run!(
py,
*ctx,
"assert str(CustomError) == \"<class 'mymodule.CustomError'>\""
);
pyo3::py_run!(py, *ctx, "assert CustomError('oops').args == ('oops',)");
# Ok(())
})
# }
```
When using PyO3 to create an extension module, you can add the new exception to
the module like this, so that it is importable from Python:
```rust
use pyo3::prelude::*;
use pyo3::exceptions::PyException;
pyo3::create_exception!(mymodule, CustomError, PyException);
#[pymodule]
fn mymodule(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
// ... other elements added to module ...
m.add("CustomError", py.get_type::<CustomError>())?;
Ok(())
}
```
## Raising an exception
As described in the [function error handling](./function/error-handling.md) chapter, to raise an exception from a `#[pyfunction]` or `#[pymethods]`, return an `Err(PyErr)`. PyO3 will automatically raise this exception for you when returning the result to Python.
You can also manually write and fetch errors in the Python interpreter's global state:
```rust
use pyo3::{Python, PyErr};
use pyo3::exceptions::PyTypeError;
Python::with_gil(|py| {
PyTypeError::new_err("Error").restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
});
```
## Checking exception types
Python has an [`isinstance`](https://docs.python.org/3/library/functions.html#isinstance) method to check an object's type.
In PyO3 every object has the [`PyAny::is_instance`] and [`PyAny::is_instance_of`] methods which do the same thing.
```rust
use pyo3::prelude::*;
use pyo3::types::{PyBool, PyList};
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
assert!(PyBool::new(py, true).is_instance_of::<PyBool>());
let list = PyList::new(py, &[1, 2, 3, 4])?;
assert!(!list.is_instance_of::<PyBool>());
assert!(list.is_instance_of::<PyList>());
# Ok(())
})
# }
```
To check the type of an exception, you can similarly do:
```rust
# use pyo3::exceptions::PyTypeError;
# use pyo3::prelude::*;
# Python::with_gil(|py| {
# let err = PyTypeError::new_err(());
err.is_instance_of::<PyTypeError>(py);
# });
```
## Using exceptions defined in Python code
It is possible to use an exception defined in Python code as a native Rust type.
The `import_exception!` macro allows importing a specific exception class and defines a Rust type
for that exception.
```rust
#![allow(dead_code)]
use pyo3::prelude::*;
mod io {
pyo3::import_exception!(io, UnsupportedOperation);
}
fn tell(file: &Bound<'_, PyAny>) -> PyResult<u64> {
match file.call_method0("tell") {
Err(_) => Err(io::UnsupportedOperation::new_err("not supported: tell")),
Ok(x) => x.extract::<u64>(),
}
}
```
[`pyo3::exceptions`]({{#PYO3_DOCS_URL}}/pyo3/exceptions/index.html)
defines exceptions for several standard library modules.
[`create_exception!`]: {{#PYO3_DOCS_URL}}/pyo3/macro.create_exception.html
[`import_exception!`]: {{#PYO3_DOCS_URL}}/pyo3/macro.import_exception.html
[`PyErr`]: {{#PYO3_DOCS_URL}}/pyo3/struct.PyErr.html
[`PyResult`]: {{#PYO3_DOCS_URL}}/pyo3/type.PyResult.html
[`PyErr::from_value`]: {{#PYO3_DOCS_URL}}/pyo3/struct.PyErr.html#method.from_value
[`PyAny::is_instance`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.is_instance
[`PyAny::is_instance_of`]: {{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.is_instance_of
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/async-await.md | # Using `async` and `await`
*This feature is still in active development. See [the related issue](https://github.com/PyO3/pyo3/issues/1632).*
`#[pyfunction]` and `#[pymethods]` attributes also support `async fn`.
```rust
# #![allow(dead_code)]
# #[cfg(feature = "experimental-async")] {
use std::{thread, time::Duration};
use futures::channel::oneshot;
use pyo3::prelude::*;
#[pyfunction]
#[pyo3(signature=(seconds, result=None))]
async fn sleep(seconds: f64, result: Option<PyObject>) -> Option<PyObject> {
let (tx, rx) = oneshot::channel();
thread::spawn(move || {
thread::sleep(Duration::from_secs_f64(seconds));
tx.send(()).unwrap();
});
rx.await.unwrap();
result
}
# }
```
*Python awaitables instantiated with this method can only be awaited in *asyncio* context. Other Python async runtime may be supported in the future.*
## `Send + 'static` constraint
Resulting future of an `async fn` decorated by `#[pyfunction]` must be `Send + 'static` to be embedded in a Python object.
As a consequence, `async fn` parameters and return types must also be `Send + 'static`, so it is not possible to have a signature like `async fn does_not_compile<'py>(arg: Bound<'py, PyAny>) -> Bound<'py, PyAny>`.
However, there is an exception for method receivers, so async methods can accept `&self`/`&mut self`. Note that this means that the class instance is borrowed for as long as the returned future is not completed, even across yield points and while waiting for I/O operations to complete. Hence, other methods cannot obtain exclusive borrows while the future is still being polled. This is the same as how async methods in Rust generally work but it is more problematic for Rust code interfacing with Python code due to pervasive shared mutability. This strongly suggests to prefer shared borrows `&self` over exclusive ones `&mut self` to avoid racy borrow check failures at runtime.
## Implicit GIL holding
Even if it is not possible to pass a `py: Python<'py>` parameter to `async fn`, the GIL is still held during the execution of the future – it's also the case for regular `fn` without `Python<'py>`/`Bound<'py, PyAny>` parameter, yet the GIL is held.
It is still possible to get a `Python` marker using [`Python::with_gil`]({{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.with_gil); because `with_gil` is reentrant and optimized, the cost will be negligible.
## Release the GIL across `.await`
There is currently no simple way to release the GIL when awaiting a future, *but solutions are currently in development*.
Here is the advised workaround for now:
```rust,ignore
use std::{
future::Future,
pin::{Pin, pin},
task::{Context, Poll},
};
use pyo3::prelude::*;
struct AllowThreads<F>(F);
impl<F> Future for AllowThreads<F>
where
F: Future + Unpin + Send,
F::Output: Send,
{
type Output = F::Output;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let waker = cx.waker();
Python::with_gil(|gil| {
gil.allow_threads(|| pin!(&mut self.0).poll(&mut Context::from_waker(waker)))
})
}
}
```
## Cancellation
Cancellation on the Python side can be caught using [`CancelHandle`]({{#PYO3_DOCS_URL}}/pyo3/coroutine/struct.CancelHandle.html) type, by annotating a function parameter with `#[pyo3(cancel_handle)]`.
```rust
# #![allow(dead_code)]
# #[cfg(feature = "experimental-async")] {
use futures::FutureExt;
use pyo3::prelude::*;
use pyo3::coroutine::CancelHandle;
#[pyfunction]
async fn cancellable(#[pyo3(cancel_handle)] mut cancel: CancelHandle) {
futures::select! {
/* _ = ... => println!("done"), */
_ = cancel.cancelled().fuse() => println!("cancelled"),
}
}
# }
```
## The `Coroutine` type
To make a Rust future awaitable in Python, PyO3 defines a [`Coroutine`]({{#PYO3_DOCS_URL}}/pyo3/coroutine/struct.Coroutine.html) type, which implements the Python [coroutine protocol](https://docs.python.org/3/library/collections.abc.html#collections.abc.Coroutine).
Each `coroutine.send` call is translated to a `Future::poll` call. If a [`CancelHandle`]({{#PYO3_DOCS_URL}}/pyo3/coroutine/struct.CancelHandle.html) parameter is declared, the exception passed to `coroutine.throw` call is stored in it and can be retrieved with [`CancelHandle::cancelled`]({{#PYO3_DOCS_URL}}/pyo3/coroutine/struct.CancelHandle.html#method.cancelled); otherwise, it cancels the Rust future, and the exception is reraised;
*The type does not yet have a public constructor until the design is finalized.*
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/index.md | # The PyO3 user guide
Welcome to the PyO3 user guide! This book is a companion to [PyO3's API docs](https://docs.rs/pyo3). It contains examples and documentation to explain all of PyO3's use cases in detail.
The rough order of material in this user guide is as follows:
1. Getting started
2. Wrapping Rust code for use from Python
3. How to use Python code from Rust
4. Remaining topics which go into advanced concepts in detail
Please choose from the chapters on the left to jump to individual topics, or continue below to start with PyO3's README.
<hr style="opacity:0.2">
{{#include ../../README.md}}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/ecosystem.md | # The PyO3 ecosystem
This portion of the guide is dedicated to crates which are external to the main PyO3 project and provide additional functionality you might find useful.
Because these projects evolve independently of the PyO3 repository the content of these articles may fall out of date over time; please file issues on the PyO3 GitHub to alert maintainers when this is the case.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/free-threading.md | # Supporting Free-Threaded CPython
CPython 3.13 introduces an experimental "free-threaded" build of CPython that
does not rely on the [global interpreter
lock](https://docs.python.org/3/glossary.html#term-global-interpreter-lock)
(often referred to as the GIL) for thread safety. As of version 0.23, PyO3 also
has preliminary support for building Rust extensions for the free-threaded
Python build and support for calling into free-threaded Python from Rust.
If you want more background on free-threaded Python in general, see the [what's
new](https://docs.python.org/3.13/whatsnew/3.13.html#whatsnew313-free-threaded-cpython)
entry in the CPython docs, the [HOWTO
guide](https://docs.python.org/3.13/howto/free-threading-extensions.html#freethreading-extensions-howto)
for porting C extensions, and [PEP 703](https://peps.python.org/pep-0703/),
which provides the technical background for the free-threading implementation in
CPython.
In the GIL-enabled build, the global interpreter lock serializes access to the
Python runtime. The GIL is therefore a fundamental limitation to parallel
scaling of multithreaded Python workflows, due to [Amdahl's
law](https://en.wikipedia.org/wiki/Amdahl%27s_law), because any time spent
executing a parallel processing task on only one execution context fundamentally
cannot be sped up using parallelism.
The free-threaded build removes this limit on multithreaded Python scaling. This
means it's much more straightforward to achieve parallelism using the Python
[`threading`] module. If you
have ever needed to use
[`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html) to
achieve a parallel speedup for some Python code, free-threading will likely
allow the use of Python threads instead for the same workflow.
PyO3's support for free-threaded Python will enable authoring native Python
extensions that are thread-safe by construction, with much stronger safety
guarantees than C extensions. Our goal is to enable ["fearless
concurrency"](https://doc.rust-lang.org/book/ch16-00-concurrency.html) in the
native Python runtime by building on the Rust [`Send` and
`Sync`](https://doc.rust-lang.org/nomicon/send-and-sync.html) traits.
This document provides advice for porting Rust code using PyO3 to run under
free-threaded Python.
## Supporting free-threaded Python with PyO3
Many simple uses of PyO3, like exposing bindings for a "pure" Rust function
with no side-effects or defining an immutable Python class, will likely work
"out of the box" on the free-threaded build. All that will be necessary is to
annotate Python modules declared by rust code in your project to declare that
they support free-threaded Python, for example by declaring the module with
`#[pymodule(gil_used = false)]`.
At a low-level, annotating a module sets the `Py_MOD_GIL` slot on modules
defined by an extension to `Py_MOD_GIL_NOT_USED`, which allows the interpreter
to see at runtime that the author of the extension thinks the extension is
thread-safe. You should only do this if you know that your extension is
thread-safe. Because of Rust's guarantees, this is already true for many
extensions, however see below for more discussion about how to evaluate the
thread safety of existing Rust extensions and how to think about the PyO3 API
using a Python runtime with no GIL.
If you do not explicitly mark that modules are thread-safe, the Python
interpreter will re-enable the GIL at runtime while importing your module and
print a `RuntimeWarning` with a message containing the name of the module
causing it to re-enable the GIL. You can force the GIL to remain disabled by
setting the `PYTHON_GIL=0` as an environment variable or passing `-Xgil=0` when
starting Python (`0` means the GIL is turned off).
If you are sure that all data structures exposed in a `PyModule` are
thread-safe, then pass `gil_used = false` as a parameter to the
`pymodule` procedural macro declaring the module or call
`PyModule::gil_used` on a `PyModule` instance. For example:
```rust
use pyo3::prelude::*;
/// This module supports free-threaded Python
#[pymodule(gil_used = false)]
fn my_extension(m: &Bound<'_, PyModule>) -> PyResult<()> {
// add members to the module that you know are thread-safe
Ok(())
}
```
Or for a module that is set up without using the `pymodule` macro:
```rust
use pyo3::prelude::*;
# #[allow(dead_code)]
fn register_child_module(parent_module: &Bound<'_, PyModule>) -> PyResult<()> {
let child_module = PyModule::new(parent_module.py(), "child_module")?;
child_module.gil_used(false)?;
parent_module.add_submodule(&child_module)
}
```
For now you must explicitly opt in to free-threading support by annotating
modules defined in your extension. In a future version of `PyO3`, we plan to
make `gil_used = false` the default.
See the
[`string-sum`](https://github.com/PyO3/pyo3/tree/main/pyo3-ffi/examples/string-sum)
example for how to declare free-threaded support using raw FFI calls for modules
using single-phase initialization and the
[`sequential`](https://github.com/PyO3/pyo3/tree/main/pyo3-ffi/examples/sequential)
example for modules using multi-phase initialization.
## Special considerations for the free-threaded build
The free-threaded interpreter does not have a GIL, and this can make interacting
with the PyO3 API confusing, since the API was originally designed around strong
assumptions about the GIL providing locking. Additionally, since the GIL
provided locking for operations on Python objects, many existing extensions that
provide mutable data structures relied on the GIL to make interior mutability
thread-safe.
Working with PyO3 under the free-threaded interpreter therefore requires some
additional care and mental overhead compared with a GIL-enabled interpreter. We
discuss how to handle this below.
### Many symbols exposed by PyO3 have `GIL` in the name
We are aware that there are some naming issues in the PyO3 API that make it
awkward to think about a runtime environment where there is no GIL. We plan to
change the names of these types to de-emphasize the role of the GIL in future
versions of PyO3, but for now you should remember that the use of the term `GIL`
in functions and types like [`Python::with_gil`] and [`GILOnceCell`] is
historical.
Instead, you should think about whether or not a Rust thread is attached to a
Python interpreter runtime. Calling into the CPython C API is only legal when an
OS thread is explicitly attached to the interpreter runtime. In the GIL-enabled
build, this happens when the GIL is acquired. In the free-threaded build there
is no GIL, but the same C macros that release or acquire the GIL in the
GIL-enabled build instead ask the interpreter to attach the thread to the Python
runtime, and there can be many threads simultaneously attached. See [PEP
703](https://peps.python.org/pep-0703/#thread-states) for more background about
how threads can be attached and detached from the interpreter runtime, in a
manner analagous to releasing and acquiring the GIL in the GIL-enabled build.
In the GIL-enabled build, PyO3 uses the [`Python<'py>`] type and the `'py`
lifetime to signify that the global interpreter lock is held. In the
freethreaded build, holding a `'py` lifetime means only that the thread is
currently attached to the Python interpreter -- other threads can be
simultaneously interacting with the interpreter.
The main reason for obtaining a `'py` lifetime is to interact with Python
objects or call into the CPython C API. If you are not yet attached to the
Python runtime, you can register a thread using the [`Python::with_gil`]
function. Threads created via the Python [`threading`] module do not not need to
do this, but all other OS threads that interact with the Python runtime must
explicitly attach using `with_gil` and obtain a `'py` liftime.
Since there is no GIL in the free-threaded build, releasing the GIL for
long-running tasks is no longer necessary to ensure other threads run, but you
should still detach from the interpreter runtime using [`Python::allow_threads`]
when doing long-running tasks that do not require the CPython runtime. The
garbage collector can only run if all threads are detached from the runtime (in
a stop-the-world state), so detaching from the runtime allows freeing unused
memory.
### Exceptions and panics for multithreaded access of mutable `pyclass` instances
Data attached to `pyclass` instances is protected from concurrent access by a
`RefCell`-like pattern of runtime borrow checking. Like a `RefCell`, PyO3 will
raise exceptions (or in some cases panic) to enforce exclusive access for
mutable borrows. It was always possible to generate panics like this in PyO3 in
code that releases the GIL with [`Python::allow_threads`] or calling a python
method accepting `&self` from a `&mut self` (see [the docs on interior
mutability](./class.md#bound-and-interior-mutability),) but now in free-threaded
Python there are more opportunities to trigger these panics from Python because
there is no GIL to lock concurrent access to mutably borrowed data from Python.
The most straightforward way to trigger this problem to use the Python
[`threading`] module to simultaneously call a rust function that mutably borrows a
[`pyclass`]({{#PYO3_DOCS_URL}}/pyo3/attr.pyclass.html). For example,
consider the following implementation:
```rust
# use pyo3::prelude::*;
# fn main() {
#[pyclass]
#[derive(Default)]
struct ThreadIter {
count: usize,
}
#[pymethods]
impl ThreadIter {
#[new]
pub fn new() -> Self {
Default::default()
}
fn __next__(&mut self, py: Python<'_>) -> usize {
self.count += 1;
self.count
}
}
# }
```
And then if we do something like this in Python:
```python
import concurrent.futures
from my_module import ThreadIter
i = ThreadIter()
def increment():
next(i)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as tpe:
futures = [tpe.submit(increment) for _ in range(100)]
[f.result() for f in futures]
```
We will see an exception:
```text
Traceback (most recent call last)
File "example.py", line 5, in <module>
next(i)
RuntimeError: Already borrowed
```
We plan to allow user-selectable semantics for mutable pyclass definitions in
PyO3 0.24, allowing some form of opt-in locking to emulate the GIL if that is
needed. For now you should explicitly add locking, possibly using conditional
compilation or using the critical section API to avoid creating deadlocks with
the GIL.
## Thread-safe single initialization
Until version 0.23, PyO3 provided only [`GILOnceCell`] to enable deadlock-free
single initialization of data in contexts that might execute arbitrary Python
code. While we have updated [`GILOnceCell`] to avoid thread safety issues
triggered only under the free-threaded build, the design of [`GILOnceCell`] is
inherently thread-unsafe, in a manner that can be problematic even in the
GIL-enabled build.
If, for example, the function executed by [`GILOnceCell`] releases the GIL or
calls code that releases the GIL, then it is possible for multiple threads to
race to initialize the cell. While the cell will only ever be intialized
once, it can be problematic in some contexts that [`GILOnceCell`] does not block
like the standard library [`OnceLock`].
In cases where the initialization function must run exactly once, you can bring
the [`OnceExt`] or [`OnceLockExt`] traits into scope. The [`OnceExt`] trait adds
[`OnceExt::call_once_py_attached`] and [`OnceExt::call_once_force_py_attached`]
functions to the api of `std::sync::Once`, enabling use of [`Once`] in contexts
where the GIL is held. Similarly, [`OnceLockExt`] adds
[`OnceLockExt::get_or_init_py_attached`]. These functions are analogous to
[`Once::call_once`], [`Once::call_once_force`], and [`OnceLock::get_or_init`] except
they accept a [`Python<'py>`] token in addition to an `FnOnce`. All of these
functions release the GIL and re-acquire it before executing the function,
avoiding deadlocks with the GIL that are possible without using the PyO3
extension traits. Here is an example of how to use [`OnceExt`] to
enable single-initialization of a runtime cache holding a `Py<PyDict>`.
```rust
# fn main() {
# use pyo3::prelude::*;
use std::sync::Once;
use pyo3::sync::OnceExt;
use pyo3::types::PyDict;
struct RuntimeCache {
once: Once,
cache: Option<Py<PyDict>>
}
let mut cache = RuntimeCache {
once: Once::new(),
cache: None
};
Python::with_gil(|py| {
// guaranteed to be called once and only once
cache.once.call_once_py_attached(py, || {
cache.cache = Some(PyDict::new(py).unbind());
});
});
# }
```
### `GILProtected` is not exposed
[`GILProtected`] is a PyO3 type that allows mutable access to static data by
leveraging the GIL to lock concurrent access from other threads. In
free-threaded Python there is no GIL, so you will need to replace this type with
some other form of locking. In many cases, a type from
[`std::sync::atomic`](https://doc.rust-lang.org/std/sync/atomic/) or a
[`std::sync::Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) will
be sufficient.
Before:
```rust
# fn main() {
# #[cfg(not(Py_GIL_DISABLED))] {
# use pyo3::prelude::*;
use pyo3::sync::GILProtected;
use pyo3::types::{PyDict, PyNone};
use std::cell::RefCell;
static OBJECTS: GILProtected<RefCell<Vec<Py<PyDict>>>> =
GILProtected::new(RefCell::new(Vec::new()));
Python::with_gil(|py| {
// stand-in for something that executes arbitrary Python code
let d = PyDict::new(py);
d.set_item(PyNone::get(py), PyNone::get(py)).unwrap();
OBJECTS.get(py).borrow_mut().push(d.unbind());
});
# }}
```
After:
```rust
# use pyo3::prelude::*;
# fn main() {
use pyo3::types::{PyDict, PyNone};
use std::sync::Mutex;
static OBJECTS: Mutex<Vec<Py<PyDict>>> = Mutex::new(Vec::new());
Python::with_gil(|py| {
// stand-in for something that executes arbitrary Python code
let d = PyDict::new(py);
d.set_item(PyNone::get(py), PyNone::get(py)).unwrap();
// as with any `Mutex` usage, lock the mutex for as little time as possible
// in this case, we do it just while pushing into the `Vec`
OBJECTS.lock().unwrap().push(d.unbind());
});
# }
```
If you are executing arbitrary Python code while holding the lock, then you will
need to use conditional compilation to use [`GILProtected`] on GIL-enabled Python
builds and mutexes otherwise. If your use of [`GILProtected`] does not guard the
execution of arbitrary Python code or use of the CPython C API, then conditional
compilation is likely unnecessary since [`GILProtected`] was not needed in the
first place and instead Rust mutexes or atomics should be preferred. Python 3.13
introduces [`PyMutex`](https://docs.python.org/3/c-api/init.html#c.PyMutex),
which releases the GIL while the waiting for the lock, so that is another option
if you only need to support newer Python versions.
[`GILOnceCell`]: {{#PYO3_DOCS_URL}}/pyo3/sync/struct.GILOnceCell.html
[`GILProtected`]: https://docs.rs/pyo3/0.22/pyo3/sync/struct.GILProtected.html
[`Once`]: https://doc.rust-lang.org/stable/std/sync/struct.Once.html
[`Once::call_once`]: https://doc.rust-lang.org/stable/std/sync/struct.Once.html#tymethod.call_once
[`Once::call_once_force`]: https://doc.rust-lang.org/stable/std/sync/struct.Once.html#tymethod.call_once_force
[`OnceExt`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceExt.html
[`OnceExt::call_once_py_attached`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceExt.html#tymethod.call_once_py_attached
[`OnceExt::call_once_force_py_attached`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceExt.html#tymethod.call_once_force_py_attached
[`OnceLockExt`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceLockExt.html
[`OnceLockExt::get_or_init_py_attached`]: {{#PYO3_DOCS_URL}}/pyo3/sync/trait.OnceLockExt.html#tymethod.get_or_init_py_attached
[`OnceLock`]: https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html
[`OnceLock::get_or_init`]: https://doc.rust-lang.org/stable/std/sync/struct.OnceLock.html#tymethod.get_or_init
[`Python::allow_threads`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.allow_threads
[`Python::with_gil`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.with_gil
[`Python<'py>`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html
[`threading`]: https://docs.python.org/3/library/threading.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/features.md | # Features reference
PyO3 provides a number of Cargo features to customize functionality. This chapter of the guide provides detail on each of them.
By default, only the `macros` feature is enabled.
## Features for extension module authors
### `extension-module`
This feature is required when building a Python extension module using PyO3.
It tells PyO3's build script to skip linking against `libpython.so` on Unix platforms, where this must not be done.
See the [building and distribution](building-and-distribution.md#the-extension-module-feature) section for further detail.
### `abi3`
This feature is used when building Python extension modules to create wheels which are compatible with multiple Python versions.
It restricts PyO3's API to a subset of the full Python API which is guaranteed by [PEP 384](https://www.python.org/dev/peps/pep-0384/) to be forwards-compatible with future Python versions.
See the [building and distribution](building-and-distribution.md#py_limited_apiabi3) section for further detail.
### The `abi3-pyXY` features
(`abi3-py37`, `abi3-py38`, `abi3-py39`, `abi3-py310` and `abi3-py311`)
These features are extensions of the `abi3` feature to specify the exact minimum Python version which the multiple-version-wheel will support.
See the [building and distribution](building-and-distribution.md#minimum-python-version-for-abi3) section for further detail.
### `generate-import-lib`
This experimental feature is used to generate import libraries for Python DLL
for MinGW-w64 and MSVC (cross-)compile targets.
Enabling it allows to (cross-)compile extension modules to any Windows targets
without having to install the Windows Python distribution files for the target.
See the [building and distribution](building-and-distribution.md#building-abi3-extensions-without-a-python-interpreter)
section for further detail.
## Features for embedding Python in Rust
### `auto-initialize`
This feature changes [`Python::with_gil`]({{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.with_gil) to automatically initialize a Python interpreter (by calling [`prepare_freethreaded_python`]({{#PYO3_DOCS_URL}}/pyo3/fn.prepare_freethreaded_python.html)) if needed.
If you do not enable this feature, you should call `pyo3::prepare_freethreaded_python()` before attempting to call any other Python APIs.
## Advanced Features
### `experimental-async`
This feature adds support for `async fn` in `#[pyfunction]` and `#[pymethods]`.
The feature has some unfinished refinements and performance improvements. To help finish this off, see [issue #1632](https://github.com/PyO3/pyo3/issues/1632) and its associated draft PRs.
### `experimental-inspect`
This feature adds the `pyo3::inspect` module, as well as `IntoPy::type_output` and `FromPyObject::type_input` APIs to produce Python type "annotations" for Rust types.
This is a first step towards adding first-class support for generating type annotations automatically in PyO3, however work is needed to finish this off. All feedback and offers of help welcome on [issue #2454](https://github.com/PyO3/pyo3/issues/2454).
### `gil-refs`
This feature is a backwards-compatibility feature to allow continued use of the "GIL Refs" APIs deprecated in PyO3 0.21. These APIs have performance drawbacks and soundness edge cases which the newer `Bound<T>` smart pointer and accompanying APIs resolve.
This feature and the APIs it enables is expected to be removed in a future PyO3 version.
### `py-clone`
This feature was introduced to ease migration. It was found that delayed reference counts cannot be made sound and hence `Clon`ing an instance of `Py<T>` must panic without the GIL being held. To avoid migrations introducing new panics without warning, the `Clone` implementation itself is now gated behind this feature.
### `pyo3_disable_reference_pool`
This is a performance-oriented conditional compilation flag, e.g. [set via `$RUSTFLAGS`][set-configuration-options], which disabled the global reference pool and the assocaited overhead for the crossing the Python-Rust boundary. However, if enabled, `Drop`ping an instance of `Py<T>` without the GIL being held will abort the process.
### `macros`
This feature enables a dependency on the `pyo3-macros` crate, which provides the procedural macros portion of PyO3's API:
- `#[pymodule]`
- `#[pyfunction]`
- `#[pyclass]`
- `#[pymethods]`
- `#[derive(FromPyObject)]`
It also provides the `py_run!` macro.
These macros require a number of dependencies which may not be needed by users who just need PyO3 for Python FFI. Disabling this feature enables faster builds for those users, as these dependencies will not be built if this feature is disabled.
> This feature is enabled by default. To disable it, set `default-features = false` for the `pyo3` entry in your Cargo.toml.
### `multiple-pymethods`
This feature enables each `#[pyclass]` to have more than one `#[pymethods]` block.
Most users should only need a single `#[pymethods]` per `#[pyclass]`. In addition, not all platforms (e.g. Wasm) are supported by `inventory`, which is used in the implementation of the feature. For this reason this feature is not enabled by default, meaning fewer dependencies and faster compilation for the majority of users.
See [the `#[pyclass]` implementation details](class.md#implementation-details) for more information.
### `nightly`
The `nightly` feature needs the nightly Rust compiler. This allows PyO3 to use the `auto_traits` and `negative_impls` features to fix the `Python::allow_threads` function.
### `resolve-config`
The `resolve-config` feature of the `pyo3-build-config` crate controls whether that crate's
build script automatically resolves a Python interpreter / build configuration. This feature is primarily useful when building PyO3
itself. By default this feature is not enabled, meaning you can freely use `pyo3-build-config` as a standalone library to read or write PyO3 build configuration files or resolve metadata about a Python interpreter.
## Optional Dependencies
These features enable conversions between Python types and types from other Rust crates, enabling easy access to the rest of the Rust ecosystem.
### `anyhow`
Adds a dependency on [anyhow](https://docs.rs/anyhow). Enables a conversion from [anyhow](https://docs.rs/anyhow)’s [`Error`](https://docs.rs/anyhow/latest/anyhow/struct.Error.html) type to [`PyErr`]({{#PYO3_DOCS_URL}}/pyo3/struct.PyErr.html), for easy error handling.
### `chrono`
Adds a dependency on [chrono](https://docs.rs/chrono). Enables a conversion from [chrono](https://docs.rs/chrono)'s types to python:
- [TimeDelta](https://docs.rs/chrono/latest/chrono/struct.TimeDelta.html) -> [`PyDelta`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyDelta.html)
- [FixedOffset](https://docs.rs/chrono/latest/chrono/offset/struct.FixedOffset.html) -> [`PyDelta`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyDelta.html)
- [Utc](https://docs.rs/chrono/latest/chrono/offset/struct.Utc.html) -> [`PyTzInfo`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyTzInfo.html)
- [NaiveDate](https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html) -> [`PyDate`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyDate.html)
- [NaiveTime](https://docs.rs/chrono/latest/chrono/naive/struct.NaiveTime.html) -> [`PyTime`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyTime.html)
- [DateTime](https://docs.rs/chrono/latest/chrono/struct.DateTime.html) -> [`PyDateTime`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyDateTime.html)
### `chrono-tz`
Adds a dependency on [chrono-tz](https://docs.rs/chrono-tz).
Enables conversion from and to [`Tz`](https://docs.rs/chrono-tz/latest/chrono_tz/enum.Tz.html).
It requires at least Python 3.9.
### `either`
Adds a dependency on [either](https://docs.rs/either). Enables a conversions into [either](https://docs.rs/either)’s [`Either`](https://docs.rs/either/latest/either/enum.Either.html) type.
### `eyre`
Adds a dependency on [eyre](https://docs.rs/eyre). Enables a conversion from [eyre](https://docs.rs/eyre)’s [`Report`](https://docs.rs/eyre/latest/eyre/struct.Report.html) type to [`PyErr`]({{#PYO3_DOCS_URL}}/pyo3/struct.PyErr.html), for easy error handling.
### `hashbrown`
Adds a dependency on [hashbrown](https://docs.rs/hashbrown) and enables conversions into its [`HashMap`](https://docs.rs/hashbrown/latest/hashbrown/struct.HashMap.html) and [`HashSet`](https://docs.rs/hashbrown/latest/hashbrown/struct.HashSet.html) types.
### `indexmap`
Adds a dependency on [indexmap](https://docs.rs/indexmap) and enables conversions into its [`IndexMap`](https://docs.rs/indexmap/latest/indexmap/map/struct.IndexMap.html) type.
### `num-bigint`
Adds a dependency on [num-bigint](https://docs.rs/num-bigint) and enables conversions into its [`BigInt`](https://docs.rs/num-bigint/latest/num_bigint/struct.BigInt.html) and [`BigUint`](https://docs.rs/num-bigint/latest/num_bigint/struct.BigUint.html) types.
### `num-complex`
Adds a dependency on [num-complex](https://docs.rs/num-complex) and enables conversions into its [`Complex`](https://docs.rs/num-complex/latest/num_complex/struct.Complex.html) type.
### `num-rational`
Adds a dependency on [num-rational](https://docs.rs/num-rational) and enables conversions into its [`Ratio`](https://docs.rs/num-rational/latest/num_rational/struct.Ratio.html) type.
### `rust_decimal`
Adds a dependency on [rust_decimal](https://docs.rs/rust_decimal) and enables conversions into its [`Decimal`](https://docs.rs/rust_decimal/latest/rust_decimal/struct.Decimal.html) type.
### `serde`
Enables (de)serialization of `Py<T>` objects via [serde](https://serde.rs/).
This allows to use [`#[derive(Serialize, Deserialize)`](https://serde.rs/derive.html) on structs that hold references to `#[pyclass]` instances
```rust
# #[cfg(feature = "serde")]
# #[allow(dead_code)]
# mod serde_only {
# use pyo3::prelude::*;
# use serde::{Deserialize, Serialize};
#[pyclass]
#[derive(Serialize, Deserialize)]
struct Permission {
name: String,
}
#[pyclass]
#[derive(Serialize, Deserialize)]
struct User {
username: String,
permissions: Vec<Py<Permission>>,
}
# }
```
### `smallvec`
Adds a dependency on [smallvec](https://docs.rs/smallvec) and enables conversions into its [`SmallVec`](https://docs.rs/smallvec/latest/smallvec/struct.SmallVec.html) type.
[set-configuration-options]: https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/migration.md | # Migrating from older PyO3 versions
This guide can help you upgrade code through breaking changes from one PyO3 version to the next.
For a detailed list of all changes, see the [CHANGELOG](changelog.md).
## from 0.22.* to 0.23
### `gil-refs` feature removed
<details open>
<summary><small>Click to expand</small></summary>
PyO3 0.23 completes the removal of the "GIL Refs" API in favour of the new "Bound" API introduced in PyO3 0.21.
With the removal of the old API, many "Bound" API functions which had been introduced with `_bound` suffixes no longer need the suffixes as these names has been freed up. For example, `PyTuple::new_bound` is now just `PyTuple::new` (the existing name remains but is deprecated).
Before:
```rust
# #![allow(deprecated)]
# use pyo3::prelude::*;
# use pyo3::types::PyTuple;
# fn main() {
# Python::with_gil(|py| {
// For example, for PyTuple. Many such APIs have been changed.
let tup = PyTuple::new_bound(py, [1, 2, 3]);
# })
# }
```
After:
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyTuple;
# fn main() {
# Python::with_gil(|py| {
// For example, for PyTuple. Many such APIs have been changed.
let tup = PyTuple::new(py, [1, 2, 3]);
# })
# }
```
</details>
### Renamed `IntoPyDict::into_py_dict_bound` into `IntoPyDict::into_py_dict`.
<details open>
<summary><small>Click to expand</small></summary>
The `IntoPyDict::into_py_dict_bound` method has been renamed to `IntoPyDict::into_py_dict` and is now fallible. If you implemented `IntoPyDict` for your type, you should implement `into_py_dict` instead of `into_py_dict_bound`. The old name is still available but deprecated.
Before:
```rust,ignore
# use pyo3::prelude::*;
# use pyo3::types::{PyDict, IntoPyDict};
# use std::collections::HashMap;
struct MyMap<K, V>(HashMap<K, V>);
impl<K, V> IntoPyDict for MyMap<K, V>
where
K: ToPyObject,
V: ToPyObject,
{
fn into_py_dict_bound(self, py: Python<'_>) -> Bound<'_, PyDict> {
let dict = PyDict::new_bound(py);
for (key, value) in self.0 {
dict.set_item(key, value)
.expect("Failed to set_item on dict");
}
dict
}
}
```
After:
```rust
# use pyo3::prelude::*;
# use pyo3::types::{PyDict, IntoPyDict};
# use std::collections::HashMap;
# #[allow(dead_code)]
# struct MyMap<K, V>(HashMap<K, V>);
impl<'py, K, V> IntoPyDict<'py> for MyMap<K, V>
where
K: IntoPyObject<'py>,
V: IntoPyObject<'py>,
{
fn into_py_dict(self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
let dict = PyDict::new(py);
for (key, value) in self.0 {
dict.set_item(key, value)?;
}
Ok(dict)
}
}
```
</details>
### Macro conversion changed for byte collections (`Vec<u8>`, `[u8; N]` and `SmallVec<[u8; N]>`).
<details open>
<summary><small>Click to expand</small></summary>
PyO3 0.23 introduced the new fallible conversion trait `IntoPyObject`. The `#[pyfunction]` and
`#[pymethods]` macros prefer `IntoPyObject` implementations over `IntoPy<PyObject>`. This also
applies to `#[pyo3(get)]`.
This change has an effect on functions and methods returning _byte_ collections like
- `Vec<u8>`
- `[u8; N]`
- `SmallVec<[u8; N]>`
In their new `IntoPyObject` implementation these will now turn into `PyBytes` rather than a
`PyList`. All other `T`s are unaffected and still convert into a `PyList`.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
fn foo() -> Vec<u8> { // would previously turn into a `PyList`, now `PyBytes`
vec![0, 1, 2, 3]
}
#[pyfunction]
fn bar() -> Vec<u16> { // unaffected, returns `PyList`
vec![0, 1, 2, 3]
}
```
If this conversion is _not_ desired, consider building a list manually using `PyList::new`.
The following types were previously _only_ implemented for `u8` and now allow other `T`s turn into
`PyList`
- `&[T]`
- `Cow<[T]>`
This is purely additional and should just extend the possible return types.
</details>
### Python API trait bounds changed
<details open>
<summary><small>Click to expand</small></summary>
PyO3 0.23 introduces a new unified `IntoPyObject` trait to convert Rust types into Python objects.
Notable features of this new trait:
- conversions can now return an error
- compared to `IntoPy<T>` the generic `T` moved into an associated type, so
- there is now only one way to convert a given type
- the output type is stronger typed and may return any Python type instead of just `PyAny`
- byte collections are special handled and convert into `PyBytes` now, see [above](#macro-conversion-changed-for-byte-collections-vecu8-u8-n-and-smallvecu8-n)
- `()` (unit) is now only special handled in return position and otherwise converts into an empty `PyTuple`
All PyO3 provided types as well as `#[pyclass]`es already implement `IntoPyObject`. Other types will
need to adapt an implementation of `IntoPyObject` to stay compatible with the Python APIs. In many cases
the new [`#[derive(IntoPyObject)]`](#intopyobject-derive-macro) macro can be used instead of
[manual implementations](#intopyobject-manual-implementation).
Together with the introduction of `IntoPyObject` the old conversion traits `ToPyObject` and `IntoPy`
are deprecated and will be removed in a future PyO3 version.
#### `IntoPyObject` derive macro
To migrate you may use the new `IntoPyObject` derive macro as below.
```rust
# use pyo3::prelude::*;
#[derive(IntoPyObject)]
struct Struct {
count: usize,
obj: Py<PyAny>,
}
```
#### `IntoPyObject` manual implementation
Before:
```rust,ignore
# use pyo3::prelude::*;
# #[allow(dead_code)]
struct MyPyObjectWrapper(PyObject);
impl IntoPy<PyObject> for MyPyObjectWrapper {
fn into_py(self, py: Python<'_>) -> PyObject {
self.0
}
}
impl ToPyObject for MyPyObjectWrapper {
fn to_object(&self, py: Python<'_>) -> PyObject {
self.0.clone_ref(py)
}
}
```
After:
```rust
# use pyo3::prelude::*;
# #[allow(dead_code)]
# struct MyPyObjectWrapper(PyObject);
impl<'py> IntoPyObject<'py> for MyPyObjectWrapper {
type Target = PyAny; // the Python type
type Output = Bound<'py, Self::Target>; // in most cases this will be `Bound`
type Error = std::convert::Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(self.0.into_bound(py))
}
}
// `ToPyObject` implementations should be converted to implementations on reference types
impl<'a, 'py> IntoPyObject<'py> for &'a MyPyObjectWrapper {
type Target = PyAny;
type Output = Borrowed<'a, 'py, Self::Target>; // `Borrowed` can be used to optimized reference counting
type Error = std::convert::Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(self.0.bind_borrowed(py))
}
}
```
</details>
### Free-threaded Python Support
PyO3 0.23 introduces preliminary support for the new free-threaded build of
CPython 3.13. PyO3 features that implicitly assumed the existence of the GIL are
not exposed in the free-threaded build, since they are no longer safe. Other
features, such as `GILOnceCell`, have been internally rewritten to be threadsafe
without the GIL, although note that `GILOnceCell` is inherently racey. You can
also use `OnceExt::call_once_py_attached` or
`OnceExt::call_once_force_py_attached` to enable use of `std::sync::Once` in
code that has the GIL acquired without risking a dealock with the GIL. We plan
We plan to expose more extension traits in the future that make it easier to
write code for the GIL-enabled and free-threaded builds of Python.
If you make use of these features then you will need to account for the
unavailability of this API in the free-threaded build. One way to handle it is
via conditional compilation -- extensions built for the free-threaded build will
have the `Py_GIL_DISABLED` attribute defined.
See [the guide section on free-threaded Python](free-threading.md) for more
details about supporting free-threaded Python in your PyO3 extensions.
## from 0.21.* to 0.22
### Deprecation of `gil-refs` feature continues
<details open>
<summary><small>Click to expand</small></summary>
Following the introduction of the "Bound" API in PyO3 0.21 and the planned removal of the "GIL Refs" API, all functionality related to GIL Refs is now gated behind the `gil-refs` feature and emits a deprecation warning on use.
See <a href="#from-021-to-022">the 0.21 migration entry</a> for help upgrading.
</details>
### Deprecation of implicit default for trailing optional arguments
<details open>
<summary><small>Click to expand</small></summary>
With `pyo3` 0.22 the implicit `None` default for trailing `Option<T>` type argument is deprecated. To migrate, place a `#[pyo3(signature = (...))]` attribute on affected functions or methods and specify the desired behavior.
The migration warning specifies the corresponding signature to keep the current behavior. With 0.23 the signature will be required for any function containing `Option<T>` type parameters to prevent accidental
and unnoticed changes in behavior. With 0.24 this restriction will be lifted again and `Option<T>` type arguments will be treated as any other argument _without_ special handling.
Before:
```rust
# #![allow(deprecated, dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
fn increment(x: u64, amount: Option<u64>) -> u64 {
x + amount.unwrap_or(1)
}
```
After:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
#[pyo3(signature = (x, amount=None))]
fn increment(x: u64, amount: Option<u64>) -> u64 {
x + amount.unwrap_or(1)
}
```
</details>
### `Py::clone` is now gated behind the `py-clone` feature
<details open>
<summary><small>Click to expand</small></summary>
If you rely on `impl<T> Clone for Py<T>` to fulfil trait requirements imposed by existing Rust code written without PyO3-based code in mind, the newly introduced feature `py-clone` must be enabled.
However, take care to note that the behaviour is different from previous versions. If `Clone` was called without the GIL being held, we tried to delay the application of these reference count increments until PyO3-based code would re-acquire it. This turned out to be impossible to implement in a sound manner and hence was removed. Now, if `Clone` is called without the GIL being held, we panic instead for which calling code might not be prepared.
It is advised to migrate off the `py-clone` feature. The simplest way to remove dependency on `impl<T> Clone for Py<T>` is to wrap `Py<T>` as `Arc<Py<T>>` and use cloning of the arc.
Related to this, we also added a `pyo3_disable_reference_pool` conditional compilation flag which removes the infrastructure necessary to apply delayed reference count decrements implied by `impl<T> Drop for Py<T>`. They do not appear to be a soundness hazard as they should lead to memory leaks in the worst case. However, the global synchronization adds significant overhead to cross the Python-Rust boundary. Enabling this feature will remove these costs and make the `Drop` implementation abort the process if called without the GIL being held instead.
</details>
### Require explicit opt-in for comparison for simple enums
<details open>
<summary><small>Click to expand</small></summary>
With `pyo3` 0.22 the new `#[pyo3(eq)]` options allows automatic implementation of Python equality using Rust's `PartialEq`. Previously simple enums automatically implemented equality in terms of their discriminants. To make PyO3 more consistent, this automatic equality implementation is deprecated in favour of having opt-ins for all `#[pyclass]` types. Similarly, simple enums supported comparison with integers, which is not covered by Rust's `PartialEq` derive, so has been split out into the `#[pyo3(eq_int)]` attribute.
To migrate, place a `#[pyo3(eq, eq_int)]` attribute on simple enum classes.
Before:
```rust
# #![allow(deprecated, dead_code)]
# use pyo3::prelude::*;
#[pyclass]
enum SimpleEnum {
VariantA,
VariantB = 42,
}
```
After:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum SimpleEnum {
VariantA,
VariantB = 42,
}
```
</details>
### `PyType::name` reworked to better match Python `__name__`
<details open>
<summary><small>Click to expand</small></summary>
This function previously would try to read directly from Python type objects' C API field (`tp_name`), in which case it
would return a `Cow::Borrowed`. However the contents of `tp_name` don't have well-defined semantics.
Instead `PyType::name()` now returns the equivalent of Python `__name__` and returns `PyResult<Bound<'py, PyString>>`.
The closest equivalent to PyO3 0.21's version of `PyType::name()` has been introduced as a new function `PyType::fully_qualified_name()`,
which is equivalent to `__module__` and `__qualname__` joined as `module.qualname`.
Before:
```rust,ignore
# #![allow(deprecated, dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::{PyBool};
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let bool_type = py.get_type_bound::<PyBool>();
let name = bool_type.name()?.into_owned();
println!("Hello, {}", name);
let mut name_upper = bool_type.name()?;
name_upper.to_mut().make_ascii_uppercase();
println!("Hello, {}", name_upper);
Ok(())
})
# }
```
After:
```rust,ignore
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::{PyBool};
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let bool_type = py.get_type_bound::<PyBool>();
let name = bool_type.name()?;
println!("Hello, {}", name);
// (if the full dotted path was desired, switch from `name()` to `fully_qualified_name()`)
let mut name_upper = bool_type.fully_qualified_name()?.to_string();
name_upper.make_ascii_uppercase();
println!("Hello, {}", name_upper);
Ok(())
})
# }
```
</details>
## from 0.20.* to 0.21
<details>
<summary><small>Click to expand</small></summary>
PyO3 0.21 introduces a new `Bound<'py, T>` smart pointer which replaces the existing "GIL Refs" API to interact with Python objects. For example, in PyO3 0.20 the reference `&'py PyAny` would be used to interact with Python objects. In PyO3 0.21 the updated type is `Bound<'py, PyAny>`. Making this change moves Rust ownership semantics out of PyO3's internals and into user code. This change fixes [a known soundness edge case of interaction with gevent](https://github.com/PyO3/pyo3/issues/3668) as well as improves CPU and [memory performance](https://github.com/PyO3/pyo3/issues/1056). For a full history of discussion see https://github.com/PyO3/pyo3/issues/3382.
The "GIL Ref" `&'py PyAny` and similar types such as `&'py PyDict` continue to be available as a deprecated API. Due to the advantages of the new API it is advised that all users make the effort to upgrade as soon as possible.
In addition to the major API type overhaul, PyO3 has needed to make a few small breaking adjustments to other APIs to close correctness and soundness gaps.
The recommended steps to update to PyO3 0.21 is as follows:
1. Enable the `gil-refs` feature to silence deprecations related to the API change
2. Fix all other PyO3 0.21 migration steps
3. Disable the `gil-refs` feature and migrate off the deprecated APIs
The following sections are laid out in this order.
</details>
### Enable the `gil-refs` feature
<details>
<summary><small>Click to expand</small></summary>
To make the transition for the PyO3 ecosystem away from the GIL Refs API as smooth as possible, in PyO3 0.21 no APIs consuming or producing GIL Refs have been altered. Instead, variants using `Bound<T>` smart pointers have been introduced, for example `PyTuple::new_bound` which returns `Bound<PyTuple>` is the replacement form of `PyTuple::new`. The GIL Ref APIs have been deprecated, but to make migration easier it is possible to disable these deprecation warnings by enabling the `gil-refs` feature.
> The one single exception where an existing API was changed in-place is the `pyo3::intern!` macro. Almost all uses of this macro did not need to update code to account it changing to return `&Bound<PyString>` immediately, and adding an `intern_bound!` replacement was perceived as adding more work for users.
It is recommended that users do this as a first step of updating to PyO3 0.21 so that the deprecation warnings do not get in the way of resolving the rest of the migration steps.
Before:
```toml
# Cargo.toml
[dependencies]
pyo3 = "0.20"
```
After:
```toml
# Cargo.toml
[dependencies]
pyo3 = { version = "0.21", features = ["gil-refs"] }
```
</details>
### `PyTypeInfo` and `PyTryFrom` have been adjusted
<details>
<summary><small>Click to expand</small></summary>
The `PyTryFrom` trait has aged poorly, its `try_from` method now conflicts with `TryFrom::try_from` in the 2021 edition prelude. A lot of its functionality was also duplicated with `PyTypeInfo`.
To tighten up the PyO3 traits as part of the deprecation of the GIL Refs API the `PyTypeInfo` trait has had a simpler companion `PyTypeCheck`. The methods `PyAny::downcast` and `PyAny::downcast_exact` no longer use `PyTryFrom` as a bound, instead using `PyTypeCheck` and `PyTypeInfo` respectively.
To migrate, switch all type casts to use `obj.downcast()` instead of `try_from(obj)` (and similar for `downcast_exact`).
Before:
```rust,ignore
# #![allow(deprecated)]
# use pyo3::prelude::*;
# use pyo3::types::{PyInt, PyList};
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let list = PyList::new(py, 0..5);
let b = <PyInt as PyTryFrom>::try_from(list.get_item(0).unwrap())?;
Ok(())
})
# }
```
After:
```rust,ignore
# use pyo3::prelude::*;
# use pyo3::types::{PyInt, PyList};
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
// Note that PyList::new is deprecated for PyList::new_bound as part of the GIL Refs API removal,
// see the section below on migration to Bound<T>.
#[allow(deprecated)]
let list = PyList::new(py, 0..5);
let b = list.get_item(0).unwrap().downcast::<PyInt>()?;
Ok(())
})
# }
```
</details>
### `Iter(A)NextOutput` are deprecated
<details>
<summary><small>Click to expand</small></summary>
The `__next__` and `__anext__` magic methods can now return any type convertible into Python objects directly just like all other `#[pymethods]`. The `IterNextOutput` used by `__next__` and `IterANextOutput` used by `__anext__` are subsequently deprecated. Most importantly, this change allows returning an awaitable from `__anext__` without non-sensically wrapping it into `Yield` or `Some`. Only the return types `Option<T>` and `Result<Option<T>, E>` are still handled in a special manner where `Some(val)` yields `val` and `None` stops iteration.
Starting with an implementation of a Python iterator using `IterNextOutput`, e.g.
```rust,ignore
use pyo3::prelude::*;
use pyo3::iter::IterNextOutput;
#[pyclass]
struct PyClassIter {
count: usize,
}
#[pymethods]
impl PyClassIter {
fn __next__(&mut self) -> IterNextOutput<usize, &'static str> {
if self.count < 5 {
self.count += 1;
IterNextOutput::Yield(self.count)
} else {
IterNextOutput::Return("done")
}
}
}
```
If returning `"done"` via `StopIteration` is not really required, this should be written as
```rust
use pyo3::prelude::*;
#[pyclass]
struct PyClassIter {
count: usize,
}
#[pymethods]
impl PyClassIter {
fn __next__(&mut self) -> Option<usize> {
if self.count < 5 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
```
This form also has additional benefits: It has already worked in previous PyO3 versions, it matches the signature of Rust's [`Iterator` trait](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html) and it allows using a fast path in CPython which completely avoids the cost of raising a `StopIteration` exception. Note that using [`Option::transpose`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.transpose) and the `Result<Option<T>, E>` variant, this form can also be used to wrap fallible iterators.
Alternatively, the implementation can also be done as it would in Python itself, i.e. by "raising" a `StopIteration` exception
```rust
use pyo3::prelude::*;
use pyo3::exceptions::PyStopIteration;
#[pyclass]
struct PyClassIter {
count: usize,
}
#[pymethods]
impl PyClassIter {
fn __next__(&mut self) -> PyResult<usize> {
if self.count < 5 {
self.count += 1;
Ok(self.count)
} else {
Err(PyStopIteration::new_err("done"))
}
}
}
```
Finally, an asynchronous iterator can directly return an awaitable without confusing wrapping
```rust
use pyo3::prelude::*;
#[pyclass]
struct PyClassAwaitable {
number: usize,
}
#[pymethods]
impl PyClassAwaitable {
fn __next__(&self) -> usize {
self.number
}
fn __await__(slf: Py<Self>) -> Py<Self> {
slf
}
}
#[pyclass]
struct PyClassAsyncIter {
number: usize,
}
#[pymethods]
impl PyClassAsyncIter {
fn __anext__(&mut self) -> PyClassAwaitable {
self.number += 1;
PyClassAwaitable {
number: self.number,
}
}
fn __aiter__(slf: Py<Self>) -> Py<Self> {
slf
}
}
```
</details>
### `PyType::name` has been renamed to `PyType::qualname`
<details>
<summary><small>Click to expand</small></summary>
`PyType::name` has been renamed to `PyType::qualname` to indicate that it does indeed return the [qualified name](https://docs.python.org/3/glossary.html#term-qualified-name), matching the `__qualname__` attribute. The newly added `PyType::name` yields the full name including the module name now which corresponds to `__module__.__name__` on the level of attributes.
</details>
### `PyCell` has been deprecated
<details>
<summary><small>Click to expand</small></summary>
Interactions with Python objects implemented in Rust no longer need to go though `PyCell<T>`. Instead iteractions with Python object now consistently go through `Bound<T>` or `Py<T>` independently of whether `T` is native Python object or a `#[pyclass]` implemented in Rust. Use `Bound::new` or `Py::new` respectively to create and `Bound::borrow(_mut)` / `Py::borrow(_mut)` to borrow the Rust object.
</details>
### Migrating from the GIL Refs API to `Bound<T>`
<details>
<summary><small>Click to expand</small></summary>
To minimise breakage of code using the GIL Refs API, the `Bound<T>` smart pointer has been introduced by adding complements to all functions which accept or return GIL Refs. This allows code to migrate by replacing the deprecated APIs with the new ones.
To identify what to migrate, temporarily switch off the `gil-refs` feature to see deprecation warnings on [almost](#cases-where-pyo3-cannot-emit-gil-ref-deprecation-warnings) all uses of APIs accepting and producing GIL Refs . Over one or more PRs it should be possible to follow the deprecation hints to update code. Depending on your development environment, switching off the `gil-refs` feature may introduce [some very targeted breakages](#deactivating-the-gil-refs-feature), so you may need to fixup those first.
For example, the following APIs have gained updated variants:
- `PyList::new`, `PyTyple::new` and similar constructors have replacements `PyList::new_bound`, `PyTuple::new_bound` etc.
- `FromPyObject::extract` has a new `FromPyObject::extract_bound` (see the section below)
- The `PyTypeInfo` trait has had new `_bound` methods added to accept / return `Bound<T>`.
Because the new `Bound<T>` API brings ownership out of the PyO3 framework and into user code, there are a few places where user code is expected to need to adjust while switching to the new API:
- Code will need to add the occasional `&` to borrow the new smart pointer as `&Bound<T>` to pass these types around (or use `.clone()` at the very small cost of increasing the Python reference count)
- `Bound<PyList>` and `Bound<PyTuple>` cannot support indexing with `list[0]`, you should use `list.get_item(0)` instead.
- `Bound<PyTuple>::iter_borrowed` is slightly more efficient than `Bound<PyTuple>::iter`. The default iteration of `Bound<PyTuple>` cannot return borrowed references because Rust does not (yet) have "lending iterators". Similarly `Bound<PyTuple>::get_borrowed_item` is more efficient than `Bound<PyTuple>::get_item` for the same reason.
- `&Bound<T>` does not implement `FromPyObject` (although it might be possible to do this in the future once the GIL Refs API is completely removed). Use `bound_any.downcast::<T>()` instead of `bound_any.extract::<&Bound<T>>()`.
- `Bound<PyString>::to_str` now borrows from the `Bound<PyString>` rather than from the `'py` lifetime, so code will need to store the smart pointer as a value in some cases where previously `&PyString` was just used as a temporary. (There are some more details relating to this in [the section below](#deactivating-the-gil-refs-feature).)
- `.extract::<&str>()` now borrows from the source Python object. The simplest way to update is to change to `.extract::<PyBackedStr>()`, which retains ownership of the Python reference. See more information [in the section on deactivating the `gil-refs` feature](#deactivating-the-gil-refs-feature).
To convert between `&PyAny` and `&Bound<PyAny>` use the `as_borrowed()` method:
```rust,ignore
let gil_ref: &PyAny = ...;
let bound: &Bound<PyAny> = &gil_ref.as_borrowed();
```
To convert between `Py<T>` and `Bound<T>` use the `bind()` / `into_bound()` methods, and `as_unbound()` / `unbind()` to go back from `Bound<T>` to `Py<T>`.
```rust,ignore
let obj: Py<PyList> = ...;
let bound: &Bound<'py, PyList> = obj.bind(py);
let bound: Bound<'py, PyList> = obj.into_bound(py);
let obj: &Py<PyList> = bound.as_unbound();
let obj: Py<PyList> = bound.unbind();
```
<div class="warning">
⚠️ Warning: dangling pointer trap 💣
> Because of the ownership changes, code which uses `.as_ptr()` to convert `&PyAny` and other GIL Refs to a `*mut pyo3_ffi::PyObject` should take care to avoid creating dangling pointers now that `Bound<PyAny>` carries ownership.
>
> For example, the following pattern with `Option<&PyAny>` can easily create a dangling pointer when migrating to the `Bound<PyAny>` smart pointer:
>
> ```rust,ignore
> let opt: Option<&PyAny> = ...;
> let p: *mut ffi::PyObject = opt.map_or(std::ptr::null_mut(), |any| any.as_ptr());
> ```
>
> The correct way to migrate this code is to use `.as_ref()` to avoid dropping the `Bound<PyAny>` in the `map_or` closure:
>
> ```rust,ignore
> let opt: Option<Bound<PyAny>> = ...;
> let p: *mut ffi::PyObject = opt.as_ref().map_or(std::ptr::null_mut(), Bound::as_ptr);
> ```
<div>
#### Migrating `FromPyObject` implementations
`FromPyObject` has had a new method `extract_bound` which takes `&Bound<'py, PyAny>` as an argument instead of `&PyAny`. Both `extract` and `extract_bound` have been given default implementations in terms of the other, to avoid breaking code immediately on update to 0.21.
All implementations of `FromPyObject` should be switched from `extract` to `extract_bound`.
Before:
```rust,ignore
impl<'py> FromPyObject<'py> for MyType {
fn extract(obj: &'py PyAny) -> PyResult<Self> {
/* ... */
}
}
```
After:
```rust,ignore
impl<'py> FromPyObject<'py> for MyType {
fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
/* ... */
}
}
```
The expectation is that in 0.22 `extract_bound` will have the default implementation removed and in 0.23 `extract` will be removed.
#### Cases where PyO3 cannot emit GIL Ref deprecation warnings
Despite a large amount of deprecations warnings produced by PyO3 to aid with the transition from GIL Refs to the Bound API, there are a few cases where PyO3 cannot automatically warn on uses of GIL Refs. It is worth checking for these cases manually after the deprecation warnings have all been addressed:
- Individual implementations of the `FromPyObject` trait cannot be deprecated, so PyO3 cannot warn about uses of code patterns like `.extract<&PyAny>()` which produce a GIL Ref.
- GIL Refs in `#[pyfunction]` arguments emit a warning, but if the GIL Ref is wrapped inside another container such as `Vec<&PyAny>` then PyO3 cannot warn against this.
- The `wrap_pyfunction!(function)(py)` deferred argument form of the `wrap_pyfunction` macro taking `py: Python<'py>` produces a GIL Ref, and due to limitations in type inference PyO3 cannot warn against this specific case.
</details>
### Deactivating the `gil-refs` feature
<details>
<summary><small>Click to expand</small></summary>
As a final step of migration, deactivating the `gil-refs` feature will set up code for best performance and is intended to set up a forward-compatible API for PyO3 0.22.
At this point code that needed to manage GIL Ref memory can safely remove uses of `GILPool` (which are constructed by calls to `Python::new_pool` and `Python::with_pool`). Deprecation warnings will highlight these cases.
There is just one case of code that changes upon disabling these features: `FromPyObject` trait implementations for types that borrow directly from the input data cannot be implemented by PyO3 without GIL Refs (while the GIL Refs API is in the process of being removed). The main types affected are `&str`, `Cow<'_, str>`, `&[u8]`, `Cow<'_, u8>`.
To make PyO3's core functionality continue to work while the GIL Refs API is in the process of being removed, disabling the `gil-refs` feature moves the implementations of `FromPyObject` for `&str`, `Cow<'_, str>`, `&[u8]`, `Cow<'_, u8>` to a new temporary trait `FromPyObjectBound`. This trait is the expected future form of `FromPyObject` and has an additional lifetime `'a` to enable these types to borrow data from Python objects.
PyO3 0.21 has introduced the [`PyBackedStr`]({{#PYO3_DOCS_URL}}/pyo3/pybacked/struct.PyBackedStr.html) and [`PyBackedBytes`]({{#PYO3_DOCS_URL}}/pyo3/pybacked/struct.PyBackedBytes.html) types to help with this case. The easiest way to avoid lifetime challenges from extracting `&str` is to use these. For more complex types like `Vec<&str>`, is now impossible to extract directly from a Python object and `Vec<PyBackedStr>` is the recommended upgrade path.
A key thing to note here is because extracting to these types now ties them to the input lifetime, some extremely common patterns may need to be split into multiple Rust lines. For example, the following snippet of calling `.extract::<&str>()` directly on the result of `.getattr()` needs to be adjusted when deactivating the `gil-refs` feature.
Before:
```rust,ignore
# #[cfg(feature = "gil-refs")] {
# use pyo3::prelude::*;
# use pyo3::types::{PyList, PyType};
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
#[allow(deprecated)] // GIL Ref API
let obj: &'py PyType = py.get_type::<PyList>();
let name: &'py str = obj.getattr("__name__")?.extract()?;
assert_eq!(name, "list");
# Ok(())
# }
# Python::with_gil(example).unwrap();
# }
```
After:
```rust,ignore
# #[cfg(any(not(Py_LIMITED_API), Py_3_10))] {
# use pyo3::prelude::*;
# use pyo3::types::{PyList, PyType};
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
let obj: Bound<'py, PyType> = py.get_type_bound::<PyList>();
let name_obj: Bound<'py, PyAny> = obj.getattr("__name__")?;
// the lifetime of the data is no longer `'py` but the much shorter
// lifetime of the `name_obj` smart pointer above
let name: &'_ str = name_obj.extract()?;
assert_eq!(name, "list");
# Ok(())
# }
# Python::with_gil(example).unwrap();
# }
```
To avoid needing to worry about lifetimes at all, it is also possible to use the new `PyBackedStr` type, which stores a reference to the Python `str` without a lifetime attachment. In particular, `PyBackedStr` helps for `abi3` builds for Python older than 3.10. Due to limitations in the `abi3` CPython API for those older versions, PyO3 cannot offer a `FromPyObjectBound` implementation for `&str` on those versions. The easiest way to migrate for older `abi3` builds is to replace any cases of `.extract::<&str>()` with `.extract::<PyBackedStr>()`. Alternatively, use `.extract::<Cow<str>>()`, `.extract::<String>()` to copy the data into Rust.
The following example uses the same snippet as those just above, but this time the final extracted type is `PyBackedStr`:
```rust,ignore
# use pyo3::prelude::*;
# use pyo3::types::{PyList, PyType};
# fn example<'py>(py: Python<'py>) -> PyResult<()> {
use pyo3::pybacked::PyBackedStr;
let obj: Bound<'py, PyType> = py.get_type_bound::<PyList>();
let name: PyBackedStr = obj.getattr("__name__")?.extract()?;
assert_eq!(&*name, "list");
# Ok(())
# }
# Python::with_gil(example).unwrap();
```
</details>
## from 0.19.* to 0.20
### Drop support for older technologies
<details>
<summary><small>Click to expand</small></summary>
PyO3 0.20 has increased minimum Rust version to 1.56. This enables use of newer language features and simplifies maintenance of the project.
</details>
### `PyDict::get_item` now returns a `Result`
<details>
<summary><small>Click to expand</small></summary>
`PyDict::get_item` in PyO3 0.19 and older was implemented using a Python API which would suppress all exceptions and return `None` in those cases. This included errors in `__hash__` and `__eq__` implementations of the key being looked up.
Newer recommendations by the Python core developers advise against using these APIs which suppress exceptions, instead allowing exceptions to bubble upwards. `PyDict::get_item_with_error` already implemented this recommended behavior, so that API has been renamed to `PyDict::get_item`.
Before:
```rust,ignore
use pyo3::prelude::*;
use pyo3::exceptions::PyTypeError;
use pyo3::types::{PyDict, IntoPyDict};
# fn main() {
# let _ =
Python::with_gil(|py| {
let dict: &PyDict = [("a", 1)].into_py_dict(py);
// `a` is in the dictionary, with value 1
assert!(dict.get_item("a").map_or(Ok(false), |x| x.eq(1))?);
// `b` is not in the dictionary
assert!(dict.get_item("b").is_none());
// `dict` is not hashable, so this fails with a `TypeError`
assert!(dict
.get_item_with_error(dict)
.unwrap_err()
.is_instance_of::<PyTypeError>(py));
});
# }
```
After:
```rust,ignore
use pyo3::prelude::*;
use pyo3::exceptions::PyTypeError;
use pyo3::types::{PyDict, IntoPyDict};
# fn main() {
# let _ =
Python::with_gil(|py| -> PyResult<()> {
let dict: &PyDict = [("a", 1)].into_py_dict(py);
// `a` is in the dictionary, with value 1
assert!(dict.get_item("a")?.map_or(Ok(false), |x| x.eq(1))?);
// `b` is not in the dictionary
assert!(dict.get_item("b")?.is_none());
// `dict` is not hashable, so this fails with a `TypeError`
assert!(dict
.get_item(dict)
.unwrap_err()
.is_instance_of::<PyTypeError>(py));
Ok(())
});
# }
```
</details>
### Required arguments are no longer accepted after optional arguments
<details>
<summary><small>Click to expand</small></summary>
[Trailing `Option<T>` arguments](./function/signature.md#trailing-optional-arguments) have an automatic default of `None`. To avoid unwanted changes when modifying function signatures, in PyO3 0.18 it was deprecated to have a required argument after an `Option<T>` argument without using `#[pyo3(signature = (...))]` to specify the intended defaults. In PyO3 0.20, this becomes a hard error.
Before:
```rust,ignore
#[pyfunction]
fn x_or_y(x: Option<u64>, y: u64) -> u64 {
x.unwrap_or(y)
}
```
After:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
#[pyo3(signature = (x, y))] // both x and y have no defaults and are required
fn x_or_y(x: Option<u64>, y: u64) -> u64 {
x.unwrap_or(y)
}
```
</details>
### Remove deprecated function forms
<details>
<summary><small>Click to expand</small></summary>
In PyO3 0.18 the `#[args]` attribute for `#[pymethods]`, and directly specifying the function signature in `#[pyfunction]`, was deprecated. This functionality has been removed in PyO3 0.20.
Before:
```rust,ignore
#[pyfunction]
#[pyo3(a, b = "0", "/")]
fn add(a: u64, b: u64) -> u64 {
a + b
}
```
After:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
#[pyo3(signature = (a, b=0, /))]
fn add(a: u64, b: u64) -> u64 {
a + b
}
```
</details>
### `IntoPyPointer` trait removed
<details>
<summary><small>Click to expand</small></summary>
The trait `IntoPyPointer`, which provided the `into_ptr` method on many types, has been removed. `into_ptr` is now available as an inherent method on all types that previously implemented this trait.
</details>
### `AsPyPointer` now `unsafe` trait
<details>
<summary><small>Click to expand</small></summary>
The trait `AsPyPointer` is now `unsafe trait`, meaning any external implementation of it must be marked as `unsafe impl`, and ensure that they uphold the invariant of returning valid pointers.
</details>
## from 0.18.* to 0.19
### Access to `Python` inside `__traverse__` implementations are now forbidden
<details>
<summary><small>Click to expand</small></summary>
During `__traverse__` implementations for Python's Garbage Collection it is forbidden to do anything other than visit the members of the `#[pyclass]` being traversed. This means making Python function calls or other API calls are forbidden.
Previous versions of PyO3 would allow access to `Python` (e.g. via `Python::with_gil`), which could cause the Python interpreter to crash or otherwise confuse the garbage collection algorithm.
Attempts to acquire the GIL will now panic. See [#3165](https://github.com/PyO3/pyo3/issues/3165) for more detail.
```rust,ignore
# use pyo3::prelude::*;
#[pyclass]
struct SomeClass {}
impl SomeClass {
fn __traverse__(&self, pyo3::class::gc::PyVisit<'_>) -> Result<(), pyo3::class::gc::PyTraverseError>` {
Python::with_gil(|| { /*...*/ }) // ERROR: this will panic
}
}
```
</details>
### Smarter `anyhow::Error` / `eyre::Report` conversion when inner error is "simple" `PyErr`
<details>
<summary><small>Click to expand</small></summary>
When converting from `anyhow::Error` or `eyre::Report` to `PyErr`, if the inner error is a "simple" `PyErr` (with no source error), then the inner error will be used directly as the `PyErr` instead of wrapping it in a new `PyRuntimeError` with the original information converted into a string.
```rust,ignore
# #[cfg(feature = "anyhow")]
# #[allow(dead_code)]
# mod anyhow_only {
# use pyo3::prelude::*;
# use pyo3::exceptions::PyValueError;
#[pyfunction]
fn raise_err() -> anyhow::Result<()> {
Err(PyValueError::new_err("original error message").into())
}
fn main() {
Python::with_gil(|py| {
let rs_func = wrap_pyfunction!(raise_err, py).unwrap();
pyo3::py_run!(
py,
rs_func,
r"
try:
rs_func()
except Exception as e:
print(repr(e))
"
);
})
}
# }
```
Before, the above code would have printed `RuntimeError('ValueError: original error message')`, which might be confusing.
After, the same code will print `ValueError: original error message`, which is more straightforward.
However, if the `anyhow::Error` or `eyre::Report` has a source, then the original exception will still be wrapped in a `PyRuntimeError`.
</details>
### The deprecated `Python::acquire_gil` was removed and `Python::with_gil` must be used instead
<details>
<summary><small>Click to expand</small></summary>
While the API provided by [`Python::acquire_gil`](https://docs.rs/pyo3/0.18.3/pyo3/marker/struct.Python.html#method.acquire_gil) seems convenient, it is somewhat brittle as the design of the GIL token [`Python`](https://docs.rs/pyo3/0.18.3/pyo3/marker/struct.Python.html) relies on proper nesting and panics if not used correctly, e.g.
```rust,ignore
# #![allow(dead_code, deprecated)]
# use pyo3::prelude::*;
#[pyclass]
struct SomeClass {}
struct ObjectAndGuard {
object: Py<SomeClass>,
guard: GILGuard,
}
impl ObjectAndGuard {
fn new() -> Self {
let guard = Python::acquire_gil();
let object = Py::new(guard.python(), SomeClass {}).unwrap();
Self { object, guard }
}
}
let first = ObjectAndGuard::new();
let second = ObjectAndGuard::new();
// Panics because the guard within `second` is still alive.
drop(first);
drop(second);
```
The replacement is [`Python::with_gil`](https://docs.rs/pyo3/0.18.3/pyo3/marker/struct.Python.html#method.with_gil) which is more cumbersome but enforces the proper nesting by design, e.g.
```rust,ignore
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyclass]
struct SomeClass {}
struct Object {
object: Py<SomeClass>,
}
impl Object {
fn new(py: Python<'_>) -> Self {
let object = Py::new(py, SomeClass {}).unwrap();
Self { object }
}
}
// It either forces us to release the GIL before aquiring it again.
let first = Python::with_gil(|py| Object::new(py));
let second = Python::with_gil(|py| Object::new(py));
drop(first);
drop(second);
// Or it ensures releasing the inner lock before the outer one.
Python::with_gil(|py| {
let first = Object::new(py);
let second = Python::with_gil(|py| Object::new(py));
drop(first);
drop(second);
});
```
Furthermore, `Python::acquire_gil` provides ownership of a `GILGuard` which can be freely stored and passed around. This is usually not helpful as it may keep the lock held for a long time thereby blocking progress in other parts of the program. Due to the generative lifetime attached to the GIL token supplied by `Python::with_gil`, the problem is avoided as the GIL token can only be passed down the call chain. Often, this issue can also be avoided entirely as any GIL-bound reference `&'py PyAny` implies access to a GIL token `Python<'py>` via the [`PyAny::py`](https://docs.rs/pyo3/0.22.5/pyo3/types/struct.PyAny.html#method.py) method.
</details>
## from 0.17.* to 0.18
### Required arguments after `Option<_>` arguments will no longer be automatically inferred
<details>
<summary><small>Click to expand</small></summary>
In `#[pyfunction]` and `#[pymethods]`, if a "required" function input such as `i32` came after an `Option<_>` input, then the `Option<_>` would be implicitly treated as required. (All trailing `Option<_>` arguments were treated as optional with a default value of `None`).
Starting with PyO3 0.18, this is deprecated and a future PyO3 version will require a [`#[pyo3(signature = (...))]` option](./function/signature.md) to explicitly declare the programmer's intention.
Before, x in the below example would be required to be passed from Python code:
```rust,compile_fail
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
fn required_argument_after_option(x: Option<i32>, y: i32) {}
```
After, specify the intended Python signature explicitly:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
// If x really was intended to be required
#[pyfunction(signature = (x, y))]
fn required_argument_after_option_a(x: Option<i32>, y: i32) {}
// If x was intended to be optional, y needs a default too
#[pyfunction(signature = (x=None, y=0))]
fn required_argument_after_option_b(x: Option<i32>, y: i32) {}
```
</details>
### `__text_signature__` is now automatically generated for `#[pyfunction]` and `#[pymethods]`
<details>
<summary><small>Click to expand</small></summary>
The [`#[pyo3(text_signature = "...")]` option](./function/signature.md#making-the-function-signature-available-to-python) was previously the only supported way to set the `__text_signature__` attribute on generated Python functions.
PyO3 is now able to automatically populate `__text_signature__` for all functions automatically based on their Rust signature (or the [new `#[pyo3(signature = (...))]` option](./function/signature.md)). These automatically-generated `__text_signature__` values will currently only render `...` for all default values. Many `#[pyo3(text_signature = "...")]` options can be removed from functions when updating to PyO3 0.18, however in cases with default values a manual implementation may still be preferred for now.
As examples:
```rust
# use pyo3::prelude::*;
// The `text_signature` option here is no longer necessary, as PyO3 will automatically
// generate exactly the same value.
#[pyfunction(text_signature = "(a, b, c)")]
fn simple_function(a: i32, b: i32, c: i32) {}
// The `text_signature` still provides value here as of PyO3 0.18, because the automatically
// generated signature would be "(a, b=..., c=...)".
#[pyfunction(signature = (a, b = 1, c = 2), text_signature = "(a, b=1, c=2)")]
fn function_with_defaults(a: i32, b: i32, c: i32) {}
# fn main() {
# Python::with_gil(|py| {
# let simple = wrap_pyfunction!(simple_function, py).unwrap();
# assert_eq!(simple.getattr("__text_signature__").unwrap().to_string(), "(a, b, c)");
# let defaulted = wrap_pyfunction!(function_with_defaults, py).unwrap();
# assert_eq!(defaulted.getattr("__text_signature__").unwrap().to_string(), "(a, b=1, c=2)");
# })
# }
```
</details>
## from 0.16.* to 0.17
### Type checks have been changed for `PyMapping` and `PySequence` types
<details>
<summary><small>Click to expand</small></summary>
Previously the type checks for `PyMapping` and `PySequence` (implemented in `PyTryFrom`)
used the Python C-API functions `PyMapping_Check` and `PySequence_Check`.
Unfortunately these functions are not sufficient for distinguishing such types,
leading to inconsistent behavior (see
[pyo3/pyo3#2072](https://github.com/PyO3/pyo3/issues/2072)).
PyO3 0.17 changes these downcast checks to explicitly test if the type is a
subclass of the corresponding abstract base class `collections.abc.Mapping` or
`collections.abc.Sequence`. Note this requires calling into Python, which may
incur a performance penalty over the previous method. If this performance
penalty is a problem, you may be able to perform your own checks and use
`try_from_unchecked` (unsafe).
Another side-effect is that a pyclass defined in Rust with PyO3 will need to
be _registered_ with the corresponding Python abstract base class for
downcasting to succeed. `PySequence::register` and `PyMapping:register` have
been added to make it easy to do this from Rust code. These are equivalent to
calling `collections.abc.Mapping.register(MappingPyClass)` or
`collections.abc.Sequence.register(SequencePyClass)` from Python.
For example, for a mapping class defined in Rust:
```rust,compile_fail
use pyo3::prelude::*;
use std::collections::HashMap;
#[pyclass(mapping)]
struct Mapping {
index: HashMap<String, usize>,
}
#[pymethods]
impl Mapping {
#[new]
fn new(elements: Option<&PyList>) -> PyResult<Self> {
// ...
// truncated implementation of this mapping pyclass - basically a wrapper around a HashMap
}
```
You must register the class with `collections.abc.Mapping` before the downcast will work:
```rust,compile_fail
let m = Py::new(py, Mapping { index }).unwrap();
assert!(m.as_ref(py).downcast::<PyMapping>().is_err());
PyMapping::register::<Mapping>(py).unwrap();
assert!(m.as_ref(py).downcast::<PyMapping>().is_ok());
```
Note that this requirement may go away in the future when a pyclass is able to inherit from the abstract base class directly (see [pyo3/pyo3#991](https://github.com/PyO3/pyo3/issues/991)).
</details>
### The `multiple-pymethods` feature now requires Rust 1.62
<details>
<summary><small>Click to expand</small></summary>
Due to limitations in the `inventory` crate which the `multiple-pymethods` feature depends on, this feature now
requires Rust 1.62. For more information see [dtolnay/inventory#32](https://github.com/dtolnay/inventory/issues/32).
</details>
### Added `impl IntoPy<Py<PyString>> for &str`
<details>
<summary><small>Click to expand</small></summary>
This may cause inference errors.
Before:
```rust,compile_fail
# use pyo3::prelude::*;
#
# fn main() {
Python::with_gil(|py| {
// Cannot infer either `Py<PyAny>` or `Py<PyString>`
let _test = "test".into_py(py);
});
# }
```
After, some type annotations may be necessary:
```rust
# #![allow(deprecated)]
# use pyo3::prelude::*;
#
# fn main() {
Python::with_gil(|py| {
let _test: Py<PyAny> = "test".into_py(py);
});
# }
```
</details>
### The `pyproto` feature is now disabled by default
<details>
<summary><small>Click to expand</small></summary>
In preparation for removing the deprecated `#[pyproto]` attribute macro in a future PyO3 version, it is now gated behind an opt-in feature flag. This also gives a slight saving to compile times for code which does not use the deprecated macro.
</details>
### `PyTypeObject` trait has been deprecated
<details>
<summary><small>Click to expand</small></summary>
The `PyTypeObject` trait already was near-useless; almost all functionality was already on the `PyTypeInfo` trait, which `PyTypeObject` had a blanket implementation based upon. In PyO3 0.17 the final method, `PyTypeObject::type_object` was moved to `PyTypeInfo::type_object`.
To migrate, update trait bounds and imports from `PyTypeObject` to `PyTypeInfo`.
Before:
```rust,ignore
use pyo3::Python;
use pyo3::type_object::PyTypeObject;
use pyo3::types::PyType;
fn get_type_object<T: PyTypeObject>(py: Python<'_>) -> &PyType {
T::type_object(py)
}
```
After
```rust,ignore
use pyo3::{Python, PyTypeInfo};
use pyo3::types::PyType;
fn get_type_object<T: PyTypeInfo>(py: Python<'_>) -> &PyType {
T::type_object(py)
}
# Python::with_gil(|py| { get_type_object::<pyo3::types::PyList>(py); });
```
</details>
### `impl<T, const N: usize> IntoPy<PyObject> for [T; N]` now requires `T: IntoPy` rather than `T: ToPyObject`
<details>
<summary><small>Click to expand</small></summary>
If this leads to errors, simply implement `IntoPy`. Because pyclasses already implement `IntoPy`, you probably don't need to worry about this.
</details>
### Each `#[pymodule]` can now only be initialized once per process
<details>
<summary><small>Click to expand</small></summary>
To make PyO3 modules sound in the presence of Python sub-interpreters, for now it has been necessary to explicitly disable the ability to initialize a `#[pymodule]` more than once in the same process. Attempting to do this will now raise an `ImportError`.
</details>
## from 0.15.* to 0.16
### Drop support for older technologies
<details>
<summary><small>Click to expand</small></summary>
PyO3 0.16 has increased minimum Rust version to 1.48 and minimum Python version to 3.7. This enables use of newer language features (enabling some of the other additions in 0.16) and simplifies maintenance of the project.
</details>
### `#[pyproto]` has been deprecated
<details>
<summary><small>Click to expand</small></summary>
In PyO3 0.15, the `#[pymethods]` attribute macro gained support for implementing "magic methods" such as `__str__` (aka "dunder" methods). This implementation was not quite finalized at the time, with a few edge cases to be decided upon. The existing `#[pyproto]` attribute macro was left untouched, because it covered these edge cases.
In PyO3 0.16, the `#[pymethods]` implementation has been completed and is now the preferred way to implement magic methods. To allow the PyO3 project to move forward, `#[pyproto]` has been deprecated (with expected removal in PyO3 0.18).
Migration from `#[pyproto]` to `#[pymethods]` is straightforward; copying the existing methods directly from the `#[pyproto]` trait implementation is all that is needed in most cases.
Before:
```rust,compile_fail
use pyo3::prelude::*;
use pyo3::class::{PyObjectProtocol, PyIterProtocol};
use pyo3::types::PyString;
#[pyclass]
struct MyClass {}
#[pyproto]
impl PyObjectProtocol for MyClass {
fn __str__(&self) -> &'static [u8] {
b"hello, world"
}
}
#[pyproto]
impl PyIterProtocol for MyClass {
fn __iter__(slf: PyRef<self>) -> PyResult<&PyAny> {
PyString::new(slf.py(), "hello, world").iter()
}
}
```
After
```rust,compile_fail
use pyo3::prelude::*;
use pyo3::types::PyString;
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
fn __str__(&self) -> &'static [u8] {
b"hello, world"
}
fn __iter__(slf: PyRef<self>) -> PyResult<&PyAny> {
PyString::new(slf.py(), "hello, world").iter()
}
}
```
</details>
### Removed `PartialEq` for object wrappers
<details>
<summary><small>Click to expand</small></summary>
The Python object wrappers `Py` and `PyAny` had implementations of `PartialEq`
so that `object_a == object_b` would compare the Python objects for pointer
equality, which corresponds to the `is` operator, not the `==` operator in
Python. This has been removed in favor of a new method: use
`object_a.is(object_b)`. This also has the advantage of not requiring the same
wrapper type for `object_a` and `object_b`; you can now directly compare a
`Py<T>` with a `&PyAny` without having to convert.
To check for Python object equality (the Python `==` operator), use the new
method `eq()`.
</details>
### Container magic methods now match Python behavior
<details>
<summary><small>Click to expand</small></summary>
In PyO3 0.15, `__getitem__`, `__setitem__` and `__delitem__` in `#[pymethods]` would generate only the _mapping_ implementation for a `#[pyclass]`. To match the Python behavior, these methods now generate both the _mapping_ **and** _sequence_ implementations.
This means that classes implementing these `#[pymethods]` will now also be treated as sequences, same as a Python `class` would be. Small differences in behavior may result:
- PyO3 will allow instances of these classes to be cast to `PySequence` as well as `PyMapping`.
- Python will provide a default implementation of `__iter__` (if the class did not have one) which repeatedly calls `__getitem__` with integers (starting at 0) until an `IndexError` is raised.
To explain this in detail, consider the following Python class:
```python
class ExampleContainer:
def __len__(self):
return 5
def __getitem__(self, idx: int) -> int:
if idx < 0 or idx > 5:
raise IndexError()
return idx
```
This class implements a Python [sequence](https://docs.python.org/3/glossary.html#term-sequence).
The `__len__` and `__getitem__` methods are also used to implement a Python [mapping](https://docs.python.org/3/glossary.html#term-mapping). In the Python C-API, these methods are not shared: the sequence `__len__` and `__getitem__` are defined by the `sq_length` and `sq_item` slots, and the mapping equivalents are `mp_length` and `mp_subscript`. There are similar distinctions for `__setitem__` and `__delitem__`.
Because there is no such distinction from Python, implementing these methods will fill the mapping and sequence slots simultaneously. A Python class with `__len__` implemented, for example, will have both the `sq_length` and `mp_length` slots filled.
The PyO3 behavior in 0.16 has been changed to be closer to this Python behavior by default.
</details>
### `wrap_pymodule!` and `wrap_pyfunction!` now respect privacy correctly
<details>
<summary><small>Click to expand</small></summary>
Prior to PyO3 0.16 the `wrap_pymodule!` and `wrap_pyfunction!` macros could use modules and functions whose defining `fn` was not reachable according Rust privacy rules.
For example, the following code was legal before 0.16, but in 0.16 is rejected because the `wrap_pymodule!` macro cannot access the `private_submodule` function:
```rust,compile_fail
mod foo {
use pyo3::prelude::*;
#[pymodule]
fn private_submodule(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
Ok(())
}
}
use pyo3::prelude::*;
use foo::*;
#[pymodule]
fn my_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pymodule!(private_submodule))?;
Ok(())
}
```
To fix it, make the private submodule visible, e.g. with `pub` or `pub(crate)`.
```rust,ignore
mod foo {
use pyo3::prelude::*;
#[pymodule]
pub(crate) fn private_submodule(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
Ok(())
}
}
use pyo3::prelude::*;
use pyo3::wrap_pymodule;
use foo::*;
#[pymodule]
fn my_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pymodule!(private_submodule))?;
Ok(())
}
```
</details>
## from 0.14.* to 0.15
### Changes in sequence indexing
<details>
<summary><small>Click to expand</small></summary>
For all types that take sequence indices (`PyList`, `PyTuple` and `PySequence`),
the API has been made consistent to only take `usize` indices, for consistency
with Rust's indexing conventions. Negative indices, which were only
sporadically supported even in APIs that took `isize`, now aren't supported
anywhere.
Further, the `get_item` methods now always return a `PyResult` instead of
panicking on invalid indices. The `Index` trait has been implemented instead,
and provides the same panic behavior as on Rust vectors.
Note that *slice* indices (accepted by `PySequence::get_slice` and other) still
inherit the Python behavior of clamping the indices to the actual length, and
not panicking/returning an error on out of range indices.
An additional advantage of using Rust's indexing conventions for these types is
that these types can now also support Rust's indexing operators as part of a
consistent API:
```rust,ignore
#![allow(deprecated)]
use pyo3::{Python, types::PyList};
Python::with_gil(|py| {
let list = PyList::new(py, &[1, 2, 3]);
assert_eq!(list[0..2].to_string(), "[1, 2]");
});
```
</details>
## from 0.13.* to 0.14
### `auto-initialize` feature is now opt-in
<details>
<summary><small>Click to expand</small></summary>
For projects embedding Python in Rust, PyO3 no longer automatically initializes a Python interpreter on the first call to `Python::with_gil` (or `Python::acquire_gil`) unless the [`auto-initialize` feature](features.md#auto-initialize) is enabled.
</details>
### New `multiple-pymethods` feature
<details>
<summary><small>Click to expand</small></summary>
`#[pymethods]` have been reworked with a simpler default implementation which removes the dependency on the `inventory` crate. This reduces dependencies and compile times for the majority of users.
The limitation of the new default implementation is that it cannot support multiple `#[pymethods]` blocks for the same `#[pyclass]`. If you need this functionality, you must enable the `multiple-pymethods` feature which will switch `#[pymethods]` to the inventory-based implementation.
</details>
### Deprecated `#[pyproto]` methods
<details>
<summary><small>Click to expand</small></summary>
Some protocol (aka `__dunder__`) methods such as `__bytes__` and `__format__` have been possible to implement two ways in PyO3 for some time: via a `#[pyproto]` (e.g. `PyObjectProtocol` for the methods listed here), or by writing them directly in `#[pymethods]`. This is only true for a handful of the `#[pyproto]` methods (for technical reasons to do with the way PyO3 currently interacts with the Python C-API).
In the interest of having only one way to do things, the `#[pyproto]` forms of these methods have been deprecated.
To migrate just move the affected methods from a `#[pyproto]` to a `#[pymethods]` block.
Before:
```rust,compile_fail
use pyo3::prelude::*;
use pyo3::class::basic::PyObjectProtocol;
#[pyclass]
struct MyClass {}
#[pyproto]
impl PyObjectProtocol for MyClass {
fn __bytes__(&self) -> &'static [u8] {
b"hello, world"
}
}
```
After:
```rust
use pyo3::prelude::*;
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
fn __bytes__(&self) -> &'static [u8] {
b"hello, world"
}
}
```
</details>
## from 0.12.* to 0.13
### Minimum Rust version increased to Rust 1.45
<details>
<summary><small>Click to expand</small></summary>
PyO3 `0.13` makes use of new Rust language features stabilized between Rust 1.40 and Rust 1.45. If you are using a Rust compiler older than Rust 1.45, you will need to update your toolchain to be able to continue using PyO3.
</details>
### Runtime changes to support the CPython limited API
<details>
<summary><small>Click to expand</small></summary>
In PyO3 `0.13` support was added for compiling against the CPython limited API. This had a number of implications for _all_ PyO3 users, described here.
The largest of these is that all types created from PyO3 are what CPython calls "heap" types. The specific implications of this are:
- If you wish to subclass one of these types _from Rust_ you must mark it `#[pyclass(subclass)]`, as you would if you wished to allow subclassing it from Python code.
- Type objects are now mutable - Python code can set attributes on them.
- `__module__` on types without `#[pyclass(module="mymodule")]` no longer returns `builtins`, it now raises `AttributeError`.
</details>
## from 0.11.* to 0.12
### `PyErr` has been reworked
<details>
<summary><small>Click to expand</small></summary>
In PyO3 `0.12` the `PyErr` type has been re-implemented to be significantly more compatible with
the standard Rust error handling ecosystem. Specifically `PyErr` now implements
`Error + Send + Sync`, which are the standard traits used for error types.
While this has necessitated the removal of a number of APIs, the resulting `PyErr` type should now
be much more easier to work with. The following sections list the changes in detail and how to
migrate to the new APIs.
</details>
#### `PyErr::new` and `PyErr::from_type` now require `Send + Sync` for their argument
<details>
<summary><small>Click to expand</small></summary>
For most uses no change will be needed. If you are trying to construct `PyErr` from a value that is
not `Send + Sync`, you will need to first create the Python object and then use
`PyErr::from_instance`.
Similarly, any types which implemented `PyErrArguments` will now need to be `Send + Sync`.
</details>
#### `PyErr`'s contents are now private
<details>
<summary><small>Click to expand</small></summary>
It is no longer possible to access the fields `.ptype`, `.pvalue` and `.ptraceback` of a `PyErr`.
You should instead now use the new methods `PyErr::ptype`, `PyErr::pvalue` and `PyErr::ptraceback`.
</details>
#### `PyErrValue` and `PyErr::from_value` have been removed
<details>
<summary><small>Click to expand</small></summary>
As these were part the internals of `PyErr` which have been reworked, these APIs no longer exist.
If you used this API, it is recommended to use `PyException::new_err` (see [the section on
Exception types](#exception-types-have-been-reworked)).
</details>
#### `Into<PyResult<T>>` for `PyErr` has been removed
<details>
<summary><small>Click to expand</small></summary>
This implementation was redundant. Just construct the `Result::Err` variant directly.
Before:
```rust,compile_fail
let result: PyResult<()> = PyErr::new::<TypeError, _>("error message").into();
```
After (also using the new reworked exception types; see the following section):
```rust
# use pyo3::{PyResult, exceptions::PyTypeError};
let result: PyResult<()> = Err(PyTypeError::new_err("error message"));
```
</details>
### Exception types have been reworked
<details>
<summary><small>Click to expand</small></summary>
Previously exception types were zero-sized marker types purely used to construct `PyErr`. In PyO3
0.12, these types have been replaced with full definitions and are usable in the same way as `PyAny`, `PyDict` etc. This
makes it possible to interact with Python exception objects.
The new types also have names starting with the "Py" prefix. For example, before:
```rust,ignore
let err: PyErr = TypeError::py_err("error message");
```
After:
```rust,ignore
# use pyo3::{PyErr, PyResult, Python, type_object::PyTypeObject};
# use pyo3::exceptions::{PyBaseException, PyTypeError};
# Python::with_gil(|py| -> PyResult<()> {
let err: PyErr = PyTypeError::new_err("error message");
// Uses Display for PyErr, new for PyO3 0.12
assert_eq!(err.to_string(), "TypeError: error message");
// Now possible to interact with exception instances, new for PyO3 0.12
let instance: &PyBaseException = err.instance(py);
assert_eq!(
instance.getattr("__class__")?,
PyTypeError::type_object(py).as_ref()
);
# Ok(())
# }).unwrap();
```
</details>
### `FromPy` has been removed
<details>
<summary><small>Click to expand</small></summary>
To simplify the PyO3 conversion traits, the `FromPy` trait has been removed. Previously there were
two ways to define the to-Python conversion for a type:
`FromPy<T> for PyObject` and `IntoPy<PyObject> for T`.
Now there is only one way to define the conversion, `IntoPy`, so downstream crates may need to
adjust accordingly.
Before:
```rust,compile_fail
# use pyo3::prelude::*;
struct MyPyObjectWrapper(PyObject);
impl FromPy<MyPyObjectWrapper> for PyObject {
fn from_py(other: MyPyObjectWrapper, _py: Python<'_>) -> Self {
other.0
}
}
```
After
```rust
# use pyo3::prelude::*;
# #[allow(dead_code)]
struct MyPyObjectWrapper(PyObject);
# #[allow(deprecated)]
impl IntoPy<PyObject> for MyPyObjectWrapper {
fn into_py(self, _py: Python<'_>) -> PyObject {
self.0
}
}
```
Similarly, code which was using the `FromPy` trait can be trivially rewritten to use `IntoPy`.
Before:
```rust,compile_fail
# use pyo3::prelude::*;
# Python::with_gil(|py| {
let obj = PyObject::from_py(1.234, py);
# })
```
After:
```rust
# #![allow(deprecated)]
# use pyo3::prelude::*;
# Python::with_gil(|py| {
let obj: PyObject = 1.234.into_py(py);
# })
```
</details>
### `PyObject` is now a type alias of `Py<PyAny>`
<details>
<summary><small>Click to expand</small></summary>
This should change very little from a usage perspective. If you implemented traits for both
`PyObject` and `Py<T>`, you may find you can just remove the `PyObject` implementation.
</details>
### `AsPyRef` has been removed
<details>
<summary><small>Click to expand</small></summary>
As `PyObject` has been changed to be just a type alias, the only remaining implementor of `AsPyRef`
was `Py<T>`. This removed the need for a trait, so the `AsPyRef::as_ref` method has been moved to
`Py::as_ref`.
This should require no code changes except removing `use pyo3::AsPyRef` for code which did not use
`pyo3::prelude::*`.
Before:
```rust,ignore
use pyo3::{AsPyRef, Py, types::PyList};
# pyo3::Python::with_gil(|py| {
let list_py: Py<PyList> = PyList::empty(py).into();
let list_ref: &PyList = list_py.as_ref(py);
# })
```
After:
```rust,ignore
use pyo3::{Py, types::PyList};
# pyo3::Python::with_gil(|py| {
let list_py: Py<PyList> = PyList::empty(py).into();
let list_ref: &PyList = list_py.as_ref(py);
# })
```
</details>
## from 0.10.* to 0.11
### Stable Rust
<details>
<summary><small>Click to expand</small></summary>
PyO3 now supports the stable Rust toolchain. The minimum required version is 1.39.0.
</details>
### `#[pyclass]` structs must now be `Send` or `unsendable`
<details>
<summary><small>Click to expand</small></summary>
Because `#[pyclass]` structs can be sent between threads by the Python interpreter, they must implement
`Send` or declared as `unsendable` (by `#[pyclass(unsendable)]`).
Note that `unsendable` is added in PyO3 `0.11.1` and `Send` is always required in PyO3 `0.11.0`.
This may "break" some code which previously was accepted, even though it could be unsound.
There can be two fixes:
1. If you think that your `#[pyclass]` actually must be `Send`able, then let's implement `Send`.
A common, safer way is using thread-safe types. E.g., `Arc` instead of `Rc`, `Mutex` instead of
`RefCell`, and `Box<dyn Send + T>` instead of `Box<dyn T>`.
Before:
```rust,compile_fail
use pyo3::prelude::*;
use std::rc::Rc;
use std::cell::RefCell;
#[pyclass]
struct NotThreadSafe {
shared_bools: Rc<RefCell<Vec<bool>>>,
closure: Box<dyn Fn()>,
}
```
After:
```rust,ignore
# #![allow(dead_code)]
use pyo3::prelude::*;
use std::sync::{Arc, Mutex};
#[pyclass]
struct ThreadSafe {
shared_bools: Arc<Mutex<Vec<bool>>>,
closure: Box<dyn Fn() + Send>,
}
```
In situations where you cannot change your `#[pyclass]` to automatically implement `Send`
(e.g., when it contains a raw pointer), you can use `unsafe impl Send`.
In such cases, care should be taken to ensure the struct is actually thread safe.
See [the Rustonomicon](https://doc.rust-lang.org/nomicon/send-and-sync.html) for more.
2. If you think that your `#[pyclass]` should not be accessed by another thread, you can use
`unsendable` flag. A class marked with `unsendable` panics when accessed by another thread,
making it thread-safe to expose an unsendable object to the Python interpreter.
Before:
```rust,compile_fail
use pyo3::prelude::*;
#[pyclass]
struct Unsendable {
pointers: Vec<*mut std::os::raw::c_char>,
}
```
After:
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
#[pyclass(unsendable)]
struct Unsendable {
pointers: Vec<*mut std::os::raw::c_char>,
}
```
</details>
### All `PyObject` and `Py<T>` methods now take `Python` as an argument
<details>
<summary><small>Click to expand</small></summary>
Previously, a few methods such as `Object::get_refcnt` did not take `Python` as an argument (to
ensure that the Python GIL was held by the current thread). Technically, this was not sound.
To migrate, just pass a `py` argument to any calls to these methods.
Before:
```rust,compile_fail
# pyo3::Python::with_gil(|py| {
py.None().get_refcnt();
# })
```
After:
```rust
# pyo3::Python::with_gil(|py| {
py.None().get_refcnt(py);
# })
```
</details>
## from 0.9.* to 0.10
### `ObjectProtocol` is removed
<details>
<summary><small>Click to expand</small></summary>
All methods are moved to [`PyAny`].
And since now all native types (e.g., `PyList`) implements `Deref<Target=PyAny>`,
all you need to do is remove `ObjectProtocol` from your code.
Or if you use `ObjectProtocol` by `use pyo3::prelude::*`, you have to do nothing.
Before:
```rust,compile_fail,ignore
use pyo3::ObjectProtocol;
# pyo3::Python::with_gil(|py| {
let obj = py.eval("lambda: 'Hi :)'", None, None).unwrap();
let hi: &pyo3::types::PyString = obj.call0().unwrap().downcast().unwrap();
assert_eq!(hi.len().unwrap(), 5);
# })
```
After:
```rust,ignore
# pyo3::Python::with_gil(|py| {
let obj = py.eval("lambda: 'Hi :)'", None, None).unwrap();
let hi: &pyo3::types::PyString = obj.call0().unwrap().downcast().unwrap();
assert_eq!(hi.len().unwrap(), 5);
# })
```
</details>
### No `#![feature(specialization)]` in user code
<details>
<summary><small>Click to expand</small></summary>
While PyO3 itself still requires specialization and nightly Rust,
now you don't have to use `#![feature(specialization)]` in your crate.
</details>
## from 0.8.* to 0.9
### `#[new]` interface
<details>
<summary><small>Click to expand</small></summary>
[`PyRawObject`](https://docs.rs/pyo3/0.8.5/pyo3/type_object/struct.PyRawObject.html)
is now removed and our syntax for constructors has changed.
Before:
```rust,compile_fail
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
fn new(obj: &PyRawObject) {
obj.init(MyClass {})
}
}
```
After:
```rust
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
fn new() -> Self {
MyClass {}
}
}
```
Basically you can return `Self` or `Result<Self>` directly.
For more, see [the constructor section](class.md#constructor) of this guide.
</details>
### PyCell
<details>
<summary><small>Click to expand</small></summary>
PyO3 0.9 introduces `PyCell`, which is a [`RefCell`]-like object wrapper
for ensuring Rust's rules regarding aliasing of references are upheld.
For more detail, see the
[Rust Book's section on Rust's rules of references](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references)
For `#[pymethods]` or `#[pyfunction]`s, your existing code should continue to work without any change.
Python exceptions will automatically be raised when your functions are used in a way which breaks Rust's
rules of references.
Here is an example.
```rust
# use pyo3::prelude::*;
#[pyclass]
struct Names {
names: Vec<String>,
}
#[pymethods]
impl Names {
#[new]
fn new() -> Self {
Names { names: vec![] }
}
fn merge(&mut self, other: &mut Names) {
self.names.append(&mut other.names)
}
}
# Python::with_gil(|py| {
# let names = Py::new(py, Names::new()).unwrap();
# pyo3::py_run!(py, names, r"
# try:
# names.merge(names)
# assert False, 'Unreachable'
# except RuntimeError as e:
# assert str(e) == 'Already borrowed'
# ");
# })
```
`Names` has a `merge` method, which takes `&mut self` and another argument of type `&mut Self`.
Given this `#[pyclass]`, calling `names.merge(names)` in Python raises
a [`PyBorrowMutError`] exception, since it requires two mutable borrows of `names`.
However, for `#[pyproto]` and some functions, you need to manually fix the code.
#### Object creation
In 0.8 object creation was done with `PyRef::new` and `PyRefMut::new`.
In 0.9 these have both been removed.
To upgrade code, please use
`PyCell::new` instead.
If you need [`PyRef`] or [`PyRefMut`], just call `.borrow()` or `.borrow_mut()`
on the newly-created `PyCell`.
Before:
```rust,compile_fail
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {}
# Python::with_gil(|py| {
let obj_ref = PyRef::new(py, MyClass {}).unwrap();
# })
```
After:
```rust,ignore
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {}
# Python::with_gil(|py| {
let obj = PyCell::new(py, MyClass {}).unwrap();
let obj_ref = obj.borrow();
# })
```
#### Object extraction
For `PyClass` types `T`, `&T` and `&mut T` no longer have [`FromPyObject`] implementations.
Instead you should extract `PyRef<T>` or `PyRefMut<T>`, respectively.
If `T` implements `Clone`, you can extract `T` itself.
In addition, you can also extract `&PyCell<T>`, though you rarely need it.
Before:
```compile_fail
let obj: &PyAny = create_obj();
let obj_ref: &MyClass = obj.extract().unwrap();
let obj_ref_mut: &mut MyClass = obj.extract().unwrap();
```
After:
```rust,ignore
# use pyo3::prelude::*;
# use pyo3::types::IntoPyDict;
# #[pyclass] #[derive(Clone)] struct MyClass {}
# #[pymethods] impl MyClass { #[new]fn new() -> Self { MyClass {} }}
# Python::with_gil(|py| {
# let typeobj = py.get_type::<MyClass>();
# let d = [("c", typeobj)].into_py_dict(py);
# let create_obj = || py.eval("c()", None, Some(d)).unwrap();
let obj: &PyAny = create_obj();
let obj_cell: &PyCell<MyClass> = obj.extract().unwrap();
let obj_cloned: MyClass = obj.extract().unwrap(); // extracted by cloning the object
{
let obj_ref: PyRef<'_, MyClass> = obj.extract().unwrap();
// we need to drop obj_ref before we can extract a PyRefMut due to Rust's rules of references
}
let obj_ref_mut: PyRefMut<'_, MyClass> = obj.extract().unwrap();
# })
```
#### `#[pyproto]`
Most of the arguments to methods in `#[pyproto]` impls require a
[`FromPyObject`] implementation.
So if your protocol methods take `&T` or `&mut T` (where `T: PyClass`),
please use [`PyRef`] or [`PyRefMut`] instead.
Before:
```rust,compile_fail
# use pyo3::prelude::*;
# use pyo3::class::PySequenceProtocol;
#[pyclass]
struct ByteSequence {
elements: Vec<u8>,
}
#[pyproto]
impl PySequenceProtocol for ByteSequence {
fn __concat__(&self, other: &Self) -> PyResult<Self> {
let mut elements = self.elements.clone();
elements.extend_from_slice(&other.elements);
Ok(Self { elements })
}
}
```
After:
```rust,compile_fail
# use pyo3::prelude::*;
# use pyo3::class::PySequenceProtocol;
#[pyclass]
struct ByteSequence {
elements: Vec<u8>,
}
#[pyproto]
impl PySequenceProtocol for ByteSequence {
fn __concat__(&self, other: PyRef<'p, Self>) -> PyResult<Self> {
let mut elements = self.elements.clone();
elements.extend_from_slice(&other.elements);
Ok(Self { elements })
}
}
```
</details>
<style>
/* render details immediately below h3 headers */
h3:has(+ details) {
margin-bottom: 0;
}
/* make summary text hint that it's clickable and increase the
size of the clickable area by padding downwards */
details > summary {
cursor: pointer;
padding-bottom: 0.5em;
}
/* reduce margin from paragraph directly below the clickable space
to avoid large gap */
details > summary + p {
margin-block-start: 0.5em;
}
/* pack headings that aren't expanded slightly closer together */
h3 + details:not([open]) + h3 {
margin-top: 1.5em;
}
</style>
[`FromPyObject`]: {{#PYO3_DOCS_URL}}/pyo3/conversion/trait.FromPyObject.html
[`PyAny`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyAny.html
[`PyBorrowMutError`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyBorrowMutError.html
[`PyRef`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyRef.html
[`PyRefMut`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyRef.html
[`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/class.md | # Python classes
PyO3 exposes a group of attributes powered by Rust's proc macro system for defining Python classes as Rust structs.
The main attribute is `#[pyclass]`, which is placed upon a Rust `struct` or `enum` to generate a Python type for it. They will usually also have *one* `#[pymethods]`-annotated `impl` block for the struct, which is used to define Python methods and constants for the generated Python type. (If the [`multiple-pymethods`] feature is enabled, each `#[pyclass]` is allowed to have multiple `#[pymethods]` blocks.) `#[pymethods]` may also have implementations for Python magic methods such as `__str__`.
This chapter will discuss the functionality and configuration these attributes offer. Below is a list of links to the relevant section of this chapter for each:
- [`#[pyclass]`](#defining-a-new-class)
- [`#[pyo3(get, set)]`](#object-properties-using-pyo3get-set)
- [`#[pymethods]`](#instance-methods)
- [`#[new]`](#constructor)
- [`#[getter]`](#object-properties-using-getter-and-setter)
- [`#[setter]`](#object-properties-using-getter-and-setter)
- [`#[staticmethod]`](#static-methods)
- [`#[classmethod]`](#class-methods)
- [`#[classattr]`](#class-attributes)
- [`#[args]`](#method-arguments)
- [Magic methods and slots](class/protocols.md)
- [Classes as function arguments](#classes-as-function-arguments)
## Defining a new class
To define a custom Python class, add the `#[pyclass]` attribute to a Rust struct or enum.
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
#[pyclass]
struct MyClass {
inner: i32,
}
// A "tuple" struct
#[pyclass]
struct Number(i32);
// PyO3 supports unit-only enums (which contain only unit variants)
// These simple enums behave similarly to Python's enumerations (enum.Enum)
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum MyEnum {
Variant,
OtherVariant = 30, // PyO3 supports custom discriminants.
}
// PyO3 supports custom discriminants in unit-only enums
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum HttpResponse {
Ok = 200,
NotFound = 404,
Teapot = 418,
// ...
}
// PyO3 also supports enums with Struct and Tuple variants
// These complex enums have sligtly different behavior from the simple enums above
// They are meant to work with instance checks and match statement patterns
// The variants can be mixed and matched
// Struct variants have named fields while tuple enums generate generic names for fields in order _0, _1, _2, ...
// Apart from this both types are functionally identical
#[pyclass]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
RegularPolygon(u32, f64),
Nothing(),
}
```
The above example generates implementations for [`PyTypeInfo`] and [`PyClass`] for `MyClass`, `Number`, `MyEnum`, `HttpResponse`, and `Shape`. To see these generated implementations, refer to the [implementation details](#implementation-details) at the end of this chapter.
### Restrictions
To integrate Rust types with Python, PyO3 needs to place some restrictions on the types which can be annotated with `#[pyclass]`. In particular, they must have no lifetime parameters, no generic parameters, and must implement `Send`. The reason for each of these is explained below.
#### No lifetime parameters
Rust lifetimes are used by the Rust compiler to reason about a program's memory safety. They are a compile-time only concept; there is no way to access Rust lifetimes at runtime from a dynamic language like Python.
As soon as Rust data is exposed to Python, there is no guarantee that the Rust compiler can make on how long the data will live. Python is a reference-counted language and those references can be held for an arbitrarily long time which is untraceable by the Rust compiler. The only possible way to express this correctly is to require that any `#[pyclass]` does not borrow data for any lifetime shorter than the `'static` lifetime, i.e. the `#[pyclass]` cannot have any lifetime parameters.
When you need to share ownership of data between Python and Rust, instead of using borrowed references with lifetimes consider using reference-counted smart pointers such as [`Arc`] or [`Py`].
#### No generic parameters
A Rust `struct Foo<T>` with a generic parameter `T` generates new compiled implementations each time it is used with a different concrete type for `T`. These new implementations are generated by the compiler at each usage site. This is incompatible with wrapping `Foo` in Python, where there needs to be a single compiled implementation of `Foo` which is integrated with the Python interpreter.
Currently, the best alternative is to write a macro which expands to a new `#[pyclass]` for each instantiation you want:
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
struct GenericClass<T> {
data: T,
}
macro_rules! create_interface {
($name: ident, $type: ident) => {
#[pyclass]
pub struct $name {
inner: GenericClass<$type>,
}
#[pymethods]
impl $name {
#[new]
pub fn new(data: $type) -> Self {
Self {
inner: GenericClass { data: data },
}
}
}
};
}
create_interface!(IntClass, i64);
create_interface!(FloatClass, String);
```
#### Must be Send
Because Python objects are freely shared between threads by the Python interpreter, there is no guarantee which thread will eventually drop the object. Therefore all types annotated with `#[pyclass]` must implement `Send` (unless annotated with [`#[pyclass(unsendable)]`](#customizing-the-class)).
## Constructor
By default, it is not possible to create an instance of a custom class from Python code.
To declare a constructor, you need to define a method and annotate it with the `#[new]`
attribute. Only Python's `__new__` method can be specified, `__init__` is not available.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
#[new]
fn new(value: i32) -> Self {
Number(value)
}
}
```
Alternatively, if your `new` method may fail you can return `PyResult<Self>`.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::exceptions::PyValueError;
# #[pyclass]
# struct Nonzero(i32);
#
#[pymethods]
impl Nonzero {
#[new]
fn py_new(value: i32) -> PyResult<Self> {
if value == 0 {
Err(PyValueError::new_err("cannot be zero"))
} else {
Ok(Nonzero(value))
}
}
}
```
If you want to return an existing object (for example, because your `new`
method caches the values it returns), `new` can return `pyo3::Py<Self>`.
As you can see, the Rust method name is not important here; this way you can
still, use `new()` for a Rust-level constructor.
If no method marked with `#[new]` is declared, object instances can only be
created from Rust, but not from Python.
For arguments, see the [`Method arguments`](#method-arguments) section below.
## Adding the class to a module
The next step is to create the module initializer and add our class to it:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# #[pyclass]
# struct Number(i32);
#
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Number>()?;
Ok(())
}
```
## Bound<T> and interior mutability
Often is useful to turn a `#[pyclass]` type `T` into a Python object and access it from Rust code. The [`Py<T>`] and [`Bound<'py, T>`] smart pointers are the ways to represent a Python object in PyO3's API. More detail can be found about them [in the Python objects](./types.md#pyo3s-smart-pointers) section of the guide.
Most Python objects do not offer exclusive (`&mut`) access (see the [section on Python's memory model](./python-from-rust.md#pythons-memory-model)). However, Rust structs wrapped as Python objects (called `pyclass` types) often *do* need `&mut` access. Due to the GIL, PyO3 *can* guarantee exclusive access to them.
The Rust borrow checker cannot reason about `&mut` references once an object's ownership has been passed to the Python interpreter. This means that borrow checking is done at runtime using with a scheme very similar to `std::cell::RefCell<T>`. This is known as [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html).
Users who are familiar with `RefCell<T>` can use `Py<T>` and `Bound<'py, T>` just like `RefCell<T>`.
For users who are not very familiar with `RefCell<T>`, here is a reminder of Rust's rules of borrowing:
- At any given time, you can have either (but not both of) one mutable reference or any number of immutable references.
- References can never outlast the data they refer to.
`Py<T>` and `Bound<'py, T>`, like `RefCell<T>`, ensure these borrowing rules by tracking references at runtime.
```rust
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
#[pyo3(get)]
num: i32,
}
Python::with_gil(|py| {
let obj = Bound::new(py, MyClass { num: 3 }).unwrap();
{
let obj_ref = obj.borrow(); // Get PyRef
assert_eq!(obj_ref.num, 3);
// You cannot get PyRefMut unless all PyRefs are dropped
assert!(obj.try_borrow_mut().is_err());
}
{
let mut obj_mut = obj.borrow_mut(); // Get PyRefMut
obj_mut.num = 5;
// You cannot get any other refs until the PyRefMut is dropped
assert!(obj.try_borrow().is_err());
assert!(obj.try_borrow_mut().is_err());
}
// You can convert `Bound` to a Python object
pyo3::py_run!(py, obj, "assert obj.num == 5");
});
```
A `Bound<'py, T>` is restricted to the GIL lifetime `'py`. To make the object longer lived (for example, to store it in a struct on the
Rust side), use `Py<T>`. `Py<T>` needs a `Python<'_>` token to allow access:
```rust
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
num: i32,
}
fn return_myclass() -> Py<MyClass> {
Python::with_gil(|py| Py::new(py, MyClass { num: 1 }).unwrap())
}
let obj = return_myclass();
Python::with_gil(move |py| {
let bound = obj.bind(py); // Py<MyClass>::bind returns &Bound<'py, MyClass>
let obj_ref = bound.borrow(); // Get PyRef<T>
assert_eq!(obj_ref.num, 1);
});
```
### frozen classes: Opting out of interior mutability
As detailed above, runtime borrow checking is currently enabled by default. But a class can opt of out it by declaring itself `frozen`. It can still use interior mutability via standard Rust types like `RefCell` or `Mutex`, but it is not bound to the implementation provided by PyO3 and can choose the most appropriate strategy on field-by-field basis.
Classes which are `frozen` and also `Sync`, e.g. they do use `Mutex` but not `RefCell`, can be accessed without needing the Python GIL via the `Bound::get` and `Py::get` methods:
```rust
use std::sync::atomic::{AtomicUsize, Ordering};
# use pyo3::prelude::*;
#[pyclass(frozen)]
struct FrozenCounter {
value: AtomicUsize,
}
let py_counter: Py<FrozenCounter> = Python::with_gil(|py| {
let counter = FrozenCounter {
value: AtomicUsize::new(0),
};
Py::new(py, counter).unwrap()
});
py_counter.get().value.fetch_add(1, Ordering::Relaxed);
Python::with_gil(move |_py| drop(py_counter));
```
Frozen classes are likely to become the default thereby guiding the PyO3 ecosystem towards a more deliberate application of interior mutability. Eventually, this should enable further optimizations of PyO3's internals and avoid downstream code paying the cost of interior mutability when it is not actually required.
## Customizing the class
{{#include ../pyclass-parameters.md}}
These parameters are covered in various sections of this guide.
### Return type
Generally, `#[new]` methods have to return `T: Into<PyClassInitializer<Self>>` or
`PyResult<T> where T: Into<PyClassInitializer<Self>>`.
For constructors that may fail, you should wrap the return type in a PyResult as well.
Consult the table below to determine which type your constructor should return:
| | **Cannot fail** | **May fail** |
|-----------------------------|---------------------------|-----------------------------------|
|**No inheritance** | `T` | `PyResult<T>` |
|**Inheritance(T Inherits U)**| `(T, U)` | `PyResult<(T, U)>` |
|**Inheritance(General Case)**| [`PyClassInitializer<T>`] | `PyResult<PyClassInitializer<T>>` |
## Inheritance
By default, `object`, i.e. `PyAny` is used as the base class. To override this default,
use the `extends` parameter for `pyclass` with the full path to the base class.
Currently, only classes defined in Rust and builtins provided by PyO3 can be inherited
from; inheriting from other classes defined in Python is not yet supported
([#991](https://github.com/PyO3/pyo3/issues/991)).
For convenience, `(T, U)` implements `Into<PyClassInitializer<T>>` where `U` is the
base class of `T`.
But for a more deeply nested inheritance, you have to return `PyClassInitializer<T>`
explicitly.
To get a parent class from a child, use [`PyRef`] instead of `&self` for methods,
or [`PyRefMut`] instead of `&mut self`.
Then you can access a parent class by `self_.as_super()` as `&PyRef<Self::BaseClass>`,
or by `self_.into_super()` as `PyRef<Self::BaseClass>` (and similar for the `PyRefMut`
case). For convenience, `self_.as_ref()` can also be used to get `&Self::BaseClass`
directly; however, this approach does not let you access base classes higher in the
inheritance hierarchy, for which you would need to chain multiple `as_super` or
`into_super` calls.
```rust
# use pyo3::prelude::*;
#[pyclass(subclass)]
struct BaseClass {
val1: usize,
}
#[pymethods]
impl BaseClass {
#[new]
fn new() -> Self {
BaseClass { val1: 10 }
}
pub fn method1(&self) -> PyResult<usize> {
Ok(self.val1)
}
}
#[pyclass(extends=BaseClass, subclass)]
struct SubClass {
val2: usize,
}
#[pymethods]
impl SubClass {
#[new]
fn new() -> (Self, BaseClass) {
(SubClass { val2: 15 }, BaseClass::new())
}
fn method2(self_: PyRef<'_, Self>) -> PyResult<usize> {
let super_ = self_.as_super(); // Get &PyRef<BaseClass>
super_.method1().map(|x| x * self_.val2)
}
}
#[pyclass(extends=SubClass)]
struct SubSubClass {
val3: usize,
}
#[pymethods]
impl SubSubClass {
#[new]
fn new() -> PyClassInitializer<Self> {
PyClassInitializer::from(SubClass::new()).add_subclass(SubSubClass { val3: 20 })
}
fn method3(self_: PyRef<'_, Self>) -> PyResult<usize> {
let base = self_.as_super().as_super(); // Get &PyRef<'_, BaseClass>
base.method1().map(|x| x * self_.val3)
}
fn method4(self_: PyRef<'_, Self>) -> PyResult<usize> {
let v = self_.val3;
let super_ = self_.into_super(); // Get PyRef<'_, SubClass>
SubClass::method2(super_).map(|x| x * v)
}
fn get_values(self_: PyRef<'_, Self>) -> (usize, usize, usize) {
let val1 = self_.as_super().as_super().val1;
let val2 = self_.as_super().val2;
(val1, val2, self_.val3)
}
fn double_values(mut self_: PyRefMut<'_, Self>) {
self_.as_super().as_super().val1 *= 2;
self_.as_super().val2 *= 2;
self_.val3 *= 2;
}
#[staticmethod]
fn factory_method(py: Python<'_>, val: usize) -> PyResult<PyObject> {
let base = PyClassInitializer::from(BaseClass::new());
let sub = base.add_subclass(SubClass { val2: val });
if val % 2 == 0 {
Ok(Py::new(py, sub)?.into_any())
} else {
let sub_sub = sub.add_subclass(SubSubClass { val3: val });
Ok(Py::new(py, sub_sub)?.into_any())
}
}
}
# Python::with_gil(|py| {
# let subsub = pyo3::Py::new(py, SubSubClass::new()).unwrap();
# pyo3::py_run!(py, subsub, "assert subsub.method1() == 10");
# pyo3::py_run!(py, subsub, "assert subsub.method2() == 150");
# pyo3::py_run!(py, subsub, "assert subsub.method3() == 200");
# pyo3::py_run!(py, subsub, "assert subsub.method4() == 3000");
# pyo3::py_run!(py, subsub, "assert subsub.get_values() == (10, 15, 20)");
# pyo3::py_run!(py, subsub, "assert subsub.double_values() == None");
# pyo3::py_run!(py, subsub, "assert subsub.get_values() == (20, 30, 40)");
# let subsub = SubSubClass::factory_method(py, 2).unwrap();
# let subsubsub = SubSubClass::factory_method(py, 3).unwrap();
# let cls = py.get_type::<SubSubClass>();
# pyo3::py_run!(py, subsub cls, "assert not isinstance(subsub, cls)");
# pyo3::py_run!(py, subsubsub cls, "assert isinstance(subsubsub, cls)");
# });
```
You can inherit native types such as `PyDict`, if they implement
[`PySizedLayout`]({{#PYO3_DOCS_URL}}/pyo3/type_object/trait.PySizedLayout.html).
This is not supported when building for the Python limited API (aka the `abi3` feature of PyO3).
To convert between the Rust type and its native base class, you can take
`slf` as a Python object. To access the Rust fields use `slf.borrow()` or
`slf.borrow_mut()`, and to access the base class use `slf.downcast::<BaseClass>()`.
```rust
# #[cfg(not(Py_LIMITED_API))] {
# use pyo3::prelude::*;
use pyo3::types::PyDict;
use std::collections::HashMap;
#[pyclass(extends=PyDict)]
#[derive(Default)]
struct DictWithCounter {
counter: HashMap<String, usize>,
}
#[pymethods]
impl DictWithCounter {
#[new]
fn new() -> Self {
Self::default()
}
fn set(slf: &Bound<'_, Self>, key: String, value: Bound<'_, PyAny>) -> PyResult<()> {
slf.borrow_mut().counter.entry(key.clone()).or_insert(0);
let dict = slf.downcast::<PyDict>()?;
dict.set_item(key, value)
}
}
# Python::with_gil(|py| {
# let cnt = pyo3::Py::new(py, DictWithCounter::new()).unwrap();
# pyo3::py_run!(py, cnt, "cnt.set('abc', 10); assert cnt['abc'] == 10")
# });
# }
```
If `SubClass` does not provide a base class initialization, the compilation fails.
```rust,compile_fail
# use pyo3::prelude::*;
#[pyclass]
struct BaseClass {
val1: usize,
}
#[pyclass(extends=BaseClass)]
struct SubClass {
val2: usize,
}
#[pymethods]
impl SubClass {
#[new]
fn new() -> Self {
SubClass { val2: 15 }
}
}
```
The `__new__` constructor of a native base class is called implicitly when
creating a new instance from Python. Be sure to accept arguments in the
`#[new]` method that you want the base class to get, even if they are not used
in that `fn`:
```rust
# #[allow(dead_code)]
# #[cfg(not(Py_LIMITED_API))] {
# use pyo3::prelude::*;
use pyo3::types::PyDict;
#[pyclass(extends=PyDict)]
struct MyDict {
private: i32,
}
#[pymethods]
impl MyDict {
#[new]
#[pyo3(signature = (*args, **kwargs))]
fn new(args: &Bound<'_, PyAny>, kwargs: Option<&Bound<'_, PyAny>>) -> Self {
Self { private: 0 }
}
// some custom methods that use `private` here...
}
# Python::with_gil(|py| {
# let cls = py.get_type::<MyDict>();
# pyo3::py_run!(py, cls, "cls(a=1, b=2)")
# });
# }
```
Here, the `args` and `kwargs` allow creating instances of the subclass passing
initial items, such as `MyDict(item_sequence)` or `MyDict(a=1, b=2)`.
## Object properties
PyO3 supports two ways to add properties to your `#[pyclass]`:
- For simple struct fields with no side effects, a `#[pyo3(get, set)]` attribute can be added directly to the field definition in the `#[pyclass]`.
- For properties which require computation you can define `#[getter]` and `#[setter]` functions in the [`#[pymethods]`](#instance-methods) block.
We'll cover each of these in the following sections.
### Object properties using `#[pyo3(get, set)]`
For simple cases where a member variable is just read and written with no side effects, you can declare getters and setters in your `#[pyclass]` field definition using the `pyo3` attribute, like in the example below:
```rust
# use pyo3::prelude::*;
# #[allow(dead_code)]
#[pyclass]
struct MyClass {
#[pyo3(get, set)]
num: i32,
}
```
The above would make the `num` field available for reading and writing as a `self.num` Python property. To expose the property with a different name to the field, specify this alongside the rest of the options, e.g. `#[pyo3(get, set, name = "custom_name")]`.
Properties can be readonly or writeonly by using just `#[pyo3(get)]` or `#[pyo3(set)]` respectively.
To use these annotations, your field type must implement some conversion traits:
- For `get` the field type must implement both `IntoPy<PyObject>` and `Clone`.
- For `set` the field type must implement `FromPyObject`.
For example, implementations of those traits are provided for the `Cell` type, if the inner type also implements the trait. This means you can use `#[pyo3(get, set)]` on fields wrapped in a `Cell`.
### Object properties using `#[getter]` and `#[setter]`
For cases which don't satisfy the `#[pyo3(get, set)]` trait requirements, or need side effects, descriptor methods can be defined in a `#[pymethods]` `impl` block.
This is done using the `#[getter]` and `#[setter]` attributes, like in the example below:
```rust
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
num: i32,
}
#[pymethods]
impl MyClass {
#[getter]
fn num(&self) -> PyResult<i32> {
Ok(self.num)
}
}
```
A getter or setter's function name is used as the property name by default. There are several
ways how to override the name.
If a function name starts with `get_` or `set_` for getter or setter respectively,
the descriptor name becomes the function name with this prefix removed. This is also useful in case of
Rust keywords like `type`
([raw identifiers](https://doc.rust-lang.org/edition-guide/rust-2018/module-system/raw-identifiers.html)
can be used since Rust 2018).
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
# num: i32,
# }
#[pymethods]
impl MyClass {
#[getter]
fn get_num(&self) -> PyResult<i32> {
Ok(self.num)
}
#[setter]
fn set_num(&mut self, value: i32) -> PyResult<()> {
self.num = value;
Ok(())
}
}
```
In this case, a property `num` is defined and available from Python code as `self.num`.
Both the `#[getter]` and `#[setter]` attributes accept one parameter.
If this parameter is specified, it is used as the property name, i.e.
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
# num: i32,
# }
#[pymethods]
impl MyClass {
#[getter(number)]
fn num(&self) -> PyResult<i32> {
Ok(self.num)
}
#[setter(number)]
fn set_num(&mut self, value: i32) -> PyResult<()> {
self.num = value;
Ok(())
}
}
```
In this case, the property `number` is defined and available from Python code as `self.number`.
Attributes defined by `#[setter]` or `#[pyo3(set)]` will always raise `AttributeError` on `del`
operations. Support for defining custom `del` behavior is tracked in
[#1778](https://github.com/PyO3/pyo3/issues/1778).
## Instance methods
To define a Python compatible method, an `impl` block for your struct has to be annotated with the
`#[pymethods]` attribute. PyO3 generates Python compatible wrappers for all functions in this
block with some variations, like descriptors, class method static methods, etc.
Since Rust allows any number of `impl` blocks, you can easily split methods
between those accessible to Python (and Rust) and those accessible only to Rust. However to have multiple
`#[pymethods]`-annotated `impl` blocks for the same struct you must enable the [`multiple-pymethods`] feature of PyO3.
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
# num: i32,
# }
#[pymethods]
impl MyClass {
fn method1(&self) -> PyResult<i32> {
Ok(10)
}
fn set_method(&mut self, value: i32) -> PyResult<()> {
self.num = value;
Ok(())
}
}
```
Calls to these methods are protected by the GIL, so both `&self` and `&mut self` can be used.
The return type must be `PyResult<T>` or `T` for some `T` that implements `IntoPy<PyObject>`;
the latter is allowed if the method cannot raise Python exceptions.
A `Python` parameter can be specified as part of method signature, in this case the `py` argument
gets injected by the method wrapper, e.g.
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
# #[allow(dead_code)]
# num: i32,
# }
#[pymethods]
impl MyClass {
fn method2(&self, py: Python<'_>) -> PyResult<i32> {
Ok(10)
}
}
```
From the Python perspective, the `method2` in this example does not accept any arguments.
## Class methods
To create a class method for a custom class, the method needs to be annotated
with the `#[classmethod]` attribute.
This is the equivalent of the Python decorator `@classmethod`.
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyType;
# #[pyclass]
# struct MyClass {
# #[allow(dead_code)]
# num: i32,
# }
#[pymethods]
impl MyClass {
#[classmethod]
fn cls_method(cls: &Bound<'_, PyType>) -> PyResult<i32> {
Ok(10)
}
}
```
Declares a class method callable from Python.
* The first parameter is the type object of the class on which the method is called.
This may be the type object of a derived class.
* The first parameter implicitly has type `&Bound<'_, PyType>`.
* For details on `parameter-list`, see the documentation of `Method arguments` section.
* The return type must be `PyResult<T>` or `T` for some `T` that implements `IntoPy<PyObject>`.
### Constructors which accept a class argument
To create a constructor which takes a positional class argument, you can combine the `#[classmethod]` and `#[new]` modifiers:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use pyo3::types::PyType;
# #[pyclass]
# struct BaseClass(PyObject);
#
#[pymethods]
impl BaseClass {
#[new]
#[classmethod]
fn py_new(cls: &Bound<'_, PyType>) -> PyResult<Self> {
// Get an abstract attribute (presumably) declared on a subclass of this class.
let subclass_attr: Bound<'_, PyAny> = cls.getattr("a_class_attr")?;
Ok(Self(subclass_attr.unbind()))
}
}
```
## Static methods
To create a static method for a custom class, the method needs to be annotated with the
`#[staticmethod]` attribute. The return type must be `T` or `PyResult<T>` for some `T` that implements
`IntoPy<PyObject>`.
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
# #[allow(dead_code)]
# num: i32,
# }
#[pymethods]
impl MyClass {
#[staticmethod]
fn static_method(param1: i32, param2: &str) -> PyResult<i32> {
Ok(10)
}
}
```
## Class attributes
To create a class attribute (also called [class variable][classattr]), a method without
any arguments can be annotated with the `#[classattr]` attribute.
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {}
#[pymethods]
impl MyClass {
#[classattr]
fn my_attribute() -> String {
"hello".to_string()
}
}
Python::with_gil(|py| {
let my_class = py.get_type::<MyClass>();
pyo3::py_run!(py, my_class, "assert my_class.my_attribute == 'hello'")
});
```
> Note: if the method has a `Result` return type and returns an `Err`, PyO3 will panic during
class creation.
If the class attribute is defined with `const` code only, one can also annotate associated
constants:
```rust
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {}
#[pymethods]
impl MyClass {
#[classattr]
const MY_CONST_ATTRIBUTE: &'static str = "foobar";
}
```
## Classes as function arguments
Free functions defined using `#[pyfunction]` interact with classes through the same mechanisms as the self parameters of instance methods, i.e. they can take GIL-bound references, GIL-bound reference wrappers or GIL-indepedent references:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
my_field: i32,
}
// Take a reference when the underlying `Bound` is irrelevant.
#[pyfunction]
fn increment_field(my_class: &mut MyClass) {
my_class.my_field += 1;
}
// Take a reference wrapper when borrowing should be automatic,
// but interaction with the underlying `Bound` is desired.
#[pyfunction]
fn print_field(my_class: PyRef<'_, MyClass>) {
println!("{}", my_class.my_field);
}
// Take a reference to the underlying Bound
// when borrowing needs to be managed manually.
#[pyfunction]
fn increment_then_print_field(my_class: &Bound<'_, MyClass>) {
my_class.borrow_mut().my_field += 1;
println!("{}", my_class.borrow().my_field);
}
// Take a GIL-indepedent reference when you want to store the reference elsewhere.
#[pyfunction]
fn print_refcnt(my_class: Py<MyClass>, py: Python<'_>) {
println!("{}", my_class.get_refcnt(py));
}
```
Classes can also be passed by value if they can be cloned, i.e. they automatically implement `FromPyObject` if they implement `Clone`, e.g. via `#[derive(Clone)]`:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyclass]
#[derive(Clone)]
struct MyClass {
my_field: Box<i32>,
}
#[pyfunction]
fn dissamble_clone(my_class: MyClass) {
let MyClass { mut my_field } = my_class;
*my_field += 1;
}
```
Note that `#[derive(FromPyObject)]` on a class is usually not useful as it tries to construct a new Rust value by filling in the fields by looking up attributes of any given Python value.
## Method arguments
Similar to `#[pyfunction]`, the `#[pyo3(signature = (...))]` attribute can be used to specify the way that `#[pymethods]` accept arguments. Consult the documentation for [`function signatures`](./function/signature.md) to see the parameters this attribute accepts.
The following example defines a class `MyClass` with a method `method`. This method has a signature that sets default values for `num` and `name`, and indicates that `py_args` should collect all extra positional arguments and `py_kwargs` all extra keyword arguments:
```rust
# use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
#
# #[pyclass]
# struct MyClass {
# num: i32,
# }
#[pymethods]
impl MyClass {
#[new]
#[pyo3(signature = (num=-1))]
fn new(num: i32) -> Self {
MyClass { num }
}
#[pyo3(signature = (num=10, *py_args, name="Hello", **py_kwargs))]
fn method(
&mut self,
num: i32,
py_args: &Bound<'_, PyTuple>,
name: &str,
py_kwargs: Option<&Bound<'_, PyDict>>,
) -> String {
let num_before = self.num;
self.num = num;
format!(
"num={} (was previously={}), py_args={:?}, name={}, py_kwargs={:?} ",
num, num_before, py_args, name, py_kwargs,
)
}
}
```
In Python, this might be used like:
```python
>>> import mymodule
>>> mc = mymodule.MyClass()
>>> print(mc.method(44, False, "World", 666, x=44, y=55))
py_args=('World', 666), py_kwargs=Some({'x': 44, 'y': 55}), name=Hello, num=44, num_before=-1
>>> print(mc.method(num=-1, name="World"))
py_args=(), py_kwargs=None, name=World, num=-1, num_before=44
```
The [`#[pyo3(text_signature = "...")`](./function/signature.md#overriding-the-generated-signature) option for `#[pyfunction]` also works for `#[pymethods]`.
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
use pyo3::types::PyType;
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
#[pyo3(text_signature = "(c, d)")]
fn new(c: i32, d: &str) -> Self {
Self {}
}
// the self argument should be written $self
#[pyo3(text_signature = "($self, e, f)")]
fn my_method(&self, e: i32, f: i32) -> i32 {
e + f
}
// similarly for classmethod arguments, use $cls
#[classmethod]
#[pyo3(text_signature = "($cls, e, f)")]
fn my_class_method(cls: &Bound<'_, PyType>, e: i32, f: i32) -> i32 {
e + f
}
#[staticmethod]
#[pyo3(text_signature = "(e, f)")]
fn my_static_method(e: i32, f: i32) -> i32 {
e + f
}
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let module = PyModule::new(py, "my_module")?;
# module.add_class::<MyClass>()?;
# let class = module.getattr("MyClass")?;
#
# if cfg!(not(Py_LIMITED_API)) || py.version_info() >= (3, 10) {
# let doc: String = class.getattr("__doc__")?.extract()?;
# assert_eq!(doc, "");
#
# let sig: String = inspect
# .call1((&class,))?
# .call_method0("__str__")?
# .extract()?;
# assert_eq!(sig, "(c, d)");
# } else {
# let doc: String = class.getattr("__doc__")?.extract()?;
# assert_eq!(doc, "");
#
# inspect.call1((&class,)).expect_err("`text_signature` on classes is not compatible with compilation in `abi3` mode until Python 3.10 or greater");
# }
#
# {
# let method = class.getattr("my_method")?;
#
# assert!(method.getattr("__doc__")?.is_none());
#
# let sig: String = inspect
# .call1((method,))?
# .call_method0("__str__")?
# .extract()?;
# assert_eq!(sig, "(self, /, e, f)");
# }
#
# {
# let method = class.getattr("my_class_method")?;
#
# assert!(method.getattr("__doc__")?.is_none());
#
# let sig: String = inspect
# .call1((method,))?
# .call_method0("__str__")?
# .extract()?;
# assert_eq!(sig, "(e, f)"); // inspect.signature skips the $cls arg
# }
#
# {
# let method = class.getattr("my_static_method")?;
#
# assert!(method.getattr("__doc__")?.is_none());
#
# let sig: String = inspect
# .call1((method,))?
# .call_method0("__str__")?
# .extract()?;
# assert_eq!(sig, "(e, f)");
# }
#
# Ok(())
# })
# }
```
Note that `text_signature` on `#[new]` is not compatible with compilation in
`abi3` mode until Python 3.10 or greater.
### Method receivers and lifetime elision
PyO3 supports writing instance methods using the normal method receivers for shared `&self` and unique `&mut self` references. This interacts with [lifetime elision][lifetime-elision] insofar as the lifetime of a such a receiver is assigned to all elided output lifetime parameters.
This is a good default for general Rust code where return values are more likely to borrow from the receiver than from the other arguments, if they contain any lifetimes at all. However, when returning bound references `Bound<'py, T>` in PyO3-based code, the GIL lifetime `'py` should usually be derived from a GIL token `py: Python<'py>` passed as an argument instead of the receiver.
Specifically, signatures like
```rust,ignore
fn frobnicate(&self, py: Python) -> Bound<Foo>;
```
will not work as they are inferred as
```rust,ignore
fn frobnicate<'a, 'py>(&'a self, py: Python<'py>) -> Bound<'a, Foo>;
```
instead of the intended
```rust,ignore
fn frobnicate<'a, 'py>(&'a self, py: Python<'py>) -> Bound<'py, Foo>;
```
and should usually be written as
```rust,ignore
fn frobnicate<'py>(&self, py: Python<'py>) -> Bound<'py, Foo>;
```
The same problem does not exist for `#[pyfunction]`s as the special case for receiver lifetimes does not apply and indeed a signature like
```rust,ignore
fn frobnicate(bar: &Bar, py: Python) -> Bound<Foo>;
```
will yield compiler error [E0106 "missing lifetime specifier"][compiler-error-e0106].
## `#[pyclass]` enums
Enum support in PyO3 comes in two flavors, depending on what kind of variants the enum has: simple and complex.
### Simple enums
A simple enum (a.k.a. C-like enum) has only unit variants.
PyO3 adds a class attribute for each variant, so you can access them in Python without defining `#[new]`. PyO3 also provides default implementations of `__richcmp__` and `__int__`, so they can be compared using `==`:
```rust
# use pyo3::prelude::*;
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum MyEnum {
Variant,
OtherVariant,
}
Python::with_gil(|py| {
let x = Py::new(py, MyEnum::Variant).unwrap();
let y = Py::new(py, MyEnum::OtherVariant).unwrap();
let cls = py.get_type::<MyEnum>();
pyo3::py_run!(py, x y cls, r#"
assert x == cls.Variant
assert y == cls.OtherVariant
assert x != y
"#)
})
```
You can also convert your simple enums into `int`:
```rust
# use pyo3::prelude::*;
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum MyEnum {
Variant,
OtherVariant = 10,
}
Python::with_gil(|py| {
let cls = py.get_type::<MyEnum>();
let x = MyEnum::Variant as i32; // The exact value is assigned by the compiler.
pyo3::py_run!(py, cls x, r#"
assert int(cls.Variant) == x
assert int(cls.OtherVariant) == 10
"#)
})
```
PyO3 also provides `__repr__` for enums:
```rust
# use pyo3::prelude::*;
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum MyEnum{
Variant,
OtherVariant,
}
Python::with_gil(|py| {
let cls = py.get_type::<MyEnum>();
let x = Py::new(py, MyEnum::Variant).unwrap();
pyo3::py_run!(py, cls x, r#"
assert repr(x) == 'MyEnum.Variant'
assert repr(cls.OtherVariant) == 'MyEnum.OtherVariant'
"#)
})
```
All methods defined by PyO3 can be overridden. For example here's how you override `__repr__`:
```rust
# use pyo3::prelude::*;
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum MyEnum {
Answer = 42,
}
#[pymethods]
impl MyEnum {
fn __repr__(&self) -> &'static str {
"42"
}
}
Python::with_gil(|py| {
let cls = py.get_type::<MyEnum>();
pyo3::py_run!(py, cls, "assert repr(cls.Answer) == '42'")
})
```
Enums and their variants can also be renamed using `#[pyo3(name)]`.
```rust
# use pyo3::prelude::*;
#[pyclass(eq, eq_int, name = "RenamedEnum")]
#[derive(PartialEq)]
enum MyEnum {
#[pyo3(name = "UPPERCASE")]
Variant,
}
Python::with_gil(|py| {
let x = Py::new(py, MyEnum::Variant).unwrap();
let cls = py.get_type::<MyEnum>();
pyo3::py_run!(py, x cls, r#"
assert repr(x) == 'RenamedEnum.UPPERCASE'
assert x == cls.UPPERCASE
"#)
})
```
Ordering of enum variants is optionally added using `#[pyo3(ord)]`.
*Note: Implementation of the `PartialOrd` trait is required when passing the `ord` argument. If not implemented, a compile time error is raised.*
```rust
# use pyo3::prelude::*;
#[pyclass(eq, ord)]
#[derive(PartialEq, PartialOrd)]
enum MyEnum{
A,
B,
C,
}
Python::with_gil(|py| {
let cls = py.get_type::<MyEnum>();
let a = Py::new(py, MyEnum::A).unwrap();
let b = Py::new(py, MyEnum::B).unwrap();
let c = Py::new(py, MyEnum::C).unwrap();
pyo3::py_run!(py, cls a b c, r#"
assert (a < b) == True
assert (c <= b) == False
assert (c > a) == True
"#)
})
```
You may not use enums as a base class or let enums inherit from other classes.
```rust,compile_fail
# use pyo3::prelude::*;
#[pyclass(subclass)]
enum BadBase {
Var1,
}
```
```rust,compile_fail
# use pyo3::prelude::*;
#[pyclass(subclass)]
struct Base;
#[pyclass(extends=Base)]
enum BadSubclass {
Var1,
}
```
`#[pyclass]` enums are currently not interoperable with `IntEnum` in Python.
### Complex enums
An enum is complex if it has any non-unit (struct or tuple) variants.
PyO3 supports only struct and tuple variants in a complex enum. Unit variants aren't supported at present (the recommendation is to use an empty tuple enum instead).
PyO3 adds a class attribute for each variant, which may be used to construct values and in match patterns. PyO3 also provides getter methods for all fields of each variant.
```rust
# use pyo3::prelude::*;
#[pyclass]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
RegularPolygon(u32, f64),
Nothing { },
}
# #[cfg(Py_3_10)]
Python::with_gil(|py| {
let circle = Shape::Circle { radius: 10.0 }.into_pyobject(py)?;
let square = Shape::RegularPolygon(4, 10.0).into_pyobject(py)?;
let cls = py.get_type::<Shape>();
pyo3::py_run!(py, circle square cls, r#"
assert isinstance(circle, cls)
assert isinstance(circle, cls.Circle)
assert circle.radius == 10.0
assert isinstance(square, cls)
assert isinstance(square, cls.RegularPolygon)
assert square[0] == 4 # Gets _0 field
assert square[1] == 10.0 # Gets _1 field
def count_vertices(cls, shape):
match shape:
case cls.Circle():
return 0
case cls.Rectangle():
return 4
case cls.RegularPolygon(n):
return n
case cls.Nothing():
return 0
assert count_vertices(cls, circle) == 0
assert count_vertices(cls, square) == 4
"#);
# Ok::<_, PyErr>(())
})
# .unwrap();
```
WARNING: `Py::new` and `.into_pyobject` are currently inconsistent. Note how the constructed value is _not_ an instance of the specific variant. For this reason, constructing values is only recommended using `.into_pyobject`.
```rust
# use pyo3::prelude::*;
#[pyclass]
enum MyEnum {
Variant { i: i32 },
}
Python::with_gil(|py| {
let x = Py::new(py, MyEnum::Variant { i: 42 }).unwrap();
let cls = py.get_type::<MyEnum>();
pyo3::py_run!(py, x cls, r#"
assert isinstance(x, cls)
assert not isinstance(x, cls.Variant)
"#)
})
```
The constructor of each generated class can be customized using the `#[pyo3(constructor = (...))]` attribute. This uses the same syntax as the [`#[pyo3(signature = (...))]`](function/signature.md)
attribute on function and methods and supports the same options. To apply this attribute simply place it on top of a variant in a `#[pyclass]` complex enum as shown below:
```rust
# use pyo3::prelude::*;
#[pyclass]
enum Shape {
#[pyo3(constructor = (radius=1.0))]
Circle { radius: f64 },
#[pyo3(constructor = (*, width, height))]
Rectangle { width: f64, height: f64 },
#[pyo3(constructor = (side_count, radius=1.0))]
RegularPolygon { side_count: u32, radius: f64 },
Nothing { },
}
# #[cfg(Py_3_10)]
Python::with_gil(|py| {
let cls = py.get_type::<Shape>();
pyo3::py_run!(py, cls, r#"
circle = cls.Circle()
assert isinstance(circle, cls)
assert isinstance(circle, cls.Circle)
assert circle.radius == 1.0
square = cls.Rectangle(width = 1, height = 1)
assert isinstance(square, cls)
assert isinstance(square, cls.Rectangle)
assert square.width == 1
assert square.height == 1
hexagon = cls.RegularPolygon(6)
assert isinstance(hexagon, cls)
assert isinstance(hexagon, cls.RegularPolygon)
assert hexagon.side_count == 6
assert hexagon.radius == 1
"#)
})
```
## Implementation details
The `#[pyclass]` macros rely on a lot of conditional code generation: each `#[pyclass]` can optionally have a `#[pymethods]` block.
To support this flexibility the `#[pyclass]` macro expands to a blob of boilerplate code which sets up the structure for ["dtolnay specialization"](https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md). This implementation pattern enables the Rust compiler to use `#[pymethods]` implementations when they are present, and fall back to default (empty) definitions when they are not.
This simple technique works for the case when there is zero or one implementations. To support multiple `#[pymethods]` for a `#[pyclass]` (in the [`multiple-pymethods`] feature), a registry mechanism provided by the [`inventory`](https://github.com/dtolnay/inventory) crate is used instead. This collects `impl`s at library load time, but isn't supported on all platforms. See [inventory: how it works](https://github.com/dtolnay/inventory#how-it-works) for more details.
The `#[pyclass]` macro expands to roughly the code seen below. The `PyClassImplCollector` is the type used internally by PyO3 for dtolnay specialization:
```rust
# #[cfg(not(feature = "multiple-pymethods"))] {
# use pyo3::prelude::*;
// Note: the implementation differs slightly with the `multiple-pymethods` feature enabled.
# #[allow(dead_code)]
struct MyClass {
# #[allow(dead_code)]
num: i32,
}
impl pyo3::types::DerefToPyAny for MyClass {}
unsafe impl pyo3::type_object::PyTypeInfo for MyClass {
const NAME: &'static str = "MyClass";
const MODULE: ::std::option::Option<&'static str> = ::std::option::Option::None;
#[inline]
fn type_object_raw(py: pyo3::Python<'_>) -> *mut pyo3::ffi::PyTypeObject {
<Self as pyo3::impl_::pyclass::PyClassImpl>::lazy_type_object()
.get_or_init(py)
.as_type_ptr()
}
}
impl pyo3::PyClass for MyClass {
type Frozen = pyo3::pyclass::boolean_struct::False;
}
impl<'a, 'py> pyo3::impl_::extract_argument::PyFunctionArgument<'a, 'py> for &'a MyClass
{
type Holder = ::std::option::Option<pyo3::PyRef<'py, MyClass>>;
#[inline]
fn extract(obj: &'a pyo3::Bound<'py, PyAny>, holder: &'a mut Self::Holder) -> pyo3::PyResult<Self> {
pyo3::impl_::extract_argument::extract_pyclass_ref(obj, holder)
}
}
impl<'a, 'py> pyo3::impl_::extract_argument::PyFunctionArgument<'a, 'py> for &'a mut MyClass
{
type Holder = ::std::option::Option<pyo3::PyRefMut<'py, MyClass>>;
#[inline]
fn extract(obj: &'a pyo3::Bound<'py, PyAny>, holder: &'a mut Self::Holder) -> pyo3::PyResult<Self> {
pyo3::impl_::extract_argument::extract_pyclass_ref_mut(obj, holder)
}
}
#[allow(deprecated)]
impl pyo3::IntoPy<PyObject> for MyClass {
fn into_py(self, py: pyo3::Python<'_>) -> pyo3::PyObject {
pyo3::IntoPy::into_py(pyo3::Py::new(py, self).unwrap(), py)
}
}
impl pyo3::impl_::pyclass::PyClassImpl for MyClass {
const IS_BASETYPE: bool = false;
const IS_SUBCLASS: bool = false;
const IS_MAPPING: bool = false;
const IS_SEQUENCE: bool = false;
type BaseType = PyAny;
type ThreadChecker = pyo3::impl_::pyclass::SendablePyClass<MyClass>;
type PyClassMutability = <<pyo3::PyAny as pyo3::impl_::pyclass::PyClassBaseType>::PyClassMutability as pyo3::impl_::pycell::PyClassMutability>::MutableChild;
type Dict = pyo3::impl_::pyclass::PyClassDummySlot;
type WeakRef = pyo3::impl_::pyclass::PyClassDummySlot;
type BaseNativeType = pyo3::PyAny;
fn items_iter() -> pyo3::impl_::pyclass::PyClassItemsIter {
use pyo3::impl_::pyclass::*;
let collector = PyClassImplCollector::<MyClass>::new();
static INTRINSIC_ITEMS: PyClassItems = PyClassItems { slots: &[], methods: &[] };
PyClassItemsIter::new(&INTRINSIC_ITEMS, collector.py_methods())
}
fn lazy_type_object() -> &'static pyo3::impl_::pyclass::LazyTypeObject<MyClass> {
use pyo3::impl_::pyclass::LazyTypeObject;
static TYPE_OBJECT: LazyTypeObject<MyClass> = LazyTypeObject::new();
&TYPE_OBJECT
}
fn doc(py: Python<'_>) -> pyo3::PyResult<&'static ::std::ffi::CStr> {
use pyo3::impl_::pyclass::*;
static DOC: pyo3::sync::GILOnceCell<::std::borrow::Cow<'static, ::std::ffi::CStr>> = pyo3::sync::GILOnceCell::new();
DOC.get_or_try_init(py, || {
let collector = PyClassImplCollector::<Self>::new();
build_pyclass_doc(<MyClass as pyo3::PyTypeInfo>::NAME, pyo3::ffi::c_str!(""), collector.new_text_signature())
}).map(::std::ops::Deref::deref)
}
}
# Python::with_gil(|py| {
# let cls = py.get_type::<MyClass>();
# pyo3::py_run!(py, cls, "assert cls.__name__ == 'MyClass'")
# });
# }
```
[`PyTypeInfo`]: {{#PYO3_DOCS_URL}}/pyo3/type_object/trait.PyTypeInfo.html
[`Py`]: {{#PYO3_DOCS_URL}}/pyo3/struct.Py.html
[`Bound<'_, T>`]: {{#PYO3_DOCS_URL}}/pyo3/struct.Bound.html
[`PyClass`]: {{#PYO3_DOCS_URL}}/pyo3/pyclass/trait.PyClass.html
[`PyRef`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyRef.html
[`PyRefMut`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyRefMut.html
[`PyClassInitializer<T>`]: {{#PYO3_DOCS_URL}}/pyo3/pyclass_init/struct.PyClassInitializer.html
[`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
[`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
[classattr]: https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables
[`multiple-pymethods`]: features.md#multiple-pymethods
[lifetime-elision]: https://doc.rust-lang.org/reference/lifetime-elision.html
[compiler-error-e0106]: https://doc.rust-lang.org/error_codes/E0106.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/python-from-rust.md | # Calling Python in Rust code
This chapter of the guide documents some ways to interact with Python code from Rust.
Below is an introduction to the `'py` lifetime and some general remarks about how PyO3's API reasons about Python code.
The subchapters also cover the following topics:
- Python object types available in PyO3's API
- How to work with Python exceptions
- How to call Python functions
- How to execute existing Python code
## The `'py` lifetime
To safely interact with the Python interpreter a Rust thread must have a corresponding Python thread state and hold the [Global Interpreter Lock (GIL)](#the-global-interpreter-lock). PyO3 has a `Python<'py>` token that is used to prove that these conditions
are met. Its lifetime `'py` is a central part of PyO3's API.
The `Python<'py>` token serves three purposes:
* It provides global APIs for the Python interpreter, such as [`py.eval_bound()`][eval] and [`py.import_bound()`][import].
* It can be passed to functions that require a proof of holding the GIL, such as [`Py::clone_ref`][clone_ref].
* Its lifetime `'py` is used to bind many of PyO3's types to the Python interpreter, such as [`Bound<'py, T>`][Bound].
PyO3's types that are bound to the `'py` lifetime, for example `Bound<'py, T>`, all contain a `Python<'py>` token. This means they have full access to the Python interpreter and offer a complete API for interacting with Python objects.
Consult [PyO3's API documentation][obtaining-py] to learn how to acquire one of these tokens.
### The Global Interpreter Lock
Concurrent programming in Python is aided by the Global Interpreter Lock (GIL), which ensures that only one Python thread can use the Python interpreter and its API at the same time. This allows it to be used to synchronize code. See the [`pyo3::sync`] module for synchronization tools PyO3 offers that are based on the GIL's guarantees.
Non-Python operations (system calls and native Rust code) can unlock the GIL. See [the section on parallelism](parallelism.md) for how to do that using PyO3's API.
## Python's memory model
Python's memory model differs from Rust's memory model in two key ways:
- There is no concept of ownership; all Python objects are shared and usually implemented via reference counting
- There is no concept of exclusive (`&mut`) references; any reference can mutate a Python object
PyO3's API reflects this by providing [smart pointer][smart-pointers] types, `Py<T>`, `Bound<'py, T>`, and (the very rarely used) `Borrowed<'a, 'py, T>`. These smart pointers all use Python reference counting. See the [subchapter on types](./types.md) for more detail on these types.
Because of the lack of exclusive `&mut` references, PyO3's APIs for Python objects, for example [`PyListMethods::append`], use shared references. This is safe because Python objects have internal mechanisms to prevent data races (as of time of writing, the Python GIL).
[smart-pointers]: https://doc.rust-lang.org/book/ch15-00-smart-pointers.html
[obtaining-py]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#obtaining-a-python-token
[`pyo3::sync`]: {{#PYO3_DOCS_URL}}/pyo3/sync/index.html
[eval]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.eval
[import]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.import_bound
[clone_ref]: {{#PYO3_DOCS_URL}}/pyo3/prelude/struct.Py.html#method.clone_ref
[Bound]: {{#PYO3_DOCS_URL}}/pyo3/struct.Bound.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/ecosystem/logging.md | # Logging
It is desirable if both the Python and Rust parts of the application end up
logging using the same configuration into the same place.
This section of the guide briefly discusses how to connect the two languages'
logging ecosystems together. The recommended way for Python extension modules is
to configure Rust's logger to send log messages to Python using the `pyo3-log`
crate. For users who want to do the opposite and send Python log messages to
Rust, see the note at the end of this guide.
## Using `pyo3-log` to send Rust log messages to Python
The [pyo3-log] crate allows sending the messages from the Rust side to Python's
[logging] system. This is mostly suitable for writing native extensions for
Python programs.
Use [`pyo3_log::init`][init] to install the logger in its default configuration.
It's also possible to tweak its configuration (mostly to tune its performance).
```rust
use log::info;
use pyo3::prelude::*;
#[pyfunction]
fn log_something() {
// This will use the logger installed in `my_module` to send the `info`
// message to the Python logging facilities.
info!("Something!");
}
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
// A good place to install the Rust -> Python logger.
pyo3_log::init();
m.add_function(wrap_pyfunction!(log_something, m)?)?;
Ok(())
}
```
Then it is up to the Python side to actually output the messages somewhere.
```python
import logging
import my_module
FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(format=FORMAT)
logging.getLogger().setLevel(logging.INFO)
my_module.log_something()
```
It is important to initialize the Python loggers first, before calling any Rust
functions that may log. This limitation can be worked around if it is not
possible to satisfy, read the documentation about [caching].
## The Python to Rust direction
To have python logs be handled by Rust, one need only register a rust function to handle logs emitted from the core python logging module.
This has been implemented within the [pyo3-pylogger] crate.
```rust
use log::{info, warn};
use pyo3::prelude::*;
fn main() -> PyResult<()> {
// register the host handler with python logger, providing a logger target
// set the name here to something appropriate for your application
pyo3_pylogger::register("example_application_py_logger");
// initialize up a logger
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init();
// Log some messages from Rust.
info!("Just some normal information!");
warn!("Something spooky happened!");
// Log some messages from Python
Python::with_gil(|py| {
py.run(
"
import logging
logging.error('Something bad happened')
",
None,
None,
)
})
}
```
[logging]: https://docs.python.org/3/library/logging.html
[pyo3-log]: https://crates.io/crates/pyo3-log
[init]: https://docs.rs/pyo3-log/*/pyo3_log/fn.init.html
[caching]: https://docs.rs/pyo3-log/*/pyo3_log/#performance-filtering-and-caching
[pyo3-pylogger]: https://crates.io/crates/pyo3-pylogger
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/ecosystem/async-await.md | # Using `async` and `await`
*`async`/`await` support is currently being integrated in PyO3. See the [dedicated documentation](../async-await.md)*
If you are working with a Python library that makes use of async functions or wish to provide
Python bindings for an async Rust library, [`pyo3-asyncio`](https://github.com/awestlake87/pyo3-asyncio)
likely has the tools you need. It provides conversions between async functions in both Python and
Rust and was designed with first-class support for popular Rust runtimes such as
[`tokio`](https://tokio.rs/) and [`async-std`](https://async.rs/). In addition, all async Python
code runs on the default `asyncio` event loop, so `pyo3-asyncio` should work just fine with existing
Python libraries.
In the following sections, we'll give a general overview of `pyo3-asyncio` explaining how to call
async Python functions with PyO3, how to call async Rust functions from Python, and how to configure
your codebase to manage the runtimes of both.
## Quickstart
Here are some examples to get you started right away! A more detailed breakdown
of the concepts in these examples can be found in the following sections.
### Rust Applications
Here we initialize the runtime, import Python's `asyncio` library and run the given future to completion using Python's default `EventLoop` and `async-std`. Inside the future, we convert `asyncio` sleep into a Rust future and await it.
```toml
# Cargo.toml dependencies
[dependencies]
pyo3 = { version = "0.14" }
pyo3-asyncio = { version = "0.14", features = ["attributes", "async-std-runtime"] }
async-std = "1.9"
```
```rust
//! main.rs
use pyo3::prelude::*;
#[pyo3_asyncio::async_std::main]
async fn main() -> PyResult<()> {
let fut = Python::with_gil(|py| {
let asyncio = py.import("asyncio")?;
// convert asyncio.sleep into a Rust Future
pyo3_asyncio::async_std::into_future(asyncio.call_method1("sleep", (1.into_py(py),))?)
})?;
fut.await?;
Ok(())
}
```
The same application can be written to use `tokio` instead using the `#[pyo3_asyncio::tokio::main]`
attribute.
```toml
# Cargo.toml dependencies
[dependencies]
pyo3 = { version = "0.14" }
pyo3-asyncio = { version = "0.14", features = ["attributes", "tokio-runtime"] }
tokio = "1.4"
```
```rust
//! main.rs
use pyo3::prelude::*;
#[pyo3_asyncio::tokio::main]
async fn main() -> PyResult<()> {
let fut = Python::with_gil(|py| {
let asyncio = py.import("asyncio")?;
// convert asyncio.sleep into a Rust Future
pyo3_asyncio::tokio::into_future(asyncio.call_method1("sleep", (1.into_py(py),))?)
})?;
fut.await?;
Ok(())
}
```
More details on the usage of this library can be found in the [API docs](https://awestlake87.github.io/pyo3-asyncio/master/doc) and the primer below.
### PyO3 Native Rust Modules
PyO3 Asyncio can also be used to write native modules with async functions.
Add the `[lib]` section to `Cargo.toml` to make your library a `cdylib` that Python can import.
```toml
[lib]
name = "my_async_module"
crate-type = ["cdylib"]
```
Make your project depend on `pyo3` with the `extension-module` feature enabled and select your
`pyo3-asyncio` runtime:
For `async-std`:
```toml
[dependencies]
pyo3 = { version = "0.14", features = ["extension-module"] }
pyo3-asyncio = { version = "0.14", features = ["async-std-runtime"] }
async-std = "1.9"
```
For `tokio`:
```toml
[dependencies]
pyo3 = { version = "0.14", features = ["extension-module"] }
pyo3-asyncio = { version = "0.14", features = ["tokio-runtime"] }
tokio = "1.4"
```
Export an async function that makes use of `async-std`:
```rust
//! lib.rs
use pyo3::{prelude::*, wrap_pyfunction};
#[pyfunction]
fn rust_sleep(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> {
pyo3_asyncio::async_std::future_into_py(py, async {
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
Ok(Python::with_gil(|py| py.None()))
})
}
#[pymodule]
fn my_async_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(rust_sleep, m)?)
}
```
If you want to use `tokio` instead, here's what your module should look like:
```rust
//! lib.rs
use pyo3::{prelude::*, wrap_pyfunction};
#[pyfunction]
fn rust_sleep(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>>> {
pyo3_asyncio::tokio::future_into_py(py, async {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(Python::with_gil(|py| py.None()))
})
}
#[pymodule]
fn my_async_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(rust_sleep, m)?)
}
```
You can build your module with maturin (see the [Using Rust in Python](https://pyo3.rs/main/#using-rust-from-python) section in the PyO3 guide for setup instructions). After that you should be able to run the Python REPL to try it out.
```bash
maturin develop && python3
🔗 Found pyo3 bindings
🐍 Found CPython 3.8 at python3
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>>
>>> from my_async_module import rust_sleep
>>>
>>> async def main():
>>> await rust_sleep()
>>>
>>> # should sleep for 1s
>>> asyncio.run(main())
>>>
```
## Awaiting an Async Python Function in Rust
Let's take a look at a dead simple async Python function:
```python
# Sleep for 1 second
async def py_sleep():
await asyncio.sleep(1)
```
**Async functions in Python are simply functions that return a `coroutine` object**. For our purposes,
we really don't need to know much about these `coroutine` objects. The key factor here is that calling
an `async` function is _just like calling a regular function_, the only difference is that we have
to do something special with the object that it returns.
Normally in Python, that something special is the `await` keyword, but in order to await this
coroutine in Rust, we first need to convert it into Rust's version of a `coroutine`: a `Future`.
That's where `pyo3-asyncio` comes in.
[`pyo3_asyncio::async_std::into_future`](https://docs.rs/pyo3-asyncio/latest/pyo3_asyncio/async_std/fn.into_future.html)
performs this conversion for us.
The following example uses `into_future` to call the `py_sleep` function shown above and then await the
coroutine object returned from the call:
```rust
use pyo3::prelude::*;
#[pyo3_asyncio::tokio::main]
async fn main() -> PyResult<()> {
let future = Python::with_gil(|py| -> PyResult<_> {
// import the module containing the py_sleep function
let example = py.import("example")?;
// calling the py_sleep method like a normal function
// returns a coroutine
let coroutine = example.call_method0("py_sleep")?;
// convert the coroutine into a Rust future using the
// tokio runtime
pyo3_asyncio::tokio::into_future(coroutine)
})?;
// await the future
future.await?;
Ok(())
}
```
Alternatively, the below example shows how to write a `#[pyfunction]` which uses `into_future` to receive and await
a coroutine argument:
```rust
#[pyfunction]
fn await_coro(coro: &Bound<'_, PyAny>>) -> PyResult<()> {
// convert the coroutine into a Rust future using the
// async_std runtime
let f = pyo3_asyncio::async_std::into_future(coro)?;
pyo3_asyncio::async_std::run_until_complete(coro.py(), async move {
// await the future
f.await?;
Ok(())
})
}
```
This could be called from Python as:
```python
import asyncio
async def py_sleep():
asyncio.sleep(1)
await_coro(py_sleep())
```
If you wanted to pass a callable function to the `#[pyfunction]` instead, (i.e. the last line becomes `await_coro(py_sleep))`, then the above example needs to be tweaked to first call the callable to get the coroutine:
```rust
#[pyfunction]
fn await_coro(callable: &Bound<'_, PyAny>>) -> PyResult<()> {
// get the coroutine by calling the callable
let coro = callable.call0()?;
// convert the coroutine into a Rust future using the
// async_std runtime
let f = pyo3_asyncio::async_std::into_future(coro)?;
pyo3_asyncio::async_std::run_until_complete(coro.py(), async move {
// await the future
f.await?;
Ok(())
})
}
```
This can be particularly helpful where you need to repeatedly create and await a coroutine. Trying to await the same coroutine multiple times will raise an error:
```python
RuntimeError: cannot reuse already awaited coroutine
```
> If you're interested in learning more about `coroutines` and `awaitables` in general, check out the
> [Python 3 `asyncio` docs](https://docs.python.org/3/library/asyncio-task.html) for more information.
## Awaiting a Rust Future in Python
Here we have the same async function as before written in Rust using the
[`async-std`](https://async.rs/) runtime:
```rust
/// Sleep for 1 second
async fn rust_sleep() {
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
}
```
Similar to Python, Rust's async functions also return a special object called a
`Future`:
```rust
let future = rust_sleep();
```
We can convert this `Future` object into Python to make it `awaitable`. This tells Python that you
can use the `await` keyword with it. In order to do this, we'll call
[`pyo3_asyncio::async_std::future_into_py`](https://docs.rs/pyo3-asyncio/latest/pyo3_asyncio/async_std/fn.future_into_py.html):
```rust
use pyo3::prelude::*;
async fn rust_sleep() {
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
}
#[pyfunction]
fn call_rust_sleep(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>>> {
pyo3_asyncio::async_std::future_into_py(py, async move {
rust_sleep().await;
Ok(Python::with_gil(|py| py.None()))
})
}
```
In Python, we can call this pyo3 function just like any other async function:
```python
from example import call_rust_sleep
async def rust_sleep():
await call_rust_sleep()
```
## Managing Event Loops
Python's event loop requires some special treatment, especially regarding the main thread. Some of
Python's `asyncio` features, like proper signal handling, require control over the main thread, which
doesn't always play well with Rust.
Luckily, Rust's event loops are pretty flexible and don't _need_ control over the main thread, so in
`pyo3-asyncio`, we decided the best way to handle Rust/Python interop was to just surrender the main
thread to Python and run Rust's event loops in the background. Unfortunately, since most event loop
implementations _prefer_ control over the main thread, this can still make some things awkward.
### PyO3 Asyncio Initialization
Because Python needs to control the main thread, we can't use the convenient proc macros from Rust
runtimes to handle the `main` function or `#[test]` functions. Instead, the initialization for PyO3 has to be done from the `main` function and the main
thread must block on [`pyo3_asyncio::async_std::run_until_complete`](https://docs.rs/pyo3-asyncio/latest/pyo3_asyncio/async_std/fn.run_until_complete.html).
Because we have to block on one of those functions, we can't use [`#[async_std::main]`](https://docs.rs/async-std/latest/async_std/attr.main.html) or [`#[tokio::main]`](https://docs.rs/tokio/1.1.0/tokio/attr.main.html)
since it's not a good idea to make long blocking calls during an async function.
> Internally, these `#[main]` proc macros are expanded to something like this:
> ```rust
> fn main() {
> // your async main fn
> async fn _main_impl() { /* ... */ }
> Runtime::new().block_on(_main_impl());
> }
> ```
> Making a long blocking call inside the `Future` that's being driven by `block_on` prevents that
> thread from doing anything else and can spell trouble for some runtimes (also this will actually
> deadlock a single-threaded runtime!). Many runtimes have some sort of `spawn_blocking` mechanism
> that can avoid this problem, but again that's not something we can use here since we need it to
> block on the _main_ thread.
For this reason, `pyo3-asyncio` provides its own set of proc macros to provide you with this
initialization. These macros are intended to mirror the initialization of `async-std` and `tokio`
while also satisfying the Python runtime's needs.
Here's a full example of PyO3 initialization with the `async-std` runtime:
```rust
use pyo3::prelude::*;
#[pyo3_asyncio::async_std::main]
async fn main() -> PyResult<()> {
// PyO3 is initialized - Ready to go
let fut = Python::with_gil(|py| -> PyResult<_> {
let asyncio = py.import("asyncio")?;
// convert asyncio.sleep into a Rust Future
pyo3_asyncio::async_std::into_future(
asyncio.call_method1("sleep", (1.into_py(py),))?
)
})?;
fut.await?;
Ok(())
}
```
### A Note About `asyncio.run`
In Python 3.7+, the recommended way to run a top-level coroutine with `asyncio`
is with `asyncio.run`. In `v0.13` we recommended against using this function due to initialization issues, but in `v0.14` it's perfectly valid to use this function... with a caveat.
Since our Rust <--> Python conversions require a reference to the Python event loop, this poses a problem. Imagine we have a PyO3 Asyncio module that defines
a `rust_sleep` function like in previous examples. You might rightfully assume that you can call pass this directly into `asyncio.run` like this:
```python
import asyncio
from my_async_module import rust_sleep
asyncio.run(rust_sleep())
```
You might be surprised to find out that this throws an error:
```bash
Traceback (most recent call last):
File "example.py", line 5, in <module>
asyncio.run(rust_sleep())
RuntimeError: no running event loop
```
What's happening here is that we are calling `rust_sleep` _before_ the future is
actually running on the event loop created by `asyncio.run`. This is counter-intuitive, but expected behaviour, and unfortunately there doesn't seem to be a good way of solving this problem within PyO3 Asyncio itself.
However, we can make this example work with a simple workaround:
```python
import asyncio
from my_async_module import rust_sleep
# Calling main will just construct the coroutine that later calls rust_sleep.
# - This ensures that rust_sleep will be called when the event loop is running,
# not before.
async def main():
await rust_sleep()
# Run the main() coroutine at the top-level instead
asyncio.run(main())
```
### Non-standard Python Event Loops
Python allows you to use alternatives to the default `asyncio` event loop. One
popular alternative is `uvloop`. In `v0.13` using non-standard event loops was
a bit of an ordeal, but in `v0.14` it's trivial.
#### Using `uvloop` in a PyO3 Asyncio Native Extensions
```toml
# Cargo.toml
[lib]
name = "my_async_module"
crate-type = ["cdylib"]
[dependencies]
pyo3 = { version = "0.14", features = ["extension-module"] }
pyo3-asyncio = { version = "0.14", features = ["tokio-runtime"] }
async-std = "1.9"
tokio = "1.4"
```
```rust
//! lib.rs
use pyo3::{prelude::*, wrap_pyfunction};
#[pyfunction]
fn rust_sleep(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>>> {
pyo3_asyncio::tokio::future_into_py(py, async {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(Python::with_gil(|py| py.None()))
})
}
#[pymodule]
fn my_async_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(rust_sleep, m)?)?;
Ok(())
}
```
```bash
$ maturin develop && python3
🔗 Found pyo3 bindings
🐍 Found CPython 3.8 at python3
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
Python 3.8.8 (default, Apr 13 2021, 19:58:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> import uvloop
>>>
>>> import my_async_module
>>>
>>> uvloop.install()
>>>
>>> async def main():
... await my_async_module.rust_sleep()
...
>>> asyncio.run(main())
>>>
```
#### Using `uvloop` in Rust Applications
Using `uvloop` in Rust applications is a bit trickier, but it's still possible
with relatively few modifications.
Unfortunately, we can't make use of the `#[pyo3_asyncio::<runtime>::main]` attribute with non-standard event loops. This is because the `#[pyo3_asyncio::<runtime>::main]` proc macro has to interact with the Python
event loop before we can install the `uvloop` policy.
```toml
[dependencies]
async-std = "1.9"
pyo3 = "0.14"
pyo3-asyncio = { version = "0.14", features = ["async-std-runtime"] }
```
```rust
//! main.rs
use pyo3::{prelude::*, types::PyType};
fn main() -> PyResult<()> {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let uvloop = py.import("uvloop")?;
uvloop.call_method0("install")?;
// store a reference for the assertion
let uvloop = PyObject::from(uvloop);
pyo3_asyncio::async_std::run(py, async move {
// verify that we are on a uvloop.Loop
Python::with_gil(|py| -> PyResult<()> {
assert!(pyo3_asyncio::async_std::get_current_loop(py)?.is_instance(
uvloop
.as_ref(py)
.getattr("Loop")?
)?);
Ok(())
})?;
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
Ok(())
})
})
}
```
## Additional Information
- Managing event loop references can be tricky with pyo3-asyncio. See [Event Loop References](https://docs.rs/pyo3-asyncio/#event-loop-references) in the API docs to get a better intuition for how event loop references are managed in this library.
- Testing pyo3-asyncio libraries and applications requires a custom test harness since Python requires control over the main thread. You can find a testing guide in the [API docs for the `testing` module](https://docs.rs/pyo3-asyncio/latest/pyo3_asyncio/testing)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/function/error-handling.md | # Error handling
This chapter contains a little background of error handling in Rust and how PyO3 integrates this with Python exceptions.
This covers enough detail to create a `#[pyfunction]` which raises Python exceptions from errors originating in Rust.
There is a later section of the guide on [Python exceptions](../exception.md) which covers exception types in more detail.
## Representing Python exceptions
Rust code uses the generic [`Result<T, E>`] enum to propagate errors. The error type `E` is chosen by the code author to describe the possible errors which can happen.
PyO3 has the [`PyErr`] type which represents a Python exception. If a PyO3 API could result in a Python exception being raised, the return type of that `API` will be [`PyResult<T>`], which is an alias for the type `Result<T, PyErr>`.
In summary:
- When Python exceptions are raised and caught by PyO3, the exception will be stored in the `Err` variant of the `PyResult`.
- Passing Python exceptions through Rust code then uses all the "normal" techniques such as the `?` operator, with `PyErr` as the error type.
- Finally, when a `PyResult` crosses from Rust back to Python via PyO3, if the result is an `Err` variant the contained exception will be raised.
(There are many great tutorials on Rust error handling and the `?` operator, so this guide will not go into detail on Rust-specific topics.)
## Raising an exception from a function
As indicated in the previous section, when a `PyResult` containing an `Err` crosses from Rust to Python, PyO3 will raise the exception contained within.
Accordingly, to raise an exception from a `#[pyfunction]`, change the return type `T` to `PyResult<T>`. When the function returns an `Err` it will raise a Python exception. (Other `Result<T, E>` types can be used as long as the error `E` has a `From` conversion for `PyErr`, see [custom Rust error types](#custom-rust-error-types) below.)
This also works for functions in `#[pymethods]`.
For example, the following `check_positive` function raises a `ValueError` when the input is negative:
```rust
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
#[pyfunction]
fn check_positive(x: i32) -> PyResult<()> {
if x < 0 {
Err(PyValueError::new_err("x is negative"))
} else {
Ok(())
}
}
#
# fn main(){
# Python::with_gil(|py|{
# let fun = pyo3::wrap_pyfunction!(check_positive, py).unwrap();
# fun.call1((-1,)).unwrap_err();
# fun.call1((1,)).unwrap();
# });
# }
```
All built-in Python exception types are defined in the [`pyo3::exceptions`] module. They have a `new_err` constructor to directly build a `PyErr`, as seen in the example above.
## Custom Rust error types
PyO3 will automatically convert a `Result<T, E>` returned by a `#[pyfunction]` into a `PyResult<T>` as long as there is an implementation of `std::from::From<E> for PyErr`. Many error types in the Rust standard library have a [`From`] conversion defined in this way.
If the type `E` you are handling is defined in a third-party crate, see the section on [foreign rust error types](#foreign-rust-error-types) below for ways to work with this error.
The following example makes use of the implementation of `From<ParseIntError> for PyErr` to raise exceptions encountered when parsing strings as integers:
```rust
# use pyo3::prelude::*;
use std::num::ParseIntError;
#[pyfunction]
fn parse_int(x: &str) -> Result<usize, ParseIntError> {
x.parse()
}
# fn main() {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(parse_int, py).unwrap();
# let value: usize = fun.call1(("5",)).unwrap().extract().unwrap();
# assert_eq!(value, 5);
# });
# }
```
When passed a string which doesn't contain a floating-point number, the exception raised will look like the below:
```python
>>> parse_int("bar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid digit found in string
```
As a more complete example, the following snippet defines a Rust error named `CustomIOError`. It then defines a `From<CustomIOError> for PyErr`, which returns a `PyErr` representing Python's `OSError`.
Therefore, it can use this error in the result of a `#[pyfunction]` directly, relying on the conversion if it has to be propagated into a Python exception.
```rust
use pyo3::exceptions::PyOSError;
use pyo3::prelude::*;
use std::fmt;
#[derive(Debug)]
struct CustomIOError;
impl std::error::Error for CustomIOError {}
impl fmt::Display for CustomIOError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Oh no!")
}
}
impl std::convert::From<CustomIOError> for PyErr {
fn from(err: CustomIOError) -> PyErr {
PyOSError::new_err(err.to_string())
}
}
pub struct Connection {/* ... */}
fn bind(addr: String) -> Result<Connection, CustomIOError> {
if &addr == "0.0.0.0" {
Err(CustomIOError)
} else {
Ok(Connection{ /* ... */})
}
}
#[pyfunction]
fn connect(s: String) -> Result<(), CustomIOError> {
bind(s)?;
// etc.
Ok(())
}
fn main() {
Python::with_gil(|py| {
let fun = pyo3::wrap_pyfunction!(connect, py).unwrap();
let err = fun.call1(("0.0.0.0",)).unwrap_err();
assert!(err.is_instance_of::<PyOSError>(py));
});
}
```
If lazy construction of the Python exception instance is desired, the
[`PyErrArguments`]({{#PYO3_DOCS_URL}}/pyo3/trait.PyErrArguments.html)
trait can be implemented instead of `From`. In that case, actual exception argument creation is delayed
until the `PyErr` is needed.
A final note is that any errors `E` which have a `From` conversion can be used with the `?`
("try") operator with them. An alternative implementation of the above `parse_int` which instead returns `PyResult` is below:
```rust
use pyo3::prelude::*;
fn parse_int(s: String) -> PyResult<usize> {
let x = s.parse()?;
Ok(x)
}
#
# use pyo3::exceptions::PyValueError;
#
# fn main() {
# Python::with_gil(|py| {
# assert_eq!(parse_int(String::from("1")).unwrap(), 1);
# assert_eq!(parse_int(String::from("1337")).unwrap(), 1337);
#
# assert!(parse_int(String::from("-1"))
# .unwrap_err()
# .is_instance_of::<PyValueError>(py));
# assert!(parse_int(String::from("foo"))
# .unwrap_err()
# .is_instance_of::<PyValueError>(py));
# assert!(parse_int(String::from("13.37"))
# .unwrap_err()
# .is_instance_of::<PyValueError>(py));
# })
# }
```
## Foreign Rust error types
The Rust compiler will not permit implementation of traits for types outside of the crate where the type is defined. (This is known as the "orphan rule".)
Given a type `OtherError` which is defined in third-party code, there are two main strategies available to integrate it with PyO3:
- Create a newtype wrapper, e.g. `MyOtherError`. Then implement `From<MyOtherError> for PyErr` (or `PyErrArguments`), as well as `From<OtherError>` for `MyOtherError`.
- Use Rust's Result combinators such as `map_err` to write code freely to convert `OtherError` into whatever is needed. This requires boilerplate at every usage however gives unlimited flexibility.
To detail the newtype strategy a little further, the key trick is to return `Result<T, MyOtherError>` from the `#[pyfunction]`. This means that PyO3 will make use of `From<MyOtherError> for PyErr` to create Python exceptions while the `#[pyfunction]` implementation can use `?` to convert `OtherError` to `MyOtherError` automatically.
The following example demonstrates this for some imaginary third-party crate `some_crate` with a function `get_x` returning `Result<i32, OtherError>`:
```rust
# mod some_crate {
# pub struct OtherError(());
# impl OtherError {
# pub fn message(&self) -> &'static str { "some error occurred" }
# }
# pub fn get_x() -> Result<i32, OtherError> { Ok(5) }
# }
use pyo3::prelude::*;
use pyo3::exceptions::PyValueError;
use some_crate::{OtherError, get_x};
struct MyOtherError(OtherError);
impl From<MyOtherError> for PyErr {
fn from(error: MyOtherError) -> Self {
PyValueError::new_err(error.0.message())
}
}
impl From<OtherError> for MyOtherError {
fn from(other: OtherError) -> Self {
Self(other)
}
}
#[pyfunction]
fn wrapped_get_x() -> Result<i32, MyOtherError> {
// get_x is a function returning Result<i32, OtherError>
let x: i32 = get_x()?;
Ok(x)
}
# fn main() {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(wrapped_get_x, py).unwrap();
# let value: usize = fun.call0().unwrap().extract().unwrap();
# assert_eq!(value, 5);
# });
# }
```
[`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html
[`Result<T, E>`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html
[`PyResult<T>`]: {{#PYO3_DOCS_URL}}/pyo3/prelude/type.PyResult.html
[`PyErr`]: {{#PYO3_DOCS_URL}}/pyo3/struct.PyErr.html
[`pyo3::exceptions`]: {{#PYO3_DOCS_URL}}/pyo3/exceptions/index.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/function/signature.md | # Function signatures
The `#[pyfunction]` attribute also accepts parameters to control how the generated Python function accepts arguments. Just like in Python, arguments can be positional-only, keyword-only, or accept either. `*args` lists and `**kwargs` dicts can also be accepted. These parameters also work for `#[pymethods]` which will be introduced in the [Python Classes](../class.md) section of the guide.
Like Python, by default PyO3 accepts all arguments as either positional or keyword arguments. Most arguments are required by default, except for trailing `Option<_>` arguments, which are [implicitly given a default of `None`](#trailing-optional-arguments). This behaviour can be configured by the `#[pyo3(signature = (...))]` option which allows writing a signature in Python syntax.
This section of the guide goes into detail about use of the `#[pyo3(signature = (...))]` option and its related option `#[pyo3(text_signature = "...")]`
## Using `#[pyo3(signature = (...))]`
For example, below is a function that accepts arbitrary keyword arguments (`**kwargs` in Python syntax) and returns the number that was passed:
```rust
use pyo3::prelude::*;
use pyo3::types::PyDict;
#[pyfunction]
#[pyo3(signature = (**kwds))]
fn num_kwds(kwds: Option<&Bound<'_, PyDict>>) -> usize {
kwds.map_or(0, |dict| dict.len())
}
#[pymodule]
fn module_with_functions(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(num_kwds, m)?)
}
```
Just like in Python, the following constructs can be part of the signature::
* `/`: positional-only arguments separator, each parameter defined before `/` is a positional-only parameter.
* `*`: var arguments separator, each parameter defined after `*` is a keyword-only parameter.
* `*args`: "args" is var args. Type of the `args` parameter has to be `&Bound<'_, PyTuple>`.
* `**kwargs`: "kwargs" receives keyword arguments. The type of the `kwargs` parameter has to be `Option<&Bound<'_, PyDict>>`.
* `arg=Value`: arguments with default value.
If the `arg` argument is defined after var arguments, it is treated as a keyword-only argument.
Note that `Value` has to be valid rust code, PyO3 just inserts it into the generated
code unmodified.
Example:
```rust
# use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
#
# #[pyclass]
# struct MyClass {
# num: i32,
# }
#[pymethods]
impl MyClass {
#[new]
#[pyo3(signature = (num=-1))]
fn new(num: i32) -> Self {
MyClass { num }
}
#[pyo3(signature = (num=10, *py_args, name="Hello", **py_kwargs))]
fn method(
&mut self,
num: i32,
py_args: &Bound<'_, PyTuple>,
name: &str,
py_kwargs: Option<&Bound<'_, PyDict>>,
) -> String {
let num_before = self.num;
self.num = num;
format!(
"num={} (was previously={}), py_args={:?}, name={}, py_kwargs={:?} ",
num, num_before, py_args, name, py_kwargs,
)
}
fn make_change(&mut self, num: i32) -> PyResult<String> {
self.num = num;
Ok(format!("num={}", self.num))
}
}
```
Arguments of type `Python` must not be part of the signature:
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
#[pyfunction]
#[pyo3(signature = (lambda))]
pub fn simple_python_bound_function(py: Python<'_>, lambda: PyObject) -> PyResult<()> {
Ok(())
}
```
N.B. the position of the `/` and `*` arguments (if included) control the system of handling positional and keyword arguments. In Python:
```python
import mymodule
mc = mymodule.MyClass()
print(mc.method(44, False, "World", 666, x=44, y=55))
print(mc.method(num=-1, name="World"))
print(mc.make_change(44, False))
```
Produces output:
```text
py_args=('World', 666), py_kwargs=Some({'x': 44, 'y': 55}), name=Hello, num=44
py_args=(), py_kwargs=None, name=World, num=-1
num=44
num=-1
```
> Note: to use keywords like `struct` as a function argument, use "raw identifier" syntax `r#struct` in both the signature and the function definition:
>
> ```rust
> # #![allow(dead_code)]
> # use pyo3::prelude::*;
> #[pyfunction(signature = (r#struct = "foo"))]
> fn function_with_keyword(r#struct: &str) {
> # let _ = r#struct;
> /* ... */
> }
> ```
## Trailing optional arguments
<div class="warning">
⚠️ Warning: This behaviour is being phased out 🛠️
The special casing of trailing optional arguments is deprecated. In a future `pyo3` version, arguments of type `Option<..>` will share the same behaviour as other arguments, they are required unless a default is set using `#[pyo3(signature = (...))]`.
This is done to better align the Python and Rust definition of such functions and make it more intuitive to rewrite them from Python in Rust. Specifically `def some_fn(a: int, b: Optional[int]): ...` will not automatically default `b` to `none`, but requires an explicit default if desired, where as in current `pyo3` it is handled the other way around.
During the migration window a `#[pyo3(signature = (...))]` will be required to silence the deprecation warning. After support for trailing optional arguments is fully removed, the signature attribute can be removed if all arguments should be required.
</div>
As a convenience, functions without a `#[pyo3(signature = (...))]` option will treat trailing `Option<T>` arguments as having a default of `None`. In the example below, PyO3 will create `increment` with a signature of `increment(x, amount=None)`.
```rust
#![allow(deprecated)]
use pyo3::prelude::*;
/// Returns a copy of `x` increased by `amount`.
///
/// If `amount` is unspecified or `None`, equivalent to `x + 1`.
#[pyfunction]
fn increment(x: u64, amount: Option<u64>) -> u64 {
x + amount.unwrap_or(1)
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(increment, py)?;
#
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
# .extract()?;
#
# #[cfg(Py_3_8)] // on 3.7 the signature doesn't render b, upstream bug?
# assert_eq!(sig, "(x, amount=None)");
#
# Ok(())
# })
# }
```
To make trailing `Option<T>` arguments required, but still accept `None`, add a `#[pyo3(signature = (...))]` annotation. For the example above, this would be `#[pyo3(signature = (x, amount))]`:
```rust
# use pyo3::prelude::*;
#[pyfunction]
#[pyo3(signature = (x, amount))]
fn increment(x: u64, amount: Option<u64>) -> u64 {
x + amount.unwrap_or(1)
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(increment, py)?;
#
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
# .extract()?;
#
# #[cfg(Py_3_8)] // on 3.7 the signature doesn't render b, upstream bug?
# assert_eq!(sig, "(x, amount)");
#
# Ok(())
# })
# }
```
To help avoid confusion, PyO3 requires `#[pyo3(signature = (...))]` when an `Option<T>` argument is surrounded by arguments which aren't `Option<T>`.
## Making the function signature available to Python
The function signature is exposed to Python via the `__text_signature__` attribute. PyO3 automatically generates this for every `#[pyfunction]` and all `#[pymethods]` directly from the Rust function, taking into account any override done with the `#[pyo3(signature = (...))]` option.
This automatic generation can only display the value of default arguments for strings, integers, boolean types, and `None`. Any other default arguments will be displayed as `...`. (`.pyi` type stub files commonly also use `...` for default arguments in the same way.)
In cases where the automatically-generated signature needs adjusting, it can [be overridden](#overriding-the-generated-signature) using the `#[pyo3(text_signature)]` option.)
The example below creates a function `add` which accepts two positional-only arguments `a` and `b`, where `b` has a default value of zero.
```rust
use pyo3::prelude::*;
/// This function adds two unsigned 64-bit integers.
#[pyfunction]
#[pyo3(signature = (a, b=0, /))]
fn add(a: u64, b: u64) -> u64 {
a + b
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(add, py)?;
#
# let doc: String = fun.getattr("__doc__")?.extract()?;
# assert_eq!(doc, "This function adds two unsigned 64-bit integers.");
#
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
# .extract()?;
#
# #[cfg(Py_3_8)] // on 3.7 the signature doesn't render b, upstream bug?
# assert_eq!(sig, "(a, b=0, /)");
#
# Ok(())
# })
# }
```
The following IPython output demonstrates how this generated signature will be seen from Python tooling:
```text
>>> pyo3_test.add.__text_signature__
'(a, b=..., /)'
>>> pyo3_test.add?
Signature: pyo3_test.add(a, b=0, /)
Docstring: This function adds two unsigned 64-bit integers.
Type: builtin_function_or_method
```
### Overriding the generated signature
The `#[pyo3(text_signature = "(<some signature>)")]` attribute can be used to override the default generated signature.
In the snippet below, the text signature attribute is used to include the default value of `0` for the argument `b`, instead of the automatically-generated default value of `...`:
```rust
use pyo3::prelude::*;
/// This function adds two unsigned 64-bit integers.
#[pyfunction]
#[pyo3(signature = (a, b=0, /), text_signature = "(a, b=0, /)")]
fn add(a: u64, b: u64) -> u64 {
a + b
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(add, py)?;
#
# let doc: String = fun.getattr("__doc__")?.extract()?;
# assert_eq!(doc, "This function adds two unsigned 64-bit integers.");
#
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
# .extract()?;
# assert_eq!(sig, "(a, b=0, /)");
#
# Ok(())
# })
# }
```
PyO3 will include the contents of the annotation unmodified as the `__text_signature__`. Below shows how IPython will now present this (see the default value of 0 for b):
```text
>>> pyo3_test.add.__text_signature__
'(a, b=0, /)'
>>> pyo3_test.add?
Signature: pyo3_test.add(a, b=0, /)
Docstring: This function adds two unsigned 64-bit integers.
Type: builtin_function_or_method
```
If no signature is wanted at all, `#[pyo3(text_signature = None)]` will disable the built-in signature. The snippet below demonstrates use of this:
```rust
use pyo3::prelude::*;
/// This function adds two unsigned 64-bit integers.
#[pyfunction]
#[pyo3(signature = (a, b=0, /), text_signature = None)]
fn add(a: u64, b: u64) -> u64 {
a + b
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(add, py)?;
#
# let doc: String = fun.getattr("__doc__")?.extract()?;
# assert_eq!(doc, "This function adds two unsigned 64-bit integers.");
# assert!(fun.getattr("__text_signature__")?.is_none());
#
# Ok(())
# })
# }
```
Now the function's `__text_signature__` will be set to `None`, and IPython will not display any signature in the help:
```text
>>> pyo3_test.add.__text_signature__ == None
True
>>> pyo3_test.add?
Docstring: This function adds two unsigned 64-bit integers.
Type: builtin_function_or_method
```
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/building-and-distribution/multiple-python-versions.md | # Supporting multiple Python versions
PyO3 supports all actively-supported Python 3 and PyPy versions. As much as possible, this is done internally to PyO3 so that your crate's code does not need to adapt to the differences between each version. However, as Python features grow and change between versions, PyO3 cannot offer a completely identical API for every Python version. This may require you to add conditional compilation to your crate or runtime checks for the Python version.
This section of the guide first introduces the `pyo3-build-config` crate, which you can use as a `build-dependency` to add additional `#[cfg]` flags which allow you to support multiple Python versions at compile-time.
Second, we'll show how to check the Python version at runtime. This can be useful when building for multiple versions with the `abi3` feature, where the Python API compiled against is not always the same as the one in use.
## Conditional compilation for different Python versions
The `pyo3-build-config` exposes multiple [`#[cfg]` flags](https://doc.rust-lang.org/rust-by-example/attribute/cfg.html) which can be used to conditionally compile code for a given Python version. PyO3 itself depends on this crate, so by using it you can be sure that you are configured correctly for the Python version PyO3 is building against.
This allows us to write code like the following
```rust,ignore
#[cfg(Py_3_7)]
fn function_only_supported_on_python_3_7_and_up() {}
#[cfg(not(Py_3_8))]
fn function_only_supported_before_python_3_8() {}
#[cfg(not(Py_LIMITED_API))]
fn function_incompatible_with_abi3_feature() {}
```
The following sections first show how to add these `#[cfg]` flags to your build process, and then cover some common patterns flags in a little more detail.
To see a full reference of all the `#[cfg]` flags provided, see the [`pyo3-build-cfg` docs](https://docs.rs/pyo3-build-config).
### Using `pyo3-build-config`
You can use the `#[cfg]` flags in just two steps:
1. Add `pyo3-build-config` with the [`resolve-config`](../features.md#resolve-config) feature enabled to your crate's build dependencies in `Cargo.toml`:
```toml
[build-dependencies]
pyo3-build-config = { {{#PYO3_CRATE_VERSION}}, features = ["resolve-config"] }
```
2. Add a [`build.rs`](https://doc.rust-lang.org/cargo/reference/build-scripts.html) file to your crate with the following contents:
```rust,ignore
fn main() {
// If you have an existing build.rs file, just add this line to it.
pyo3_build_config::use_pyo3_cfgs();
}
```
After these steps you are ready to annotate your code!
### Common usages of `pyo3-build-cfg` flags
The `#[cfg]` flags added by `pyo3-build-cfg` can be combined with all of Rust's logic in the `#[cfg]` attribute to create very precise conditional code generation. The following are some common patterns implemented using these flags:
```text
#[cfg(Py_3_7)]
```
This `#[cfg]` marks code that will only be present on Python 3.7 and upwards. There are similar options `Py_3_8`, `Py_3_9`, `Py_3_10` and so on for each minor version.
```text
#[cfg(not(Py_3_7))]
```
This `#[cfg]` marks code that will only be present on Python versions before (but not including) Python 3.7.
```text
#[cfg(not(Py_LIMITED_API))]
```
This `#[cfg]` marks code that is only available when building for the unlimited Python API (i.e. PyO3's `abi3` feature is not enabled). This might be useful if you want to ship your extension module as an `abi3` wheel and also allow users to compile it from source to make use of optimizations only possible with the unlimited API.
```text
#[cfg(any(Py_3_9, not(Py_LIMITED_API)))]
```
This `#[cfg]` marks code which is available when running Python 3.9 or newer, or when using the unlimited API with an older Python version. Patterns like this are commonly seen on Python APIs which were added to the limited Python API in a specific minor version.
```text
#[cfg(PyPy)]
```
This `#[cfg]` marks code which is running on PyPy.
## Checking the Python version at runtime
When building with PyO3's `abi3` feature, your extension module will be compiled against a specific [minimum version](../building-and-distribution.md#minimum-python-version-for-abi3) of Python, but may be running on newer Python versions.
For example with PyO3's `abi3-py38` feature, your extension will be compiled as if it were for Python 3.8. If you were using `pyo3-build-config`, `#[cfg(Py_3_8)]` would be present. Your user could freely install and run your abi3 extension on Python 3.9.
There's no way to detect your user doing that at compile time, so instead you need to fall back to runtime checks.
PyO3 provides the APIs [`Python::version()`] and [`Python::version_info()`] to query the running Python version. This allows you to do the following, for example:
```rust
use pyo3::Python;
Python::with_gil(|py| {
// PyO3 supports Python 3.7 and up.
assert!(py.version_info() >= (3, 7));
assert!(py.version_info() >= (3, 7, 0));
});
```
[`Python::version()`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.version
[`Python::version_info()`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.version_info
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/class/protocols.md | # Class customizations
Python's object model defines several protocols for different object behavior, such as the sequence, mapping, and number protocols. Python classes support these protocols by implementing "magic" methods, such as `__str__` or `__repr__`. Because of the double-underscores surrounding their name, these are also known as "dunder" methods.
PyO3 makes it possible for every magic method to be implemented in `#[pymethods]` just as they would be done in a regular Python class, with a few notable differences:
- `__new__` and `__init__` are replaced by the [`#[new]` attribute](../class.md#constructor).
- `__del__` is not yet supported, but may be in the future.
- `__buffer__` and `__release_buffer__` are currently not supported and instead PyO3 supports [`__getbuffer__` and `__releasebuffer__`](#buffer-objects) methods (these predate [PEP 688](https://peps.python.org/pep-0688/#python-level-buffer-protocol)), again this may change in the future.
- PyO3 adds [`__traverse__` and `__clear__`](#garbage-collector-integration) methods for controlling garbage collection.
- The Python C-API which PyO3 is implemented upon requires many magic methods to have a specific function signature in C and be placed into special "slots" on the class type object. This limits the allowed argument and return types for these methods. They are listed in detail in the section below.
If a magic method is not on the list above (for example `__init_subclass__`), then it should just work in PyO3. If this is not the case, please file a bug report.
## Magic Methods handled by PyO3
If a function name in `#[pymethods]` is a magic method which is known to need special handling, it will be automatically placed into the correct slot in the Python type object. The function name is taken from the usual rules for naming `#[pymethods]`: the `#[pyo3(name = "...")]` attribute is used if present, otherwise the Rust function name is used.
The magic methods handled by PyO3 are very similar to the standard Python ones on [this page](https://docs.python.org/3/reference/datamodel.html#special-method-names) - in particular they are the subset which have slots as [defined here](https://docs.python.org/3/c-api/typeobj.html).
When PyO3 handles a magic method, a couple of changes apply compared to other `#[pymethods]`:
- The Rust function signature is restricted to match the magic method.
- The `#[pyo3(signature = (...)]` and `#[pyo3(text_signature = "...")]` attributes are not allowed.
The following sections list all magic methods for which PyO3 implements the necessary special handling. The
given signatures should be interpreted as follows:
- All methods take a receiver as first argument, shown as `<self>`. It can be
`&self`, `&mut self` or a `Bound` reference like `self_: PyRef<'_, Self>` and
`self_: PyRefMut<'_, Self>`, as described [here](../class.md#inheritance).
- An optional `Python<'py>` argument is always allowed as the first argument.
- Return values can be optionally wrapped in `PyResult`.
- `object` means that any type is allowed that can be extracted from a Python
object (if argument) or converted to a Python object (if return value).
- Other types must match what's given, e.g. `pyo3::basic::CompareOp` for
`__richcmp__`'s second argument.
- For the comparison and arithmetic methods, extraction errors are not
propagated as exceptions, but lead to a return of `NotImplemented`.
- For some magic methods, the return values are not restricted by PyO3, but
checked by the Python interpreter. For example, `__str__` needs to return a
string object. This is indicated by `object (Python type)`.
### Basic object customization
- `__str__(<self>) -> object (str)`
- `__repr__(<self>) -> object (str)`
- `__hash__(<self>) -> isize`
Objects that compare equal must have the same hash value. Any type up to 64 bits may be returned instead of `isize`, PyO3 will convert to an isize automatically (wrapping unsigned types like `u64` and `usize`).
<details>
<summary>Disabling Python's default hash</summary>
By default, all `#[pyclass]` types have a default hash implementation from Python. Types which should not be hashable can override this by setting `__hash__` to `None`. This is the same mechanism as for a pure-Python class. This is done like so:
```rust
# use pyo3::prelude::*;
#
#[pyclass]
struct NotHashable {}
#[pymethods]
impl NotHashable {
#[classattr]
const __hash__: Option<PyObject> = None;
}
```
</details>
- `__lt__(<self>, object) -> object`
- `__le__(<self>, object) -> object`
- `__eq__(<self>, object) -> object`
- `__ne__(<self>, object) -> object`
- `__gt__(<self>, object) -> object`
- `__ge__(<self>, object) -> object`
The implementations of Python's "rich comparison" operators `<`, `<=`, `==`, `!=`, `>` and `>=` respectively.
_Note that implementing any of these methods will cause Python not to generate a default `__hash__` implementation, so consider also implementing `__hash__`._
<details>
<summary>Return type</summary>
The return type will normally be `bool` or `PyResult<bool>`, however any Python object can be returned.
</details>
- `__richcmp__(<self>, object, pyo3::basic::CompareOp) -> object`
Implements Python comparison operations (`==`, `!=`, `<`, `<=`, `>`, and `>=`) in a single method.
The `CompareOp` argument indicates the comparison operation being performed. You can use
[`CompareOp::matches`] to adapt a Rust `std::cmp::Ordering` result to the requested comparison.
_This method cannot be implemented in combination with any of `__lt__`, `__le__`, `__eq__`, `__ne__`, `__gt__`, or `__ge__`._
_Note that implementing `__richcmp__` will cause Python not to generate a default `__hash__` implementation, so consider implementing `__hash__` when implementing `__richcmp__`._
<details>
<summary>Return type</summary>
The return type will normally be `PyResult<bool>`, but any Python object can be returned.
If you want to leave some operations unimplemented, you can return `py.NotImplemented()`
for some of the operations:
```rust
use pyo3::class::basic::CompareOp;
use pyo3::types::PyNotImplemented;
# use pyo3::prelude::*;
# use pyo3::BoundObject;
#
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __richcmp__<'py>(&self, other: &Self, op: CompareOp, py: Python<'py>) -> PyResult<Borrowed<'py, 'py, PyAny>> {
match op {
CompareOp::Eq => Ok((self.0 == other.0).into_pyobject(py)?.into_any()),
CompareOp::Ne => Ok((self.0 != other.0).into_pyobject(py)?.into_any()),
_ => Ok(PyNotImplemented::get(py).into_any()),
}
}
}
```
If the second argument `object` is not of the type specified in the
signature, the generated code will automatically `return NotImplemented`.
</details>
- `__getattr__(<self>, object) -> object`
- `__getattribute__(<self>, object) -> object`
<details>
<summary>Differences between `__getattr__` and `__getattribute__`</summary>
As in Python, `__getattr__` is only called if the attribute is not found
by normal attribute lookup. `__getattribute__`, on the other hand, is
called for *every* attribute access. If it wants to access existing
attributes on `self`, it needs to be very careful not to introduce
infinite recursion, and use `baseclass.__getattribute__()`.
</details>
- `__setattr__(<self>, value: object) -> ()`
- `__delattr__(<self>, object) -> ()`
Overrides attribute access.
- `__bool__(<self>) -> bool`
Determines the "truthyness" of an object.
- `__call__(<self>, ...) -> object` - here, any argument list can be defined
as for normal `pymethods`
### Iterable objects
Iterators can be defined using these methods:
- `__iter__(<self>) -> object`
- `__next__(<self>) -> Option<object> or IterNextOutput` ([see details](#returning-a-value-from-iteration))
Returning `None` from `__next__` indicates that that there are no further items.
Example:
```rust
use pyo3::prelude::*;
use std::sync::Mutex;
#[pyclass]
struct MyIterator {
iter: Mutex<Box<dyn Iterator<Item = PyObject> + Send>>,
}
#[pymethods]
impl MyIterator {
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(slf: PyRefMut<'_, Self>) -> Option<PyObject> {
slf.iter.lock().unwrap().next()
}
}
```
In many cases you'll have a distinction between the type being iterated over
(i.e. the *iterable*) and the iterator it provides. In this case, the iterable
only needs to implement `__iter__()` while the iterator must implement both
`__iter__()` and `__next__()`. For example:
```rust
# use pyo3::prelude::*;
#[pyclass]
struct Iter {
inner: std::vec::IntoIter<usize>,
}
#[pymethods]
impl Iter {
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<usize> {
slf.inner.next()
}
}
#[pyclass]
struct Container {
iter: Vec<usize>,
}
#[pymethods]
impl Container {
fn __iter__(slf: PyRef<'_, Self>) -> PyResult<Py<Iter>> {
let iter = Iter {
inner: slf.iter.clone().into_iter(),
};
Py::new(slf.py(), iter)
}
}
# Python::with_gil(|py| {
# let container = Container { iter: vec![1, 2, 3, 4] };
# let inst = pyo3::Py::new(py, container).unwrap();
# pyo3::py_run!(py, inst, "assert list(inst) == [1, 2, 3, 4]");
# pyo3::py_run!(py, inst, "assert list(iter(iter(inst))) == [1, 2, 3, 4]");
# });
```
For more details on Python's iteration protocols, check out [the "Iterator Types" section of the library
documentation](https://docs.python.org/library/stdtypes.html#iterator-types).
#### Returning a value from iteration
This guide has so far shown how to use `Option<T>` to implement yielding values
during iteration. In Python a generator can also return a value. This is done by
raising a `StopIteration` exception. To express this in Rust, return `PyResult::Err`
with a `PyStopIteration` as the error.
### Awaitable objects
- `__await__(<self>) -> object`
- `__aiter__(<self>) -> object`
- `__anext__(<self>) -> Option<object>`
### Mapping & Sequence types
The magic methods in this section can be used to implement Python container types. They are two main categories of container in Python: "mappings" such as `dict`, with arbitrary keys, and "sequences" such as `list` and `tuple`, with integer keys.
The Python C-API which PyO3 is built upon has separate "slots" for sequences and mappings. When writing a `class` in pure Python, there is no such distinction in the implementation - a `__getitem__` implementation will fill the slots for both the mapping and sequence forms, for example.
By default PyO3 reproduces the Python behaviour of filling both mapping and sequence slots. This makes sense for the "simple" case which matches Python, and also for sequences, where the mapping slot is used anyway to implement slice indexing.
Mapping types usually will not want the sequence slots filled. Having them filled will lead to outcomes which may be unwanted, such as:
- The mapping type will successfully cast to [`PySequence`]. This may lead to consumers of the type handling it incorrectly.
- Python provides a default implementation of `__iter__` for sequences, which calls `__getitem__` with consecutive positive integers starting from 0 until an `IndexError` is returned. Unless the mapping only contains consecutive positive integer keys, this `__iter__` implementation will likely not be the intended behavior.
Use the `#[pyclass(mapping)]` annotation to instruct PyO3 to only fill the mapping slots, leaving the sequence ones empty. This will apply to `__getitem__`, `__setitem__`, and `__delitem__`.
Use the `#[pyclass(sequence)]` annotation to instruct PyO3 to fill the `sq_length` slot instead of the `mp_length` slot for `__len__`. This will help libraries such as `numpy` recognise the class as a sequence, however will also cause CPython to automatically add the sequence length to any negative indices before passing them to `__getitem__`. (`__getitem__`, `__setitem__` and `__delitem__` mapping slots are still used for sequences, for slice operations.)
- `__len__(<self>) -> usize`
Implements the built-in function `len()`.
- `__contains__(<self>, object) -> bool`
Implements membership test operators.
Should return true if `item` is in `self`, false otherwise.
For objects that don’t define `__contains__()`, the membership test simply
traverses the sequence until it finds a match.
<details>
<summary>Disabling Python's default contains</summary>
By default, all `#[pyclass]` types with an `__iter__` method support a
default implementation of the `in` operator. Types which do not want this
can override this by setting `__contains__` to `None`. This is the same
mechanism as for a pure-Python class. This is done like so:
```rust
# use pyo3::prelude::*;
#
#[pyclass]
struct NoContains {}
#[pymethods]
impl NoContains {
#[classattr]
const __contains__: Option<PyObject> = None;
}
```
</details>
- `__getitem__(<self>, object) -> object`
Implements retrieval of the `self[a]` element.
*Note:* Negative integer indexes are not handled specially by PyO3.
However, for classes with `#[pyclass(sequence)]`, when a negative index is
accessed via `PySequence::get_item`, the underlying C API already adjusts
the index to be positive.
- `__setitem__(<self>, object, object) -> ()`
Implements assignment to the `self[a]` element.
Should only be implemented if elements can be replaced.
Same behavior regarding negative indices as for `__getitem__`.
- `__delitem__(<self>, object) -> ()`
Implements deletion of the `self[a]` element.
Should only be implemented if elements can be deleted.
Same behavior regarding negative indices as for `__getitem__`.
* `fn __concat__(&self, other: impl FromPyObject) -> PyResult<impl ToPyObject>`
Concatenates two sequences.
Used by the `+` operator, after trying the numeric addition via
the `__add__` and `__radd__` methods.
* `fn __repeat__(&self, count: isize) -> PyResult<impl ToPyObject>`
Repeats the sequence `count` times.
Used by the `*` operator, after trying the numeric multiplication via
the `__mul__` and `__rmul__` methods.
* `fn __inplace_concat__(&self, other: impl FromPyObject) -> PyResult<impl ToPyObject>`
Concatenates two sequences.
Used by the `+=` operator, after trying the numeric addition via
the `__iadd__` method.
* `fn __inplace_repeat__(&self, count: isize) -> PyResult<impl ToPyObject>`
Concatenates two sequences.
Used by the `*=` operator, after trying the numeric multiplication via
the `__imul__` method.
### Descriptors
- `__get__(<self>, object, object) -> object`
- `__set__(<self>, object, object) -> ()`
- `__delete__(<self>, object) -> ()`
### Numeric types
Binary arithmetic operations (`+`, `-`, `*`, `@`, `/`, `//`, `%`, `divmod()`,
`pow()` and `**`, `<<`, `>>`, `&`, `^`, and `|`) and their reflected versions:
(If the `object` is not of the type specified in the signature, the generated code
will automatically `return NotImplemented`.)
- `__add__(<self>, object) -> object`
- `__radd__(<self>, object) -> object`
- `__sub__(<self>, object) -> object`
- `__rsub__(<self>, object) -> object`
- `__mul__(<self>, object) -> object`
- `__rmul__(<self>, object) -> object`
- `__matmul__(<self>, object) -> object`
- `__rmatmul__(<self>, object) -> object`
- `__floordiv__(<self>, object) -> object`
- `__rfloordiv__(<self>, object) -> object`
- `__truediv__(<self>, object) -> object`
- `__rtruediv__(<self>, object) -> object`
- `__divmod__(<self>, object) -> object`
- `__rdivmod__(<self>, object) -> object`
- `__mod__(<self>, object) -> object`
- `__rmod__(<self>, object) -> object`
- `__lshift__(<self>, object) -> object`
- `__rlshift__(<self>, object) -> object`
- `__rshift__(<self>, object) -> object`
- `__rrshift__(<self>, object) -> object`
- `__and__(<self>, object) -> object`
- `__rand__(<self>, object) -> object`
- `__xor__(<self>, object) -> object`
- `__rxor__(<self>, object) -> object`
- `__or__(<self>, object) -> object`
- `__ror__(<self>, object) -> object`
- `__pow__(<self>, object, object) -> object`
- `__rpow__(<self>, object, object) -> object`
In-place assignment operations (`+=`, `-=`, `*=`, `@=`, `/=`, `//=`, `%=`,
`**=`, `<<=`, `>>=`, `&=`, `^=`, `|=`):
- `__iadd__(<self>, object) -> ()`
- `__isub__(<self>, object) -> ()`
- `__imul__(<self>, object) -> ()`
- `__imatmul__(<self>, object) -> ()`
- `__itruediv__(<self>, object) -> ()`
- `__ifloordiv__(<self>, object) -> ()`
- `__imod__(<self>, object) -> ()`
- `__ipow__(<self>, object, object) -> ()`
- `__ilshift__(<self>, object) -> ()`
- `__irshift__(<self>, object) -> ()`
- `__iand__(<self>, object) -> ()`
- `__ixor__(<self>, object) -> ()`
- `__ior__(<self>, object) -> ()`
Unary operations (`-`, `+`, `abs()` and `~`):
- `__pos__(<self>) -> object`
- `__neg__(<self>) -> object`
- `__abs__(<self>) -> object`
- `__invert__(<self>) -> object`
Coercions:
- `__index__(<self>) -> object (int)`
- `__int__(<self>) -> object (int)`
- `__float__(<self>) -> object (float)`
### Buffer objects
- `__getbuffer__(<self>, *mut ffi::Py_buffer, flags) -> ()`
- `__releasebuffer__(<self>, *mut ffi::Py_buffer) -> ()`
Errors returned from `__releasebuffer__` will be sent to `sys.unraiseablehook`. It is strongly advised to never return an error from `__releasebuffer__`, and if it really is necessary, to make best effort to perform any required freeing operations before returning. `__releasebuffer__` will not be called a second time; anything not freed will be leaked.
### Garbage Collector Integration
If your type owns references to other Python objects, you will need to integrate
with Python's garbage collector so that the GC is aware of those references. To
do this, implement the two methods `__traverse__` and `__clear__`. These
correspond to the slots `tp_traverse` and `tp_clear` in the Python C API.
`__traverse__` must call `visit.call()` for each reference to another Python
object. `__clear__` must clear out any mutable references to other Python
objects (thus breaking reference cycles). Immutable references do not have to be
cleared, as every cycle must contain at least one mutable reference.
- `__traverse__(<self>, pyo3::class::gc::PyVisit<'_>) -> Result<(), pyo3::class::gc::PyTraverseError>`
- `__clear__(<self>) -> ()`
Example:
```rust
use pyo3::prelude::*;
use pyo3::PyTraverseError;
use pyo3::gc::PyVisit;
#[pyclass]
struct ClassWithGCSupport {
obj: Option<PyObject>,
}
#[pymethods]
impl ClassWithGCSupport {
fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
if let Some(obj) = &self.obj {
visit.call(obj)?
}
Ok(())
}
fn __clear__(&mut self) {
// Clear reference, this decrements ref counter.
self.obj = None;
}
}
```
Usually, an implementation of `__traverse__` should do nothing but calls to `visit.call`.
Most importantly, safe access to the GIL is prohibited inside implementations of `__traverse__`,
i.e. `Python::with_gil` will panic.
> Note: these methods are part of the C API, PyPy does not necessarily honor them. If you are building for PyPy you should measure memory consumption to make sure you do not have runaway memory growth. See [this issue on the PyPy bug tracker](https://github.com/pypy/pypy/issues/3848).
[`PySequence`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PySequence.html
[`CompareOp::matches`]: {{#PYO3_DOCS_URL}}/pyo3/pyclass/enum.CompareOp.html#method.matches
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/class/object.md | # Basic object customization
Recall the `Number` class from the previous chapter:
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
#[pyclass]
struct Number(i32);
#[pymethods]
impl Number {
#[new]
fn new(value: i32) -> Self {
Self(value)
}
}
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Number>()?;
Ok(())
}
```
At this point Python code can import the module, access the class and create class instances - but
nothing else.
```python
from my_module import Number
n = Number(5)
print(n)
```
```text
<builtins.Number object at 0x000002B4D185D7D0>
```
### String representations
It can't even print an user-readable representation of itself! We can fix that by defining the
`__repr__` and `__str__` methods inside a `#[pymethods]` block. We do this by accessing the value
contained inside `Number`.
```rust
# use pyo3::prelude::*;
#
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
// For `__repr__` we want to return a string that Python code could use to recreate
// the `Number`, like `Number(5)` for example.
fn __repr__(&self) -> String {
// We use the `format!` macro to create a string. Its first argument is a
// format string, followed by any number of parameters which replace the
// `{}`'s in the format string.
//
// 👇 Tuple field access in Rust uses a dot
format!("Number({})", self.0)
}
// `__str__` is generally used to create an "informal" representation, so we
// just forward to `i32`'s `ToString` trait implementation to print a bare number.
fn __str__(&self) -> String {
self.0.to_string()
}
}
```
To automatically generate the `__str__` implementation using a `Display` trait implementation, pass the `str` argument to `pyclass`.
```rust
# use std::fmt::{Display, Formatter};
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
# #[pyclass(str)]
# struct Coordinate {
x: i32,
y: i32,
z: i32,
}
impl Display for Coordinate {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "({}, {}, {})", self.x, self.y, self.z)
}
}
```
For convenience, a shorthand format string can be passed to `str` as `str="<format string>"` for **structs only**. It expands and is passed into the `format!` macro in the following ways:
* `"{x}"` -> `"{}", self.x`
* `"{0}"` -> `"{}", self.0`
* `"{x:?}"` -> `"{:?}", self.x`
*Note: Depending upon the format string you use, this may require implementation of the `Display` or `Debug` traits for the given Rust types.*
*Note: the pyclass args `name` and `rename_all` are incompatible with the shorthand format string and will raise a compile time error.*
```rust
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
# #[pyclass(str="({x}, {y}, {z})")]
# struct Coordinate {
x: i32,
y: i32,
z: i32,
}
```
#### Accessing the class name
In the `__repr__`, we used a hard-coded class name. This is sometimes not ideal,
because if the class is subclassed in Python, we would like the repr to reflect
the subclass name. This is typically done in Python code by accessing
`self.__class__.__name__`. In order to be able to access the Python type information
*and* the Rust struct, we need to use a `Bound` as the `self` argument.
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyString;
#
# #[allow(dead_code)]
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> {
// This is the equivalent of `self.__class__.__name__` in Python.
let class_name: Bound<'_, PyString> = slf.get_type().qualname()?;
// To access fields of the Rust struct, we need to borrow the `PyCell`.
Ok(format!("{}({})", class_name, slf.borrow().0))
}
}
```
### Hashing
Let's also implement hashing. We'll just hash the `i32`. For that we need a [`Hasher`]. The one
provided by `std` is [`DefaultHasher`], which uses the [SipHash] algorithm.
```rust
use std::collections::hash_map::DefaultHasher;
// Required to call the `.hash` and `.finish` methods, which are defined on traits.
use std::hash::{Hash, Hasher};
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __hash__(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
}
```
To implement `__hash__` using the Rust [`Hash`] trait implementation, the `hash` option can be used.
This option is only available for `frozen` classes to prevent accidental hash changes from mutating the object. If you need
an `__hash__` implementation for a mutable class, use the manual method from above. This option also requires `eq`: According to the
[Python docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) "If a class does not define an `__eq__()`
method it should not define a `__hash__()` operation either"
```rust
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
#[pyclass(frozen, eq, hash)]
#[derive(PartialEq, Hash)]
struct Number(i32);
```
> **Note**: When implementing `__hash__` and comparisons, it is important that the following property holds:
>
> ```text
> k1 == k2 -> hash(k1) == hash(k2)
> ```
>
> In other words, if two keys are equal, their hashes must also be equal. In addition you must take
> care that your classes' hash doesn't change during its lifetime. In this tutorial we do that by not
> letting Python code change our `Number` class. In other words, it is immutable.
>
> By default, all `#[pyclass]` types have a default hash implementation from Python.
> Types which should not be hashable can override this by setting `__hash__` to None.
> This is the same mechanism as for a pure-Python class. This is done like so:
>
> ```rust
> # use pyo3::prelude::*;
> #[pyclass]
> struct NotHashable {}
>
> #[pymethods]
> impl NotHashable {
> #[classattr]
> const __hash__: Option<Py<PyAny>> = None;
> }
> ```
### Comparisons
PyO3 supports the usual magic comparison methods available in Python such as `__eq__`, `__lt__`
and so on. It is also possible to support all six operations at once with `__richcmp__`.
This method will be called with a value of `CompareOp` depending on the operation.
```rust
use pyo3::class::basic::CompareOp;
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self.0 < other.0),
CompareOp::Le => Ok(self.0 <= other.0),
CompareOp::Eq => Ok(self.0 == other.0),
CompareOp::Ne => Ok(self.0 != other.0),
CompareOp::Gt => Ok(self.0 > other.0),
CompareOp::Ge => Ok(self.0 >= other.0),
}
}
}
```
If you obtain the result by comparing two Rust values, as in this example, you
can take a shortcut using `CompareOp::matches`:
```rust
use pyo3::class::basic::CompareOp;
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __richcmp__(&self, other: &Self, op: CompareOp) -> bool {
op.matches(self.0.cmp(&other.0))
}
}
```
It checks that the `std::cmp::Ordering` obtained from Rust's `Ord` matches
the given `CompareOp`.
Alternatively, you can implement just equality using `__eq__`:
```rust
# use pyo3::prelude::*;
#
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __eq__(&self, other: &Self) -> bool {
self.0 == other.0
}
}
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let x = &Bound::new(py, Number(4))?;
# let y = &Bound::new(py, Number(4))?;
# assert!(x.eq(y)?);
# assert!(!x.ne(y)?);
# Ok(())
# })
# }
```
To implement `__eq__` using the Rust [`PartialEq`] trait implementation, the `eq` option can be used.
```rust
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
#[pyclass(eq)]
#[derive(PartialEq)]
struct Number(i32);
```
To implement `__lt__`, `__le__`, `__gt__`, & `__ge__` using the Rust `PartialOrd` trait implementation, the `ord` option can be used. *Note: Requires `eq`.*
```rust
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
#[pyclass(eq, ord)]
#[derive(PartialEq, PartialOrd)]
struct Number(i32);
```
### Truthyness
We'll consider `Number` to be `True` if it is nonzero:
```rust
# use pyo3::prelude::*;
#
# #[allow(dead_code)]
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __bool__(&self) -> bool {
self.0 != 0
}
}
```
### Final code
```rust
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use pyo3::prelude::*;
use pyo3::class::basic::CompareOp;
use pyo3::types::PyString;
#[pyclass]
struct Number(i32);
#[pymethods]
impl Number {
#[new]
fn new(value: i32) -> Self {
Self(value)
}
fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> {
let class_name: Bound<'_, PyString> = slf.get_type().qualname()?;
Ok(format!("{}({})", class_name, slf.borrow().0))
}
fn __str__(&self) -> String {
self.0.to_string()
}
fn __hash__(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self.0 < other.0),
CompareOp::Le => Ok(self.0 <= other.0),
CompareOp::Eq => Ok(self.0 == other.0),
CompareOp::Ne => Ok(self.0 != other.0),
CompareOp::Gt => Ok(self.0 > other.0),
CompareOp::Ge => Ok(self.0 >= other.0),
}
}
fn __bool__(&self) -> bool {
self.0 != 0
}
}
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Number>()?;
Ok(())
}
```
[`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
[`Hasher`]: https://doc.rust-lang.org/std/hash/trait.Hasher.html
[`DefaultHasher`]: https://doc.rust-lang.org/std/collections/hash_map/struct.DefaultHasher.html
[SipHash]: https://en.wikipedia.org/wiki/SipHash
[`PartialEq`]: https://doc.rust-lang.org/stable/std/cmp/trait.PartialEq.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/class/numeric.md | # Emulating numeric types
At this point we have a `Number` class that we can't actually do any math on!
Before proceeding, we should think about how we want to handle overflows. There are three obvious solutions:
- We can have infinite precision just like Python's `int`. However that would be quite boring - we'd
be reinventing the wheel.
- We can raise exceptions whenever `Number` overflows, but that makes the API painful to use.
- We can wrap around the boundary of `i32`. This is the approach we'll take here. To do that we'll just forward to `i32`'s
`wrapping_*` methods.
### Fixing our constructor
Let's address the first overflow, in `Number`'s constructor:
```python
from my_module import Number
n = Number(1 << 1337)
```
```text
Traceback (most recent call last):
File "example.py", line 3, in <module>
n = Number(1 << 1337)
OverflowError: Python int too large to convert to C long
```
Instead of relying on the default [`FromPyObject`] extraction to parse arguments, we can specify our
own extraction function, using the `#[pyo3(from_py_with = "...")]` attribute. Unfortunately PyO3
doesn't provide a way to wrap Python integers out of the box, but we can do a Python call to mask it
and cast it to an `i32`.
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
fn wrap(obj: &Bound<'_, PyAny>) -> PyResult<i32> {
let val = obj.call_method1("__and__", (0xFFFFFFFF_u32,))?;
let val: u32 = val.extract()?;
// 👇 This intentionally overflows!
Ok(val as i32)
}
```
We also add documentation, via `///` comments, which are visible to Python users.
```rust
# #![allow(dead_code)]
use pyo3::prelude::*;
fn wrap(obj: &Bound<'_, PyAny>) -> PyResult<i32> {
let val = obj.call_method1("__and__", (0xFFFFFFFF_u32,))?;
let val: u32 = val.extract()?;
Ok(val as i32)
}
/// Did you ever hear the tragedy of Darth Signed The Overfloweth? I thought not.
/// It's not a story C would tell you. It's a Rust legend.
#[pyclass(module = "my_module")]
struct Number(i32);
#[pymethods]
impl Number {
#[new]
fn new(#[pyo3(from_py_with = "wrap")] value: i32) -> Self {
Self(value)
}
}
```
With that out of the way, let's implement some operators:
```rust
use pyo3::exceptions::{PyZeroDivisionError, PyValueError};
# use pyo3::prelude::*;
#
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __add__(&self, other: &Self) -> Self {
Self(self.0.wrapping_add(other.0))
}
fn __sub__(&self, other: &Self) -> Self {
Self(self.0.wrapping_sub(other.0))
}
fn __mul__(&self, other: &Self) -> Self {
Self(self.0.wrapping_mul(other.0))
}
fn __truediv__(&self, other: &Self) -> PyResult<Self> {
match self.0.checked_div(other.0) {
Some(i) => Ok(Self(i)),
None => Err(PyZeroDivisionError::new_err("division by zero")),
}
}
fn __floordiv__(&self, other: &Self) -> PyResult<Self> {
match self.0.checked_div(other.0) {
Some(i) => Ok(Self(i)),
None => Err(PyZeroDivisionError::new_err("division by zero")),
}
}
fn __rshift__(&self, other: &Self) -> PyResult<Self> {
match other.0.try_into() {
Ok(rhs) => Ok(Self(self.0.wrapping_shr(rhs))),
Err(_) => Err(PyValueError::new_err("negative shift count")),
}
}
fn __lshift__(&self, other: &Self) -> PyResult<Self> {
match other.0.try_into() {
Ok(rhs) => Ok(Self(self.0.wrapping_shl(rhs))),
Err(_) => Err(PyValueError::new_err("negative shift count")),
}
}
}
```
### Unary arithmetic operations
```rust
# use pyo3::prelude::*;
#
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __pos__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __neg__(&self) -> Self {
Self(-self.0)
}
fn __abs__(&self) -> Self {
Self(self.0.abs())
}
fn __invert__(&self) -> Self {
Self(!self.0)
}
}
```
### Support for the `complex()`, `int()` and `float()` built-in functions.
```rust
# use pyo3::prelude::*;
#
# #[pyclass]
# struct Number(i32);
#
use pyo3::types::PyComplex;
#[pymethods]
impl Number {
fn __int__(&self) -> i32 {
self.0
}
fn __float__(&self) -> f64 {
self.0 as f64
}
fn __complex__<'py>(&self, py: Python<'py>) -> Bound<'py, PyComplex> {
PyComplex::from_doubles(py, self.0 as f64, 0.0)
}
}
```
We do not implement the in-place operations like `__iadd__` because we do not wish to mutate `Number`.
Similarly we're not interested in supporting operations with different types, so we do not implement
the reflected operations like `__radd__` either.
Now Python can use our `Number` class:
```python
from my_module import Number
def hash_djb2(s: str):
'''
A version of Daniel J. Bernstein's djb2 string hashing algorithm
Like many hashing algorithms, it relies on integer wrapping.
'''
n = Number(0)
five = Number(5)
for x in s:
n = Number(ord(x)) + ((n << five) - n)
return n
assert hash_djb2('l50_50') == Number(-1152549421)
```
### Final code
```rust
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use pyo3::exceptions::{PyValueError, PyZeroDivisionError};
use pyo3::prelude::*;
use pyo3::class::basic::CompareOp;
use pyo3::types::{PyComplex, PyString};
fn wrap(obj: &Bound<'_, PyAny>) -> PyResult<i32> {
let val = obj.call_method1("__and__", (0xFFFFFFFF_u32,))?;
let val: u32 = val.extract()?;
Ok(val as i32)
}
/// Did you ever hear the tragedy of Darth Signed The Overfloweth? I thought not.
/// It's not a story C would tell you. It's a Rust legend.
#[pyclass(module = "my_module")]
struct Number(i32);
#[pymethods]
impl Number {
#[new]
fn new(#[pyo3(from_py_with = "wrap")] value: i32) -> Self {
Self(value)
}
fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> {
// Get the class name dynamically in case `Number` is subclassed
let class_name: Bound<'_, PyString> = slf.get_type().qualname()?;
Ok(format!("{}({})", class_name, slf.borrow().0))
}
fn __str__(&self) -> String {
self.0.to_string()
}
fn __hash__(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
match op {
CompareOp::Lt => Ok(self.0 < other.0),
CompareOp::Le => Ok(self.0 <= other.0),
CompareOp::Eq => Ok(self.0 == other.0),
CompareOp::Ne => Ok(self.0 != other.0),
CompareOp::Gt => Ok(self.0 > other.0),
CompareOp::Ge => Ok(self.0 >= other.0),
}
}
fn __bool__(&self) -> bool {
self.0 != 0
}
fn __add__(&self, other: &Self) -> Self {
Self(self.0.wrapping_add(other.0))
}
fn __sub__(&self, other: &Self) -> Self {
Self(self.0.wrapping_sub(other.0))
}
fn __mul__(&self, other: &Self) -> Self {
Self(self.0.wrapping_mul(other.0))
}
fn __truediv__(&self, other: &Self) -> PyResult<Self> {
match self.0.checked_div(other.0) {
Some(i) => Ok(Self(i)),
None => Err(PyZeroDivisionError::new_err("division by zero")),
}
}
fn __floordiv__(&self, other: &Self) -> PyResult<Self> {
match self.0.checked_div(other.0) {
Some(i) => Ok(Self(i)),
None => Err(PyZeroDivisionError::new_err("division by zero")),
}
}
fn __rshift__(&self, other: &Self) -> PyResult<Self> {
match other.0.try_into() {
Ok(rhs) => Ok(Self(self.0.wrapping_shr(rhs))),
Err(_) => Err(PyValueError::new_err("negative shift count")),
}
}
fn __lshift__(&self, other: &Self) -> PyResult<Self> {
match other.0.try_into() {
Ok(rhs) => Ok(Self(self.0.wrapping_shl(rhs))),
Err(_) => Err(PyValueError::new_err("negative shift count")),
}
}
fn __xor__(&self, other: &Self) -> Self {
Self(self.0 ^ other.0)
}
fn __or__(&self, other: &Self) -> Self {
Self(self.0 | other.0)
}
fn __and__(&self, other: &Self) -> Self {
Self(self.0 & other.0)
}
fn __int__(&self) -> i32 {
self.0
}
fn __float__(&self) -> f64 {
self.0 as f64
}
fn __complex__<'py>(&self, py: Python<'py>) -> Bound<'py, PyComplex> {
PyComplex::from_doubles(py, self.0 as f64, 0.0)
}
}
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Number>()?;
Ok(())
}
# const SCRIPT: &'static std::ffi::CStr = pyo3::ffi::c_str!(r#"
# def hash_djb2(s: str):
# n = Number(0)
# five = Number(5)
#
# for x in s:
# n = Number(ord(x)) + ((n << five) - n)
# return n
#
# assert hash_djb2('l50_50') == Number(-1152549421)
# assert hash_djb2('logo') == Number(3327403)
# assert hash_djb2('horizon') == Number(1097468315)
#
#
# assert Number(2) + Number(2) == Number(4)
# assert Number(2) + Number(2) != Number(5)
#
# assert Number(13) - Number(7) == Number(6)
# assert Number(13) - Number(-7) == Number(20)
#
# assert Number(13) / Number(7) == Number(1)
# assert Number(13) // Number(7) == Number(1)
#
# assert Number(13) * Number(7) == Number(13*7)
#
# assert Number(13) > Number(7)
# assert Number(13) < Number(20)
# assert Number(13) == Number(13)
# assert Number(13) >= Number(7)
# assert Number(13) <= Number(20)
# assert Number(13) == Number(13)
#
#
# assert (True if Number(1) else False)
# assert (False if Number(0) else True)
#
#
# assert int(Number(13)) == 13
# assert float(Number(13)) == 13
# assert Number.__doc__ == "Did you ever hear the tragedy of Darth Signed The Overfloweth? I thought not.\nIt's not a story C would tell you. It's a Rust legend."
# assert Number(12345234523452) == Number(1498514748)
# try:
# import inspect
# assert inspect.signature(Number).__str__() == '(value)'
# except ValueError:
# # Not supported with `abi3` before Python 3.10
# pass
# assert Number(1337).__str__() == '1337'
# assert Number(1337).__repr__() == 'Number(1337)'
"#);
#
# use pyo3::PyTypeInfo;
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let globals = PyModule::import(py, "__main__")?.dict();
# globals.set_item("Number", Number::type_object(py))?;
#
# py.run(SCRIPT, Some(&globals), None)?;
# Ok(())
# })
# }
```
## Appendix: Writing some unsafe code
At the beginning of this chapter we said that PyO3 doesn't provide a way to wrap Python integers out
of the box but that's a half truth. There's not a PyO3 API for it, but there's a Python C API
function that does:
```c
unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)
```
We can call this function from Rust by using [`pyo3::ffi::PyLong_AsUnsignedLongMask`]. This is an *unsafe*
function, which means we have to use an unsafe block to call it and take responsibility for upholding
the contracts of this function. Let's review those contracts:
- The GIL must be held. If it's not, calling this function causes a data race.
- The pointer must be valid, i.e. it must be properly aligned and point to a valid Python object.
Let's create that helper function. The signature has to be `fn(&Bound<'_, PyAny>) -> PyResult<T>`.
- `&Bound<'_, PyAny>` represents a checked borrowed reference, so the pointer derived from it is valid (and not null).
- Whenever we have borrowed references to Python objects in scope, it is guaranteed that the GIL is held. This reference is also where we can get a [`Python`] token to use in our call to [`PyErr::take`].
```rust
# #![allow(dead_code)]
use std::os::raw::c_ulong;
use pyo3::prelude::*;
use pyo3::ffi;
fn wrap(obj: &Bound<'_, PyAny>) -> Result<i32, PyErr> {
let py: Python<'_> = obj.py();
unsafe {
let ptr = obj.as_ptr();
let ret: c_ulong = ffi::PyLong_AsUnsignedLongMask(ptr);
if ret == c_ulong::MAX {
if let Some(err) = PyErr::take(py) {
return Err(err);
}
}
Ok(ret as i32)
}
}
```
[`PyErr::take`]: {{#PYO3_DOCS_URL}}/pyo3/prelude/struct.PyErr.html#method.take
[`Python`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html
[`FromPyObject`]: {{#PYO3_DOCS_URL}}/pyo3/conversion/trait.FromPyObject.html
[`pyo3::ffi::PyLong_AsUnsignedLongMask`]: {{#PYO3_DOCS_URL}}/pyo3/ffi/fn.PyLong_AsUnsignedLongMask.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/class/call.md | # Emulating callable objects
Classes can be callable if they have a `#[pymethod]` named `__call__`.
This allows instances of a class to behave similar to functions.
This method's signature must look like `__call__(<self>, ...) -> object` - here,
any argument list can be defined as for normal pymethods
### Example: Implementing a call counter
The following pyclass is a basic decorator - its constructor takes a Python object
as argument and calls that object when called. An equivalent Python implementation
is linked at the end.
An example crate containing this pyclass can be found [here](https://github.com/PyO3/pyo3/tree/main/examples/decorator)
```rust,ignore
{{#include ../../../examples/decorator/src/lib.rs}}
```
Python code:
```python
{{#include ../../../examples/decorator/tests/example.py}}
```
Output:
```text
say_hello has been called 1 time(s).
hello
say_hello has been called 2 time(s).
hello
say_hello has been called 3 time(s).
hello
say_hello has been called 4 time(s).
hello
```
### Pure Python implementation
A Python implementation of this looks similar to the Rust version:
```python
class Counter:
def __init__(self, wraps):
self.count = 0
self.wraps = wraps
def __call__(self, *args, **kwargs):
self.count += 1
print(f"{self.wraps.__name__} has been called {self.count} time(s)")
self.wraps(*args, **kwargs)
```
Note that it can also be implemented as a higher order function:
```python
def Counter(wraps):
count = 0
def call(*args, **kwargs):
nonlocal count
count += 1
print(f"{wraps.__name__} has been called {count} time(s)")
return wraps(*args, **kwargs)
return call
```
### What is the `AtomicU64` for?
A [previous implementation] used a normal `u64`, which meant it required a `&mut self` receiver to update the count:
```rust,ignore
#[pyo3(signature = (*args, **kwargs))]
fn __call__(
&mut self,
py: Python<'_>,
args: &Bound<'_, PyTuple>,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<Py<PyAny>> {
self.count += 1;
let name = self.wraps.getattr(py, "__name__")?;
println!("{} has been called {} time(s).", name, self.count);
// After doing something, we finally forward the call to the wrapped function
let ret = self.wraps.call(py, args, kwargs)?;
// We could do something with the return value of
// the function before returning it
Ok(ret)
}
```
The problem with this is that the `&mut self` receiver means PyO3 has to borrow it exclusively,
and hold this borrow across the`self.wraps.call(py, args, kwargs)` call. This call returns control to the user's Python code
which is free to call arbitrary things, *including* the decorated function. If that happens PyO3 is unable to create a second unique borrow and will be forced to raise an exception.
As a result, something innocent like this will raise an exception:
```py
@Counter
def say_hello():
if say_hello.count < 2:
print(f"hello from decorator")
say_hello()
# RuntimeError: Already borrowed
```
The implementation in this chapter fixes that by never borrowing exclusively; all the methods take `&self` as receivers, of which multiple may exist simultaneously. This requires a shared counter and the most straightforward way to implement thread-safe interior mutability (e.g. the type does not need to accept `&mut self` to modify the "interior" state) for a `u64` is to use [`AtomicU64`], so that's what is used here.
This shows the dangers of running arbitrary Python code - note that "running arbitrary Python code" can be far more subtle than the example above:
- Python's asynchronous executor may park the current thread in the middle of Python code, even in Python code that *you* control, and let other Python code run.
- Dropping arbitrary Python objects may invoke destructors defined in Python (`__del__` methods).
- Calling Python's C-api (most PyO3 apis call C-api functions internally) may raise exceptions, which may allow Python code in signal handlers to run.
- On the free-threaded build, users might use Python's `threading` module to work with your types simultaneously from multiple OS threads.
This is especially important if you are writing unsafe code; Python code must never be able to cause undefined behavior. You must ensure that your Rust code is in a consistent state before doing any of the above things.
[previous implementation]: https://github.com/PyO3/pyo3/discussions/2598 "Thread Safe Decorator <Help Wanted> · Discussion #2598 · PyO3/pyo3"
[`AtomicU64`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU64.html "AtomicU64 in std::sync::atomic - Rust"
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/python-from-rust/function-calls.md | # Calling Python functions
The `Bound<'py, T>` smart pointer (such as `Bound<'py, PyAny>`, `Bound<'py, PyList>`, or `Bound<'py, MyClass>`) can be used to call Python functions.
PyO3 offers two APIs to make function calls:
* [`call`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.call) - call any callable Python object.
* [`call_method`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.call_method) - call a method on the Python object.
Both of these APIs take `args` and `kwargs` arguments (for positional and keyword arguments respectively). There are variants for less complex calls:
* [`call1`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.call1) and [`call_method1`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.call_method1) to call only with positional `args`.
* [`call0`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.call0) and [`call_method0`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.PyAnyMethods.html#tymethod.call_method0) to call with no arguments.
For convenience the [`Py<T>`](../types.md#pyt-and-pyobject) smart pointer also exposes these same six API methods, but needs a `Python` token as an additional first argument to prove the GIL is held.
The example below calls a Python function behind a `PyObject` (aka `Py<PyAny>`) reference:
```rust
use pyo3::prelude::*;
use pyo3::types::PyTuple;
use pyo3_ffi::c_str;
fn main() -> PyResult<()> {
let arg1 = "arg1";
let arg2 = "arg2";
let arg3 = "arg3";
Python::with_gil(|py| {
let fun: Py<PyAny> = PyModule::from_code(
py,
c_str!("def example(*args, **kwargs):
if args != ():
print('called with args', args)
if kwargs != {}:
print('called with kwargs', kwargs)
if args == () and kwargs == {}:
print('called with no arguments')"),
c_str!(""),
c_str!(""),
)?
.getattr("example")?
.into();
// call object without any arguments
fun.call0(py)?;
// pass object with Rust tuple of positional arguments
let args = (arg1, arg2, arg3);
fun.call1(py, args)?;
// call object with Python tuple of positional arguments
let args = PyTuple::new(py, &[arg1, arg2, arg3])?;
fun.call1(py, args)?;
Ok(())
})
}
```
## Creating keyword arguments
For the `call` and `call_method` APIs, `kwargs` are `Option<&Bound<'py, PyDict>>`, so can either be `None` or `Some(&dict)`. You can use the [`IntoPyDict`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.IntoPyDict.html) trait to convert other dict-like containers, e.g. `HashMap` or `BTreeMap`, as well as tuples with up to 10 elements and `Vec`s where each element is a two-element tuple.
```rust
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use std::collections::HashMap;
use pyo3_ffi::c_str;
fn main() -> PyResult<()> {
let key1 = "key1";
let val1 = 1;
let key2 = "key2";
let val2 = 2;
Python::with_gil(|py| {
let fun: Py<PyAny> = PyModule::from_code(
py,
c_str!("def example(*args, **kwargs):
if args != ():
print('called with args', args)
if kwargs != {}:
print('called with kwargs', kwargs)
if args == () and kwargs == {}:
print('called with no arguments')"),
c_str!(""),
c_str!(""),
)?
.getattr("example")?
.into();
// call object with PyDict
let kwargs = [(key1, val1)].into_py_dict(py)?;
fun.call(py, (), Some(&kwargs))?;
// pass arguments as Vec
let kwargs = vec![(key1, val1), (key2, val2)];
fun.call(py, (), Some(&kwargs.into_py_dict(py)?))?;
// pass arguments as HashMap
let mut kwargs = HashMap::<&str, i32>::new();
kwargs.insert(key1, 1);
fun.call(py, (), Some(&kwargs.into_py_dict(py)?))?;
Ok(())
})
}
``` |
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/python-from-rust/calling-existing-code.md | # Executing existing Python code
If you already have some existing Python code that you need to execute from Rust, the following FAQs can help you select the right PyO3 functionality for your situation:
## Want to access Python APIs? Then use `PyModule::import`.
[`PyModule::import`] can be used to get handle to a Python module from Rust. You can use this to import and use any Python
module available in your environment.
```rust
use pyo3::prelude::*;
fn main() -> PyResult<()> {
Python::with_gil(|py| {
let builtins = PyModule::import(py, "builtins")?;
let total: i32 = builtins
.getattr("sum")?
.call1((vec![1, 2, 3],))?
.extract()?;
assert_eq!(total, 6);
Ok(())
})
}
```
[`PyModule::import`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.import
## Want to run just an expression? Then use `eval`.
[`Python::eval`]({{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.eval) is
a method to execute a [Python expression](https://docs.python.org/3/reference/expressions.html)
and return the evaluated value as a `Bound<'py, PyAny>` object.
```rust
use pyo3::prelude::*;
use pyo3::ffi::c_str;
# fn main() -> Result<(), ()> {
Python::with_gil(|py| {
let result = py
.eval(c_str!("[i * 10 for i in range(5)]"), None, None)
.map_err(|e| {
e.print_and_set_sys_last_vars(py);
})?;
let res: Vec<i64> = result.extract().unwrap();
assert_eq!(res, vec![0, 10, 20, 30, 40]);
Ok(())
})
# }
```
## Want to run statements? Then use `run`.
[`Python::run`] is a method to execute one or more
[Python statements](https://docs.python.org/3/reference/simple_stmts.html).
This method returns nothing (like any Python statement), but you can get
access to manipulated objects via the `locals` dict.
You can also use the [`py_run!`] macro, which is a shorthand for [`Python::run`].
Since [`py_run!`] panics on exceptions, we recommend you use this macro only for
quickly testing your Python extensions.
[`Python::run`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.run
```rust
use pyo3::prelude::*;
use pyo3::py_run;
# fn main() {
#[pyclass]
struct UserData {
id: u32,
name: String,
}
#[pymethods]
impl UserData {
fn as_tuple(&self) -> (u32, String) {
(self.id, self.name.clone())
}
fn __repr__(&self) -> PyResult<String> {
Ok(format!("User {}(id: {})", self.name, self.id))
}
}
Python::with_gil(|py| {
let userdata = UserData {
id: 34,
name: "Yu".to_string(),
};
let userdata = Py::new(py, userdata).unwrap();
let userdata_as_tuple = (34, "Yu");
py_run!(py, userdata userdata_as_tuple, r#"
assert repr(userdata) == "User Yu(id: 34)"
assert userdata.as_tuple() == userdata_as_tuple
"#);
})
# }
```
## You have a Python file or code snippet? Then use `PyModule::from_code`.
[`PyModule::from_code`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.from_code)
can be used to generate a Python module which can then be used just as if it was imported with
`PyModule::import`.
**Warning**: This will compile and execute code. **Never** pass untrusted code
to this function!
```rust
use pyo3::{prelude::*, types::IntoPyDict};
use pyo3_ffi::c_str;
# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let activators = PyModule::from_code(
py,
c_str!(r#"
def relu(x):
"""see https://en.wikipedia.org/wiki/Rectifier_(neural_networks)"""
return max(0.0, x)
def leaky_relu(x, slope=0.01):
return x if x >= 0 else x * slope
"#),
c_str!("activators.py"),
c_str!("activators"),
)?;
let relu_result: f64 = activators.getattr("relu")?.call1((-1.0,))?.extract()?;
assert_eq!(relu_result, 0.0);
let kwargs = [("slope", 0.2)].into_py_dict(py)?;
let lrelu_result: f64 = activators
.getattr("leaky_relu")?
.call((-1.0,), Some(&kwargs))?
.extract()?;
assert_eq!(lrelu_result, -0.2);
# Ok(())
})
# }
```
## Want to embed Python in Rust with additional modules?
Python maintains the `sys.modules` dict as a cache of all imported modules.
An import in Python will first attempt to lookup the module from this dict,
and if not present will use various strategies to attempt to locate and load
the module.
The [`append_to_inittab`]({{#PYO3_DOCS_URL}}/pyo3/macro.append_to_inittab.html)
macro can be used to add additional `#[pymodule]` modules to an embedded
Python interpreter. The macro **must** be invoked _before_ initializing Python.
As an example, the below adds the module `foo` to the embedded interpreter:
```rust
use pyo3::prelude::*;
use pyo3::ffi::c_str;
#[pyfunction]
fn add_one(x: i64) -> i64 {
x + 1
}
#[pymodule]
fn foo(foo_module: &Bound<'_, PyModule>) -> PyResult<()> {
foo_module.add_function(wrap_pyfunction!(add_one, foo_module)?)?;
Ok(())
}
fn main() -> PyResult<()> {
pyo3::append_to_inittab!(foo);
Python::with_gil(|py| Python::run(py, c_str!("import foo; foo.add_one(6)"), None, None))
}
```
If `append_to_inittab` cannot be used due to constraints in the program,
an alternative is to create a module using [`PyModule::new`]
and insert it manually into `sys.modules`:
```rust
use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3::ffi::c_str;
#[pyfunction]
pub fn add_one(x: i64) -> i64 {
x + 1
}
fn main() -> PyResult<()> {
Python::with_gil(|py| {
// Create new module
let foo_module = PyModule::new(py, "foo")?;
foo_module.add_function(wrap_pyfunction!(add_one, &foo_module)?)?;
// Import and get sys.modules
let sys = PyModule::import(py, "sys")?;
let py_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?;
// Insert foo into sys.modules
py_modules.set_item("foo", foo_module)?;
// Now we can import + run our python code
Python::run(py, c_str!("import foo; foo.add_one(6)"), None, None)
})
}
```
## Include multiple Python files
You can include a file at compile time by using
[`std::include_str`](https://doc.rust-lang.org/std/macro.include_str.html) macro.
Or you can load a file at runtime by using
[`std::fs::read_to_string`](https://doc.rust-lang.org/std/fs/fn.read_to_string.html) function.
Many Python files can be included and loaded as modules. If one file depends on
another you must preserve correct order while declaring `PyModule`.
Example directory structure:
```text
.
├── Cargo.lock
├── Cargo.toml
├── python_app
│ ├── app.py
│ └── utils
│ └── foo.py
└── src
└── main.rs
```
`python_app/app.py`:
```python
from utils.foo import bar
def run():
return bar()
```
`python_app/utils/foo.py`:
```python
def bar():
return "baz"
```
The example below shows:
* how to include content of `app.py` and `utils/foo.py` into your rust binary
* how to call function `run()` (declared in `app.py`) that needs function
imported from `utils/foo.py`
`src/main.rs`:
```rust,ignore
use pyo3::prelude::*;
use pyo3_ffi::c_str;
fn main() -> PyResult<()> {
let py_foo = c_str!(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/python_app/utils/foo.py"
)));
let py_app = c_str!(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python_app/app.py")));
let from_python = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
PyModule::from_code(py, py_foo, c_str!("utils.foo"), c_str!("utils.foo"))?;
let app: Py<PyAny> = PyModule::from_code(py, py_app, c_str!(""), c_str!(""))?
.getattr("run")?
.into();
app.call0(py)
});
println!("py: {}", from_python?);
Ok(())
}
```
The example below shows:
* how to load content of `app.py` at runtime so that it sees its dependencies
automatically
* how to call function `run()` (declared in `app.py`) that needs function
imported from `utils/foo.py`
It is recommended to use absolute paths because then your binary can be run
from anywhere as long as your `app.py` is in the expected directory (in this example
that directory is `/usr/share/python_app`).
`src/main.rs`:
```rust,no_run
use pyo3::prelude::*;
use pyo3::types::PyList;
use pyo3_ffi::c_str;
use std::fs;
use std::path::Path;
use std::ffi::CString;
fn main() -> PyResult<()> {
let path = Path::new("/usr/share/python_app");
let py_app = CString::new(fs::read_to_string(path.join("app.py"))?)?;
let from_python = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
let syspath = py
.import("sys")?
.getattr("path")?
.downcast_into::<PyList>()?;
syspath.insert(0, path)?;
let app: Py<PyAny> = PyModule::from_code(py, py_app.as_c_str(), c_str!(""), c_str!(""))?
.getattr("run")?
.into();
app.call0(py)
});
println!("py: {}", from_python?);
Ok(())
}
```
[`Python::run`]: {{#PYO3_DOCS_URL}}/pyo3/marker/struct.Python.html#method.run
[`py_run!`]: {{#PYO3_DOCS_URL}}/pyo3/macro.py_run.html
## Need to use a context manager from Rust?
Use context managers by directly invoking `__enter__` and `__exit__`.
```rust
use pyo3::prelude::*;
use pyo3::ffi::c_str;
fn main() {
Python::with_gil(|py| {
let custom_manager = PyModule::from_code(
py,
c_str!(r#"
class House(object):
def __init__(self, address):
self.address = address
def __enter__(self):
print(f"Welcome to {self.address}!")
def __exit__(self, type, value, traceback):
if type:
print(f"Sorry you had {type} trouble at {self.address}")
else:
print(f"Thank you for visiting {self.address}, come again soon!")
"#),
c_str!("house.py"),
c_str!("house"),
)
.unwrap();
let house_class = custom_manager.getattr("House").unwrap();
let house = house_class.call1(("123 Main Street",)).unwrap();
house.call_method0("__enter__").unwrap();
let result = py.eval(c_str!("undefined_variable + 1"), None, None);
// If the eval threw an exception we'll pass it through to the context manager.
// Otherwise, __exit__ is called with empty arguments (Python "None").
match result {
Ok(_) => {
let none = py.None();
house
.call_method1("__exit__", (&none, &none, &none))
.unwrap();
}
Err(e) => {
house
.call_method1(
"__exit__",
(
e.get_type(py),
e.value(py),
e.traceback(py),
),
)
.unwrap();
}
}
})
}
```
## Handling system signals/interrupts (Ctrl-C)
The best way to handle system signals when running Rust code is to periodically call `Python::check_signals` to handle any signals captured by Python's signal handler. See also [the FAQ entry](../faq.md#ctrl-c-doesnt-do-anything-while-my-rust-code-is-executing).
Alternatively, set Python's `signal` module to take the default action for a signal:
```rust
use pyo3::prelude::*;
# fn main() -> PyResult<()> {
Python::with_gil(|py| -> PyResult<()> {
let signal = py.import("signal")?;
// Set SIGINT to have the default action
signal
.getattr("signal")?
.call1((signal.getattr("SIGINT")?, signal.getattr("SIG_DFL")?))?;
Ok(())
})
# }
```
[`PyModule::new`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.new
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/conversions/tables.md | ## Mapping of Rust types to Python types
When writing functions callable from Python (such as a `#[pyfunction]` or in a `#[pymethods]` block), the trait `FromPyObject` is required for function arguments, and `IntoPy<PyObject>` is required for function return values.
Consult the tables in the following section to find the Rust types provided by PyO3 which implement these traits.
### Argument Types
When accepting a function argument, it is possible to either use Rust library types or PyO3's Python-native types. (See the next section for discussion on when to use each.)
The table below contains the Python type and the corresponding function argument types that will accept them:
| Python | Rust | Rust (Python-native) |
| ------------- |:-------------------------------:|:--------------------:|
| `object` | - | `PyAny` |
| `str` | `String`, `Cow<str>`, `&str`, `char`, `OsString`, `PathBuf`, `Path` | `PyString` |
| `bytes` | `Vec<u8>`, `&[u8]`, `Cow<[u8]>` | `PyBytes` |
| `bool` | `bool` | `PyBool` |
| `int` | `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`, `u64`, `i128`, `u128`, `isize`, `usize`, `num_bigint::BigInt`[^1], `num_bigint::BigUint`[^1] | `PyInt` |
| `float` | `f32`, `f64` | `PyFloat` |
| `complex` | `num_complex::Complex`[^2] | `PyComplex` |
| `fractions.Fraction`| `num_rational::Ratio`[^8] | - |
| `list[T]` | `Vec<T>` | `PyList` |
| `dict[K, V]` | `HashMap<K, V>`, `BTreeMap<K, V>`, `hashbrown::HashMap<K, V>`[^3], `indexmap::IndexMap<K, V>`[^4] | `PyDict` |
| `tuple[T, U]` | `(T, U)`, `Vec<T>` | `PyTuple` |
| `set[T]` | `HashSet<T>`, `BTreeSet<T>`, `hashbrown::HashSet<T>`[^3] | `PySet` |
| `frozenset[T]` | `HashSet<T>`, `BTreeSet<T>`, `hashbrown::HashSet<T>`[^3] | `PyFrozenSet` |
| `bytearray` | `Vec<u8>`, `Cow<[u8]>` | `PyByteArray` |
| `slice` | - | `PySlice` |
| `type` | - | `PyType` |
| `module` | - | `PyModule` |
| `collections.abc.Buffer` | - | `PyBuffer<T>` |
| `datetime.datetime` | `SystemTime`, `chrono::DateTime<Tz>`[^5], `chrono::NaiveDateTime`[^5] | `PyDateTime` |
| `datetime.date` | `chrono::NaiveDate`[^5] | `PyDate` |
| `datetime.time` | `chrono::NaiveTime`[^5] | `PyTime` |
| `datetime.tzinfo` | `chrono::FixedOffset`[^5], `chrono::Utc`[^5], `chrono_tz::TimeZone`[^6] | `PyTzInfo` |
| `datetime.timedelta` | `Duration`, `chrono::Duration`[^5] | `PyDelta` |
| `decimal.Decimal` | `rust_decimal::Decimal`[^7] | - |
| `ipaddress.IPv4Address` | `std::net::IpAddr`, `std::net::IpV4Addr` | - |
| `ipaddress.IPv6Address` | `std::net::IpAddr`, `std::net::IpV6Addr` | - |
| `os.PathLike ` | `PathBuf`, `Path` | `PyString` |
| `pathlib.Path` | `PathBuf`, `Path` | `PyString` |
| `typing.Optional[T]` | `Option<T>` | - |
| `typing.Sequence[T]` | `Vec<T>` | `PySequence` |
| `typing.Mapping[K, V]` | `HashMap<K, V>`, `BTreeMap<K, V>`, `hashbrown::HashMap<K, V>`[^3], `indexmap::IndexMap<K, V>`[^4] | `&PyMapping` |
| `typing.Iterator[Any]` | - | `PyIterator` |
| `typing.Union[...]` | See [`#[derive(FromPyObject)]`](traits.md#deriving-frompyobject-for-enums) | - |
It is also worth remembering the following special types:
| What | Description |
| ---------------- | ------------------------------------- |
| `Python<'py>` | A GIL token, used to pass to PyO3 constructors to prove ownership of the GIL. |
| `Bound<'py, T>` | A Python object connected to the GIL lifetime. This provides access to most of PyO3's APIs. |
| `Py<T>` | A Python object isolated from the GIL lifetime. This can be sent to other threads. |
| `PyObject` | An alias for `Py<PyAny>` |
| `PyRef<T>` | A `#[pyclass]` borrowed immutably. |
| `PyRefMut<T>` | A `#[pyclass]` borrowed mutably. |
For more detail on accepting `#[pyclass]` values as function arguments, see [the section of this guide on Python Classes](../class.md).
#### Using Rust library types vs Python-native types
Using Rust library types as function arguments will incur a conversion cost compared to using the Python-native types. Using the Python-native types is almost zero-cost (they just require a type check similar to the Python builtin function `isinstance()`).
However, once that conversion cost has been paid, the Rust standard library types offer a number of benefits:
- You can write functionality in native-speed Rust code (free of Python's runtime costs).
- You get better interoperability with the rest of the Rust ecosystem.
- You can use `Python::allow_threads` to release the Python GIL and let other Python threads make progress while your Rust code is executing.
- You also benefit from stricter type checking. For example you can specify `Vec<i32>`, which will only accept a Python `list` containing integers. The Python-native equivalent, `&PyList`, would accept a Python `list` containing Python objects of any type.
For most PyO3 usage the conversion cost is worth paying to get these benefits. As always, if you're not sure it's worth it in your case, benchmark it!
### Returning Rust values to Python
When returning values from functions callable from Python, [PyO3's smart pointers](../types.md#pyo3s-smart-pointers) (`Py<T>`, `Bound<'py, T>`, and `Borrowed<'a, 'py, T>`) can be used with zero cost.
Because `Bound<'py, T>` and `Borrowed<'a, 'py, T>` have lifetime parameters, the Rust compiler may ask for lifetime annotations to be added to your function. See the [section of the guide dedicated to this](../types.md#function-argument-lifetimes).
If your function is fallible, it should return `PyResult<T>` or `Result<T, E>` where `E` implements `From<E> for PyErr`. This will raise a `Python` exception if the `Err` variant is returned.
Finally, the following Rust types are also able to convert to Python as return values:
| Rust type | Resulting Python Type |
| ------------- |:-------------------------------:|
| `String` | `str` |
| `&str` | `str` |
| `bool` | `bool` |
| Any integer type (`i32`, `u32`, `usize`, etc) | `int` |
| `f32`, `f64` | `float` |
| `Option<T>` | `Optional[T]` |
| `(T, U)` | `Tuple[T, U]` |
| `Vec<T>` | `List[T]` |
| `Cow<[u8]>` | `bytes` |
| `HashMap<K, V>` | `Dict[K, V]` |
| `BTreeMap<K, V>` | `Dict[K, V]` |
| `HashSet<T>` | `Set[T]` |
| `BTreeSet<T>` | `Set[T]` |
| `Py<T>` | `T` |
| `Bound<T>` | `T` |
| `PyRef<T: PyClass>` | `T` |
| `PyRefMut<T: PyClass>` | `T` |
[^1]: Requires the `num-bigint` optional feature.
[^2]: Requires the `num-complex` optional feature.
[^3]: Requires the `hashbrown` optional feature.
[^4]: Requires the `indexmap` optional feature.
[^5]: Requires the `chrono` optional feature.
[^6]: Requires the `chrono-tz` optional feature.
[^7]: Requires the `rust_decimal` optional feature.
[^8]: Requires the `num-rational` optional feature.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src | lc_public_repos/langsmith-sdk/vendor/pyo3/guide/src/conversions/traits.md | ## Conversion traits
PyO3 provides some handy traits to convert between Python types and Rust types.
### `.extract()` and the `FromPyObject` trait
The easiest way to convert a Python object to a Rust value is using
`.extract()`. It returns a `PyResult` with a type error if the conversion
fails, so usually you will use something like
```rust
# use pyo3::prelude::*;
# use pyo3::types::PyList;
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let list = PyList::new(py, b"foo")?;
let v: Vec<i32> = list.extract()?;
# assert_eq!(&v, &[102, 111, 111]);
# Ok(())
# })
# }
```
This method is available for many Python object types, and can produce a wide
variety of Rust types, which you can check out in the implementor list of
[`FromPyObject`].
[`FromPyObject`] is also implemented for your own Rust types wrapped as Python
objects (see [the chapter about classes](../class.md)). There, in order to both be
able to operate on mutable references *and* satisfy Rust's rules of non-aliasing
mutable references, you have to extract the PyO3 reference wrappers [`PyRef`]
and [`PyRefMut`]. They work like the reference wrappers of
`std::cell::RefCell` and ensure (at runtime) that Rust borrows are allowed.
#### Deriving [`FromPyObject`]
[`FromPyObject`] can be automatically derived for many kinds of structs and enums
if the member types themselves implement `FromPyObject`. This even includes members
with a generic type `T: FromPyObject`. Derivation for empty enums, enum variants and
structs is not supported.
#### Deriving [`FromPyObject`] for structs
The derivation generates code that will attempt to access the attribute `my_string` on
the Python object, i.e. `obj.getattr("my_string")`, and call `extract()` on the attribute.
```rust
use pyo3::prelude::*;
use pyo3_ffi::c_str;
#[derive(FromPyObject)]
struct RustyStruct {
my_string: String,
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let module = PyModule::from_code(
# py,
# c_str!("class Foo:
# def __init__(self):
# self.my_string = 'test'"),
# c_str!(""),
# c_str!(""),
# )?;
#
# let class = module.getattr("Foo")?;
# let instance = class.call0()?;
# let rustystruct: RustyStruct = instance.extract()?;
# assert_eq!(rustystruct.my_string, "test");
# Ok(())
# })
# }
```
By setting the `#[pyo3(item)]` attribute on the field, PyO3 will attempt to extract the value by calling the `get_item` method on the Python object.
```rust
use pyo3::prelude::*;
#[derive(FromPyObject)]
struct RustyStruct {
#[pyo3(item)]
my_string: String,
}
#
# use pyo3::types::PyDict;
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let dict = PyDict::new(py);
# dict.set_item("my_string", "test")?;
#
# let rustystruct: RustyStruct = dict.extract()?;
# assert_eq!(rustystruct.my_string, "test");
# Ok(())
# })
# }
```
The argument passed to `getattr` and `get_item` can also be configured:
```rust
use pyo3::prelude::*;
use pyo3_ffi::c_str;
#[derive(FromPyObject)]
struct RustyStruct {
#[pyo3(item("key"))]
string_in_mapping: String,
#[pyo3(attribute("name"))]
string_attr: String,
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let module = PyModule::from_code(
# py,
# c_str!("class Foo(dict):
# def __init__(self):
# self.name = 'test'
# self['key'] = 'test2'"),
# c_str!(""),
# c_str!(""),
# )?;
#
# let class = module.getattr("Foo")?;
# let instance = class.call0()?;
# let rustystruct: RustyStruct = instance.extract()?;
# assert_eq!(rustystruct.string_attr, "test");
# assert_eq!(rustystruct.string_in_mapping, "test2");
#
# Ok(())
# })
# }
```
This tries to extract `string_attr` from the attribute `name` and `string_in_mapping`
from a mapping with the key `"key"`. The arguments for `attribute` are restricted to
non-empty string literals while `item` can take any valid literal that implements
`ToBorrowedObject`.
You can use `#[pyo3(from_item_all)]` on a struct to extract every field with `get_item` method.
In this case, you can't use `#[pyo3(attribute)]` or barely use `#[pyo3(item)]` on any field.
However, using `#[pyo3(item("key"))]` to specify the key for a field is still allowed.
```rust
use pyo3::prelude::*;
#[derive(FromPyObject)]
#[pyo3(from_item_all)]
struct RustyStruct {
foo: String,
bar: String,
#[pyo3(item("foobar"))]
baz: String,
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let py_dict = py.eval(pyo3::ffi::c_str!("{'foo': 'foo', 'bar': 'bar', 'foobar': 'foobar'}"), None, None)?;
# let rustystruct: RustyStruct = py_dict.extract()?;
# assert_eq!(rustystruct.foo, "foo");
# assert_eq!(rustystruct.bar, "bar");
# assert_eq!(rustystruct.baz, "foobar");
#
# Ok(())
# })
# }
```
#### Deriving [`FromPyObject`] for tuple structs
Tuple structs are also supported but do not allow customizing the extraction. The input is
always assumed to be a Python tuple with the same length as the Rust type, the `n`th field
is extracted from the `n`th item in the Python tuple.
```rust
use pyo3::prelude::*;
#[derive(FromPyObject)]
struct RustyTuple(String, String);
# use pyo3::types::PyTuple;
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let tuple = PyTuple::new(py, vec!["test", "test2"])?;
#
# let rustytuple: RustyTuple = tuple.extract()?;
# assert_eq!(rustytuple.0, "test");
# assert_eq!(rustytuple.1, "test2");
#
# Ok(())
# })
# }
```
Tuple structs with a single field are treated as wrapper types which are described in the
following section. To override this behaviour and ensure that the input is in fact a tuple,
specify the struct as
```rust
use pyo3::prelude::*;
#[derive(FromPyObject)]
struct RustyTuple((String,));
# use pyo3::types::PyTuple;
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let tuple = PyTuple::new(py, vec!["test"])?;
#
# let rustytuple: RustyTuple = tuple.extract()?;
# assert_eq!((rustytuple.0).0, "test");
#
# Ok(())
# })
# }
```
#### Deriving [`FromPyObject`] for wrapper types
The `pyo3(transparent)` attribute can be used on structs with exactly one field. This results
in extracting directly from the input object, i.e. `obj.extract()`, rather than trying to access
an item or attribute. This behaviour is enabled per default for newtype structs and tuple-variants
with a single field.
```rust
use pyo3::prelude::*;
#[derive(FromPyObject)]
struct RustyTransparentTupleStruct(String);
#[derive(FromPyObject)]
#[pyo3(transparent)]
struct RustyTransparentStruct {
inner: String,
}
# use pyo3::types::PyString;
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let s = PyString::new(py, "test");
#
# let tup: RustyTransparentTupleStruct = s.extract()?;
# assert_eq!(tup.0, "test");
#
# let stru: RustyTransparentStruct = s.extract()?;
# assert_eq!(stru.inner, "test");
#
# Ok(())
# })
# }
```
#### Deriving [`FromPyObject`] for enums
The `FromPyObject` derivation for enums generates code that tries to extract the variants in the
order of the fields. As soon as a variant can be extracted successfully, that variant is returned.
This makes it possible to extract Python union types like `str | int`.
The same customizations and restrictions described for struct derivations apply to enum variants,
i.e. a tuple variant assumes that the input is a Python tuple, and a struct variant defaults to
extracting fields as attributes but can be configured in the same manner. The `transparent`
attribute can be applied to single-field-variants.
```rust
use pyo3::prelude::*;
use pyo3_ffi::c_str;
#[derive(FromPyObject)]
# #[derive(Debug)]
enum RustyEnum<'py> {
Int(usize), // input is a positive int
String(String), // input is a string
IntTuple(usize, usize), // input is a 2-tuple with positive ints
StringIntTuple(String, usize), // input is a 2-tuple with String and int
Coordinates3d {
// needs to be in front of 2d
x: usize,
y: usize,
z: usize,
},
Coordinates2d {
// only gets checked if the input did not have `z`
#[pyo3(attribute("x"))]
a: usize,
#[pyo3(attribute("y"))]
b: usize,
},
#[pyo3(transparent)]
CatchAll(Bound<'py, PyAny>), // This extraction never fails
}
#
# use pyo3::types::{PyBytes, PyString};
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# {
# let thing = 42_u8.into_pyobject(py)?;
# let rust_thing: RustyEnum<'_> = thing.extract()?;
#
# assert_eq!(
# 42,
# match rust_thing {
# RustyEnum::Int(i) => i,
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
# {
# let thing = PyString::new(py, "text");
# let rust_thing: RustyEnum<'_> = thing.extract()?;
#
# assert_eq!(
# "text",
# match rust_thing {
# RustyEnum::String(i) => i,
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
# {
# let thing = (32_u8, 73_u8).into_pyobject(py)?;
# let rust_thing: RustyEnum<'_> = thing.extract()?;
#
# assert_eq!(
# (32, 73),
# match rust_thing {
# RustyEnum::IntTuple(i, j) => (i, j),
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
# {
# let thing = ("foo", 73_u8).into_pyobject(py)?;
# let rust_thing: RustyEnum<'_> = thing.extract()?;
#
# assert_eq!(
# (String::from("foo"), 73),
# match rust_thing {
# RustyEnum::StringIntTuple(i, j) => (i, j),
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
# {
# let module = PyModule::from_code(
# py,
# c_str!("class Foo(dict):
# def __init__(self):
# self.x = 0
# self.y = 1
# self.z = 2"),
# c_str!(""),
# c_str!(""),
# )?;
#
# let class = module.getattr("Foo")?;
# let instance = class.call0()?;
# let rust_thing: RustyEnum<'_> = instance.extract()?;
#
# assert_eq!(
# (0, 1, 2),
# match rust_thing {
# RustyEnum::Coordinates3d { x, y, z } => (x, y, z),
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
#
# {
# let module = PyModule::from_code(
# py,
# c_str!("class Foo(dict):
# def __init__(self):
# self.x = 3
# self.y = 4"),
# c_str!(""),
# c_str!(""),
# )?;
#
# let class = module.getattr("Foo")?;
# let instance = class.call0()?;
# let rust_thing: RustyEnum<'_> = instance.extract()?;
#
# assert_eq!(
# (3, 4),
# match rust_thing {
# RustyEnum::Coordinates2d { a, b } => (a, b),
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
#
# {
# let thing = PyBytes::new(py, b"text");
# let rust_thing: RustyEnum<'_> = thing.extract()?;
#
# assert_eq!(
# b"text",
# match rust_thing {
# RustyEnum::CatchAll(ref i) => i.downcast::<PyBytes>()?.as_bytes(),
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
# Ok(())
# })
# }
```
If none of the enum variants match, a `PyTypeError` containing the names of the
tested variants is returned. The names reported in the error message can be customized
through the `#[pyo3(annotation = "name")]` attribute, e.g. to use conventional Python type
names:
```rust
use pyo3::prelude::*;
#[derive(FromPyObject)]
# #[derive(Debug)]
enum RustyEnum {
#[pyo3(transparent, annotation = "str")]
String(String),
#[pyo3(transparent, annotation = "int")]
Int(isize),
}
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# {
# let thing = 42_u8.into_pyobject(py)?;
# let rust_thing: RustyEnum = thing.extract()?;
#
# assert_eq!(
# 42,
# match rust_thing {
# RustyEnum::Int(i) => i,
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
#
# {
# let thing = "foo".into_pyobject(py)?;
# let rust_thing: RustyEnum = thing.extract()?;
#
# assert_eq!(
# "foo",
# match rust_thing {
# RustyEnum::String(i) => i,
# other => unreachable!("Error extracting: {:?}", other),
# }
# );
# }
#
# {
# let thing = b"foo".into_pyobject(py)?;
# let error = thing.extract::<RustyEnum>().unwrap_err();
# assert!(error.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
# }
#
# Ok(())
# })
# }
```
If the input is neither a string nor an integer, the error message will be:
`"'<INPUT_TYPE>' cannot be converted to 'str | int'"`.
#### `#[derive(FromPyObject)]` Container Attributes
- `pyo3(transparent)`
- extract the field directly from the object as `obj.extract()` instead of `get_item()` or
`getattr()`
- Newtype structs and tuple-variants are treated as transparent per default.
- only supported for single-field structs and enum variants
- `pyo3(annotation = "name")`
- changes the name of the failed variant in the generated error message in case of failure.
- e.g. `pyo3("int")` reports the variant's type as `int`.
- only supported for enum variants
#### `#[derive(FromPyObject)]` Field Attributes
- `pyo3(attribute)`, `pyo3(attribute("name"))`
- retrieve the field from an attribute, possibly with a custom name specified as an argument
- argument must be a string-literal.
- `pyo3(item)`, `pyo3(item("key"))`
- retrieve the field from a mapping, possibly with the custom key specified as an argument.
- can be any literal that implements `ToBorrowedObject`
- `pyo3(from_py_with = "...")`
- apply a custom function to convert the field from Python the desired Rust type.
- the argument must be the name of the function as a string.
- the function signature must be `fn(&Bound<PyAny>) -> PyResult<T>` where `T` is the Rust type of the argument.
### `IntoPyObject`
This trait defines the to-python conversion for a Rust type. All types in PyO3 implement this trait,
as does a `#[pyclass]` which doesn't use `extends`.
Occasionally you may choose to implement this for custom types which are mapped to Python types
_without_ having a unique python type.
#### derive macro
`IntoPyObject` can be implemented using our derive macro. Both `struct`s and `enum`s are supported.
`struct`s will turn into a `PyDict` using the field names as keys, tuple `struct`s will turn convert
into `PyTuple` with the fields in declaration order.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use std::collections::HashMap;
# use std::hash::Hash;
// structs convert into `PyDict` with field names as keys
#[derive(IntoPyObject)]
struct Struct {
count: usize,
obj: Py<PyAny>,
}
// tuple structs convert into `PyTuple`
// lifetimes and generics are supported, the impl will be bounded by
// `K: IntoPyObject, V: IntoPyObject`
#[derive(IntoPyObject)]
struct Tuple<'a, K: Hash + Eq, V>(&'a str, HashMap<K, V>);
```
For structs with a single field (newtype pattern) the `#[pyo3(transparent)]` option can be used to
forward the implementation to the inner type.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
// newtype tuple structs are implicitly `transparent`
#[derive(IntoPyObject)]
struct TransparentTuple(PyObject);
#[derive(IntoPyObject)]
#[pyo3(transparent)]
struct TransparentStruct<'py> {
inner: Bound<'py, PyAny>, // `'py` lifetime will be used as the Python lifetime
}
```
For `enum`s each variant is converted according to the rules for `struct`s above.
```rust
# #![allow(dead_code)]
# use pyo3::prelude::*;
# use std::collections::HashMap;
# use std::hash::Hash;
#[derive(IntoPyObject)]
enum Enum<'a, 'py, K: Hash + Eq, V> { // enums are supported and convert using the same
TransparentTuple(PyObject), // rules on the variants as the structs above
#[pyo3(transparent)]
TransparentStruct { inner: Bound<'py, PyAny> },
Tuple(&'a str, HashMap<K, V>),
Struct { count: usize, obj: Py<PyAny> }
}
```
Additionally `IntoPyObject` can be derived for a reference to a struct or enum using the
`IntoPyObjectRef` derive macro. All the same rules from above apply as well.
#### manual implementation
If the derive macro is not suitable for your use case, `IntoPyObject` can be implemented manually as
demonstrated below.
```rust
# use pyo3::prelude::*;
# #[allow(dead_code)]
struct MyPyObjectWrapper(PyObject);
impl<'py> IntoPyObject<'py> for MyPyObjectWrapper {
type Target = PyAny; // the Python type
type Output = Bound<'py, Self::Target>; // in most cases this will be `Bound`
type Error = std::convert::Infallible; // the conversion error type, has to be convertable to `PyErr`
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(self.0.into_bound(py))
}
}
// equivalent to former `ToPyObject` implementations
impl<'a, 'py> IntoPyObject<'py> for &'a MyPyObjectWrapper {
type Target = PyAny;
type Output = Borrowed<'a, 'py, Self::Target>; // `Borrowed` can be used to optimized reference counting
type Error = std::convert::Infallible;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(self.0.bind_borrowed(py))
}
}
```
### `IntoPy<T>`
<div class="warning">
⚠️ Warning: API update in progress 🛠️
PyO3 0.23 has introduced `IntoPyObject` as the new trait for to-python conversions. While `#[pymethods]` and `#[pyfunction]` contain a compatibility layer to allow `IntoPy<PyObject>` as a return type, all Python API have been migrated to use `IntoPyObject`. To migrate implement `IntoPyObject` for your type.
</div>
This trait defines the to-python conversion for a Rust type. It is usually implemented as
`IntoPy<PyObject>`, which is the trait needed for returning a value from `#[pyfunction]` and
`#[pymethods]`.
All types in PyO3 implement this trait, as does a `#[pyclass]` which doesn't use `extends`.
Occasionally you may choose to implement this for custom types which are mapped to Python types
_without_ having a unique python type.
```rust
use pyo3::prelude::*;
# #[allow(dead_code)]
struct MyPyObjectWrapper(PyObject);
#[allow(deprecated)]
impl IntoPy<PyObject> for MyPyObjectWrapper {
fn into_py(self, py: Python<'_>) -> PyObject {
self.0
}
}
```
### The `ToPyObject` trait
<div class="warning">
⚠️ Warning: API update in progress 🛠️
PyO3 0.23 has introduced `IntoPyObject` as the new trait for to-python conversions. To migrate
implement `IntoPyObject` on a referece of your type (`impl<'py> IntoPyObject<'py> for &Type { ... }`).
</div>
[`ToPyObject`] is a conversion trait that allows various objects to be
converted into [`PyObject`]. `IntoPy<PyObject>` serves the
same purpose, except that it consumes `self`.
[`IntoPy`]: {{#PYO3_DOCS_URL}}/pyo3/conversion/trait.IntoPy.html
[`FromPyObject`]: {{#PYO3_DOCS_URL}}/pyo3/conversion/trait.FromPyObject.html
[`ToPyObject`]: {{#PYO3_DOCS_URL}}/pyo3/conversion/trait.ToPyObject.html
[`PyObject`]: {{#PYO3_DOCS_URL}}/pyo3/type.PyObject.html
[`PyRef`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyRef.html
[`PyRefMut`]: {{#PYO3_DOCS_URL}}/pyo3/pycell/struct.PyRefMut.html
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/emscripten/Makefile | CURDIR=$(abspath .)
# These three are passed in from nox.
BUILDROOT ?= $(CURDIR)/builddir
PYMAJORMINORMICRO ?= 3.11.0
EMSCRIPTEN_VERSION=3.1.13
export EMSDKDIR = $(BUILDROOT)/emsdk
PLATFORM=wasm32_emscripten
SYSCONFIGDATA_NAME=_sysconfigdata__$(PLATFORM)
# BASH_ENV tells bash to source emsdk_env.sh on startup.
export BASH_ENV := $(CURDIR)/env.sh
# Use bash to run each command so that env.sh will be used.
SHELL := /bin/bash
# Set version variables.
version_tuple := $(subst ., ,$(PYMAJORMINORMICRO:v%=%))
PYMAJOR=$(word 1,$(version_tuple))
PYMINOR=$(word 2,$(version_tuple))
PYMICRO=$(word 3,$(version_tuple))
PYVERSION=$(PYMAJORMINORMICRO)
PYMAJORMINOR=$(PYMAJOR).$(PYMINOR)
PYTHONURL=https://www.python.org/ftp/python/$(PYMAJORMINORMICRO)/Python-$(PYVERSION).tgz
PYTHONTARBALL=$(BUILDROOT)/downloads/Python-$(PYVERSION).tgz
PYTHONBUILD=$(BUILDROOT)/build/Python-$(PYVERSION)
PYTHONLIBDIR=$(BUILDROOT)/install/Python-$(PYVERSION)/lib
all: $(PYTHONLIBDIR)/libpython$(PYMAJORMINOR).a
$(BUILDROOT)/.exists:
mkdir -p $(BUILDROOT)
touch $@
# Install emscripten
$(EMSDKDIR): $(CURDIR)/emscripten_patches/* $(BUILDROOT)/.exists
git clone https://github.com/emscripten-core/emsdk.git --depth 1 --branch $(EMSCRIPTEN_VERSION) $(EMSDKDIR)
$(EMSDKDIR)/emsdk install $(EMSCRIPTEN_VERSION)
cd $(EMSDKDIR)/upstream/emscripten && cat $(CURDIR)/emscripten_patches/* | patch -p1
$(EMSDKDIR)/emsdk activate $(EMSCRIPTEN_VERSION)
$(PYTHONTARBALL):
[ -d $(BUILDROOT)/downloads ] || mkdir -p $(BUILDROOT)/downloads
wget -q -O $@ $(PYTHONURL)
$(PYTHONBUILD)/.patched: $(PYTHONTARBALL)
[ -d $(PYTHONBUILD) ] || ( \
mkdir -p $(dir $(PYTHONBUILD));\
tar -C $(dir $(PYTHONBUILD)) -xf $(PYTHONTARBALL) \
)
touch $@
$(PYTHONBUILD)/Makefile: $(PYTHONBUILD)/.patched $(BUILDROOT)/emsdk
cd $(PYTHONBUILD) && \
CONFIG_SITE=Tools/wasm/config.site-wasm32-emscripten \
emconfigure ./configure -C \
--host=wasm32-unknown-emscripten \
--build=$(shell $(PYTHONBUILD)/config.guess) \
--with-emscripten-target=browser \
--enable-wasm-dynamic-linking \
--with-build-python=python3.11
$(PYTHONLIBDIR)/libpython$(PYMAJORMINOR).a : $(PYTHONBUILD)/Makefile
cd $(PYTHONBUILD) && \
emmake make -j3 libpython$(PYMAJORMINOR).a
# Generate sysconfigdata
_PYTHON_SYSCONFIGDATA_NAME=$(SYSCONFIGDATA_NAME) _PYTHON_PROJECT_BASE=$(PYTHONBUILD) python3.11 -m sysconfig --generate-posix-vars
cp `cat pybuilddir.txt`/$(SYSCONFIGDATA_NAME).py $(PYTHONBUILD)/Lib
mkdir -p $(PYTHONLIBDIR)
# Copy libexpat.a, libmpdec.a, and libpython3.11.a
# In noxfile, we explicitly link libexpat and libmpdec via RUSTFLAGS
find $(PYTHONBUILD) -name '*.a' -exec cp {} $(PYTHONLIBDIR) \;
# Install Python stdlib
cp -r $(PYTHONBUILD)/Lib $(PYTHONLIBDIR)/python$(PYMAJORMINOR)
clean:
rm -rf $(BUILDROOT)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/emscripten/runner.py | #!/usr/local/bin/python
import pathlib
import sys
import subprocess
p = pathlib.Path(sys.argv[1])
sys.exit(subprocess.call(["node", p.name], cwd=p.parent))
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/emscripten/env.sh | #!/bin/bash
# Activate emsdk environment. emsdk_env.sh writes a lot to stderr so we suppress
# the output. This also prevents it from complaining when emscripten isn't yet
# installed.
source "$EMSDKDIR/emsdk_env.sh" 2> /dev/null || true
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/emscripten | lc_public_repos/langsmith-sdk/vendor/pyo3/emscripten/emscripten_patches/0001-Add-_gxx_personality_v0-stub-to-library.js.patch | From 4b56f37c3dc9185a235a8314086c4d7a6239b2f8 Mon Sep 17 00:00:00 2001
From: Hood Chatham <roberthoodchatham@gmail.com>
Date: Sat, 4 Jun 2022 19:19:47 -0700
Subject: [PATCH] Add _gxx_personality_v0 stub to library.js
Mitigation for an incompatibility between Rust and Emscripten:
https://github.com/rust-lang/rust/issues/85821
https://github.com/emscripten-core/emscripten/issues/17128
---
src/library.js | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/library.js b/src/library.js
index e7bb4c38e..7d01744df 100644
--- a/src/library.js
+++ b/src/library.js
@@ -403,6 +403,8 @@ mergeInto(LibraryManager.library, {
abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
},
+ __gxx_personality_v0: function() {},
+
// ==========================================================================
// time.h
// ==========================================================================
--
2.25.1
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/assets/script.py | # Used in PyModule examples.
class Blah:
pass
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4351.added.md | Added `as_super` and `into_super` methods for `Bound<T: PyClass>`. |
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4497.changed.md | The `abi3` feature will now override config files provided via `PYO3_BUILD_CONFIG`.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4322.removed.md | Remove all functionality deprecated in PyO3 0.20.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4447.fixed.md | Fix FFI definition `Py_Is` for PyPy on 3.10 to call the function defined by PyPy.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4661.changed.md | `PyMapping`'s `keys`, `values` and `items` methods return `PyList` instead of `PySequence`. |
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4347.changed.md | Deprecate `PyLong` in favor of `PyInt`.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/newsfragments/4611.changed.md | `PyNativeTypeInitializer` and `PyObjectInit` are moved into `impl_`. `PyObjectInit` is now a Sealed trait
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.