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/examples/word-count
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/word-count/.template/Cargo.toml
[package] authors = ["{{authors}}"] name = "{{project-name}}" version = "0.1.0" edition = "2021" [lib] name = "word_count" crate-type = ["cdylib"] [dependencies] pyo3 = { version = "{{PYO3_VERSION}}", features = ["extension-module"] } rayon = "1.0.2"
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/word-count
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/word-count/.template/pyproject.toml
[build-system] requires = ["maturin>=1,<2"] build-backend = "maturin" [project] name = "{{project-name}}" version = "0.1.0" [project.optional-dependencies] dev = ["pytest"] [tool.pytest.ini_options] addopts = "--benchmark-disable"
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/word-count
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/word-count/.template/pre-script.rhai
variable::set("PYO3_VERSION", "0.22.5"); file::rename(".template/Cargo.toml", "Cargo.toml"); file::rename(".template/pyproject.toml", "pyproject.toml"); file::delete(".template");
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/noxfile.py
import nox @nox.session def python(session: nox.Session): session.env["MATURIN_PEP517_ARGS"] = "--profile=dev" session.install(".[dev]") session.run("pytest")
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/Cargo.toml
[package] name = "decorator" version = "0.1.0" edition = "2021" [lib] name = "decorator" crate-type = ["cdylib"] [dependencies] pyo3 = { path = "../../", features = ["extension-module"] } [workspace]
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/MANIFEST.in
include pyproject.toml Cargo.toml recursive-include src *
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/README.md
# decorator A project showcasing the example from the [Emulating callable objects](https://pyo3.rs/latest/class/call.html) chapter of the guide. ## Building and Testing To build this package, first install `maturin`: ```shell pip install maturin ``` To build and test use `maturin develop`: ```shell pip install -r requirements-dev.txt maturin develop pytest ``` Alternatively, install nox and run the tests inside an isolated environment: ```shell nox ``` ## Copying this example Use [`cargo-generate`](https://crates.io/crates/cargo-generate): ```bash $ cargo install cargo-generate $ cargo generate --git https://github.com/PyO3/pyo3 examples/decorator ``` (`cargo generate` will take a little while to clone the PyO3 repo first; be patient when waiting for the command to run.)
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/pyproject.toml
[build-system] requires = ["maturin>=1,<2"] build-backend = "maturin" [project] name = "decorator" version = "0.1.0" classifiers = [ "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Rust", "Operating System :: POSIX", "Operating System :: MacOS :: MacOS X", ] [project.optional-dependencies] dev = ["pytest"]
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/cargo-generate.toml
[template] ignore = [".nox"] [hooks] pre = [".template/pre-script.rhai"]
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/tests/test_.py
from decorator import Counter def test_no_args(): @Counter def say_hello(): print("hello") say_hello() say_hello() say_hello() say_hello() assert say_hello.count == 4 def test_arg(): @Counter def say_hello(name): print(f"hello {name}") say_hello("a") say_hello("b") say_hello("c") say_hello("d") assert say_hello.count == 4 def test_default_arg(): @Counter def say_hello(name="default"): print(f"hello {name}") say_hello("a") say_hello() say_hello("c") say_hello() assert say_hello.count == 4 # https://github.com/PyO3/pyo3/discussions/2598 def test_discussion_2598(): @Counter def say_hello(): if say_hello.count < 2: print("hello from decorator") say_hello() say_hello()
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/tests/example.py
from decorator import Counter @Counter def say_hello(): print("hello") say_hello() say_hello() say_hello() say_hello() assert say_hello.count == 4
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/src/lib.rs
use pyo3::prelude::*; use pyo3::types::{PyDict, PyTuple}; use std::sync::atomic::{AtomicU64, Ordering}; /// A function decorator that keeps track how often it is called. /// /// It otherwise doesn't do anything special. #[pyclass(name = "Counter")] pub struct PyCounter { // Keeps track of how many calls have gone through. // // See the discussion at the end for why `AtomicU64` is used. count: AtomicU64, // This is the actual function being wrapped. wraps: Py<PyAny>, } #[pymethods] impl PyCounter { // Note that we don't validate whether `wraps` is actually callable. // // While we could use `PyAny::is_callable` for that, it has some flaws: // 1. It doesn't guarantee the object can actually be called successfully // 2. We still need to handle any exceptions that the function might raise #[new] fn __new__(wraps: Py<PyAny>) -> Self { PyCounter { count: AtomicU64::new(0), wraps, } } #[getter] fn count(&self) -> u64 { self.count.load(Ordering::Relaxed) } #[pyo3(signature = (*args, **kwargs))] fn __call__( &self, py: Python<'_>, args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<Py<PyAny>> { let new_count = self.count.fetch_add(1, Ordering::Relaxed); let name = self.wraps.getattr(py, "__name__")?; println!("{} has been called {} time(s).", name, new_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) } } #[pymodule] pub fn decorator(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_class::<PyCounter>()?; Ok(()) }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/.template/Cargo.toml
[package] authors = ["{{authors}}"] name = "{{project-name}}" version = "0.1.0" edition = "2021" [lib] name = "decorator" crate-type = ["cdylib"] [dependencies] pyo3 = { version = "{{PYO3_VERSION}}", features = ["extension-module"] }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/.template/pyproject.toml
[build-system] requires = ["maturin>=1,<2"] build-backend = "maturin" [project] name = "{{project-name}}" version = "0.1.0" [project.optional-dependencies] dev = ["pytest"]
0
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator
lc_public_repos/langsmith-sdk/vendor/pyo3/examples/decorator/.template/pre-script.rhai
variable::set("PYO3_VERSION", "0.22.5"); file::rename(".template/Cargo.toml", "Cargo.toml"); file::rename(".template/pyproject.toml", "pyproject.toml"); file::delete(".template");
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pycell.rs
//! PyO3's interior mutability primitive. //! //! Rust has strict aliasing rules - you can either have any number of immutable (shared) references or one mutable //! reference. Python's ownership model is the complete opposite of that - any Python object //! can be referenced any number of times, and mutation is allowed from any reference. //! //! PyO3 deals with these differences by employing the [Interior Mutability] //! pattern. This requires that PyO3 enforces the borrowing rules and it has two mechanisms for //! doing so: //! - Statically it can enforce threadsafe access with the [`Python<'py>`](crate::Python) token. //! All Rust code holding that token, or anything derived from it, can assume that they have //! safe access to the Python interpreter's state. For this reason all the native Python objects //! can be mutated through shared references. //! - However, methods and functions in Rust usually *do* need `&mut` references. While PyO3 can //! use the [`Python<'py>`](crate::Python) token to guarantee thread-safe access to them, it cannot //! statically guarantee uniqueness of `&mut` references. As such those references have to be tracked //! dynamically at runtime, using `PyCell` and the other types defined in this module. This works //! similar to std's [`RefCell`](std::cell::RefCell) type. //! //! # When *not* to use PyCell //! //! Usually you can use `&mut` references as method and function receivers and arguments, and you //! won't need to use `PyCell` directly: //! //! ```rust //! use pyo3::prelude::*; //! //! #[pyclass] //! struct Number { //! inner: u32, //! } //! //! #[pymethods] //! impl Number { //! fn increment(&mut self) { //! self.inner += 1; //! } //! } //! ``` //! //! The [`#[pymethods]`](crate::pymethods) proc macro will generate this wrapper function (and more), //! using `PyCell` under the hood: //! //! ```rust,ignore //! # use pyo3::prelude::*; //! # #[pyclass] //! # struct Number { //! # inner: u32, //! # } //! # //! # #[pymethods] //! # impl Number { //! # fn increment(&mut self) { //! # self.inner += 1; //! # } //! # } //! # //! // The function which is exported to Python looks roughly like the following //! unsafe extern "C" fn __pymethod_increment__( //! _slf: *mut pyo3::ffi::PyObject, //! _args: *mut pyo3::ffi::PyObject, //! ) -> *mut pyo3::ffi::PyObject { //! use :: pyo3 as _pyo3; //! _pyo3::impl_::trampoline::noargs(_slf, _args, |py, _slf| { //! # #[allow(deprecated)] //! let _cell = py //! .from_borrowed_ptr::<_pyo3::PyAny>(_slf) //! .downcast::<_pyo3::PyCell<Number>>()?; //! let mut _ref = _cell.try_borrow_mut()?; //! let _slf: &mut Number = &mut *_ref; //! _pyo3::impl_::callback::convert(py, Number::increment(_slf)) //! }) //! } //! ``` //! //! # When to use PyCell //! ## Using pyclasses from Rust //! //! However, we *do* need `PyCell` if we want to call its methods from Rust: //! ```rust //! # use pyo3::prelude::*; //! # //! # #[pyclass] //! # struct Number { //! # inner: u32, //! # } //! # //! # #[pymethods] //! # impl Number { //! # fn increment(&mut self) { //! # self.inner += 1; //! # } //! # } //! # fn main() -> PyResult<()> { //! Python::with_gil(|py| { //! let n = Py::new(py, Number { inner: 0 })?; //! //! // We borrow the guard and then dereference //! // it to get a mutable reference to Number //! let mut guard: PyRefMut<'_, Number> = n.bind(py).borrow_mut(); //! let n_mutable: &mut Number = &mut *guard; //! //! n_mutable.increment(); //! //! // To avoid panics we must dispose of the //! // `PyRefMut` before borrowing again. //! drop(guard); //! //! let n_immutable: &Number = &n.bind(py).borrow(); //! assert_eq!(n_immutable.inner, 1); //! //! Ok(()) //! }) //! # } //! ``` //! ## Dealing with possibly overlapping mutable references //! //! It is also necessary to use `PyCell` if you can receive mutable arguments that may overlap. //! Suppose the following function that swaps the values of two `Number`s: //! ``` //! # use pyo3::prelude::*; //! # #[pyclass] //! # pub struct Number { //! # inner: u32, //! # } //! #[pyfunction] //! fn swap_numbers(a: &mut Number, b: &mut Number) { //! std::mem::swap(&mut a.inner, &mut b.inner); //! } //! # fn main() { //! # Python::with_gil(|py| { //! # let n = Py::new(py, Number{inner: 35}).unwrap(); //! # let n2 = n.clone_ref(py); //! # assert!(n.is(&n2)); //! # let fun = pyo3::wrap_pyfunction!(swap_numbers, py).unwrap(); //! # fun.call1((n, n2)).expect_err("Managed to create overlapping mutable references. Note: this is undefined behaviour."); //! # }); //! # } //! ``` //! When users pass in the same `Number` as both arguments, one of the mutable borrows will //! fail and raise a `RuntimeError`: //! ```text //! >>> a = Number() //! >>> swap_numbers(a, a) //! Traceback (most recent call last): //! File "<stdin>", line 1, in <module> //! RuntimeError: Already borrowed //! ``` //! //! It is better to write that function like this: //! ```rust,ignore //! # #![allow(deprecated)] //! # use pyo3::prelude::*; //! # #[pyclass] //! # pub struct Number { //! # inner: u32, //! # } //! #[pyfunction] //! fn swap_numbers(a: &PyCell<Number>, b: &PyCell<Number>) { //! // Check that the pointers are unequal //! if !a.is(b) { //! std::mem::swap(&mut a.borrow_mut().inner, &mut b.borrow_mut().inner); //! } else { //! // Do nothing - they are the same object, so don't need swapping. //! } //! } //! # fn main() { //! # // With duplicate numbers //! # Python::with_gil(|py| { //! # let n = Py::new(py, Number{inner: 35}).unwrap(); //! # let n2 = n.clone_ref(py); //! # assert!(n.is(&n2)); //! # let fun = pyo3::wrap_pyfunction!(swap_numbers, py).unwrap(); //! # fun.call1((n, n2)).unwrap(); //! # }); //! # //! # // With two different numbers //! # Python::with_gil(|py| { //! # let n = Py::new(py, Number{inner: 35}).unwrap(); //! # let n2 = Py::new(py, Number{inner: 42}).unwrap(); //! # assert!(!n.is(&n2)); //! # let fun = pyo3::wrap_pyfunction!(swap_numbers, py).unwrap(); //! # fun.call1((&n, &n2)).unwrap(); //! # let n: u32 = n.borrow(py).inner; //! # let n2: u32 = n2.borrow(py).inner; //! # assert_eq!(n, 42); //! # assert_eq!(n2, 35); //! # }); //! # } //! ``` //! See the [guide] for more information. //! //! [guide]: https://pyo3.rs/latest/class.html#pycell-and-interior-mutability "PyCell and interior mutability" //! [Interior Mutability]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html "RefCell<T> and the Interior Mutability Pattern - The Rust Programming Language" use crate::conversion::{AsPyPointer, IntoPyObject}; use crate::exceptions::PyRuntimeError; use crate::ffi_ptr_ext::FfiPtrExt; use crate::internal_tricks::{ptr_from_mut, ptr_from_ref}; use crate::pyclass::{boolean_struct::False, PyClass}; use crate::types::any::PyAnyMethods; #[allow(deprecated)] use crate::IntoPy; use crate::{ffi, Borrowed, Bound, PyErr, PyObject, Python}; use std::convert::Infallible; use std::fmt; use std::mem::ManuallyDrop; use std::ops::{Deref, DerefMut}; pub(crate) mod impl_; use impl_::{PyClassBorrowChecker, PyClassObjectLayout}; /// A wrapper type for an immutably borrowed value from a [`Bound<'py, T>`]. /// /// See the [`Bound`] documentation for more information. /// /// # Examples /// /// You can use [`PyRef`] as an alternative to a `&self` receiver when /// - you need to access the pointer of the [`Bound`], or /// - you want to get a super class. /// ``` /// # use pyo3::prelude::*; /// #[pyclass(subclass)] /// struct Parent { /// basename: &'static str, /// } /// /// #[pyclass(extends=Parent)] /// struct Child { /// name: &'static str, /// } /// /// #[pymethods] /// impl Child { /// #[new] /// fn new() -> (Self, Parent) { /// (Child { name: "Caterpillar" }, Parent { basename: "Butterfly" }) /// } /// /// fn format(slf: PyRef<'_, Self>) -> String { /// // We can get *mut ffi::PyObject from PyRef /// let refcnt = unsafe { pyo3::ffi::Py_REFCNT(slf.as_ptr()) }; /// // We can get &Self::BaseType by as_ref /// let basename = slf.as_ref().basename; /// format!("{}(base: {}, cnt: {})", slf.name, basename, refcnt) /// } /// } /// # Python::with_gil(|py| { /// # let sub = Py::new(py, Child::new()).unwrap(); /// # pyo3::py_run!(py, sub, "assert sub.format() == 'Caterpillar(base: Butterfly, cnt: 4)', sub.format()"); /// # }); /// ``` /// /// See the [module-level documentation](self) for more information. #[repr(transparent)] pub struct PyRef<'p, T: PyClass> { // TODO: once the GIL Ref API is removed, consider adding a lifetime parameter to `PyRef` to // store `Borrowed` here instead, avoiding reference counting overhead. inner: Bound<'p, T>, } impl<'p, T: PyClass> PyRef<'p, T> { /// Returns a `Python` token that is bound to the lifetime of the `PyRef`. pub fn py(&self) -> Python<'p> { self.inner.py() } } impl<T, U> AsRef<U> for PyRef<'_, T> where T: PyClass<BaseType = U>, U: PyClass, { fn as_ref(&self) -> &T::BaseType { self.as_super() } } impl<'py, T: PyClass> PyRef<'py, T> { /// Returns the raw FFI pointer represented by self. /// /// # Safety /// /// Callers are responsible for ensuring that the pointer does not outlive self. /// /// The reference is borrowed; callers should not decrease the reference count /// when they are finished with the pointer. #[inline] pub fn as_ptr(&self) -> *mut ffi::PyObject { self.inner.as_ptr() } /// Returns an owned raw FFI pointer represented by self. /// /// # Safety /// /// The reference is owned; when finished the caller should either transfer ownership /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)). #[inline] pub fn into_ptr(self) -> *mut ffi::PyObject { self.inner.clone().into_ptr() } #[track_caller] pub(crate) fn borrow(obj: &Bound<'py, T>) -> Self { Self::try_borrow(obj).expect("Already mutably borrowed") } pub(crate) fn try_borrow(obj: &Bound<'py, T>) -> Result<Self, PyBorrowError> { let cell = obj.get_class_object(); cell.ensure_threadsafe(); cell.borrow_checker() .try_borrow() .map(|_| Self { inner: obj.clone() }) } } impl<'p, T, U> PyRef<'p, T> where T: PyClass<BaseType = U>, U: PyClass, { /// Gets a `PyRef<T::BaseType>`. /// /// While `as_ref()` returns a reference of type `&T::BaseType`, this cannot be /// used to get the base of `T::BaseType`. /// /// But with the help of this method, you can get hold of instances of the /// super-superclass when needed. /// /// # Examples /// ``` /// # use pyo3::prelude::*; /// #[pyclass(subclass)] /// struct Base1 { /// name1: &'static str, /// } /// /// #[pyclass(extends=Base1, subclass)] /// struct Base2 { /// name2: &'static str, /// } /// /// #[pyclass(extends=Base2)] /// struct Sub { /// name3: &'static str, /// } /// /// #[pymethods] /// impl Sub { /// #[new] /// fn new() -> PyClassInitializer<Self> { /// PyClassInitializer::from(Base1 { name1: "base1" }) /// .add_subclass(Base2 { name2: "base2" }) /// .add_subclass(Self { name3: "sub" }) /// } /// fn name(slf: PyRef<'_, Self>) -> String { /// let subname = slf.name3; /// let super_ = slf.into_super(); /// format!("{} {} {}", super_.as_ref().name1, super_.name2, subname) /// } /// } /// # Python::with_gil(|py| { /// # let sub = Py::new(py, Sub::new()).unwrap(); /// # pyo3::py_run!(py, sub, "assert sub.name() == 'base1 base2 sub'") /// # }); /// ``` pub fn into_super(self) -> PyRef<'p, U> { let py = self.py(); PyRef { inner: unsafe { ManuallyDrop::new(self) .as_ptr() .assume_owned_unchecked(py) .downcast_into_unchecked() }, } } /// Borrows a shared reference to `PyRef<T::BaseType>`. /// /// With the help of this method, you can access attributes and call methods /// on the superclass without consuming the `PyRef<T>`. This method can also /// be chained to access the super-superclass (and so on). /// /// # Examples /// ``` /// # use pyo3::prelude::*; /// #[pyclass(subclass)] /// struct Base { /// base_name: &'static str, /// } /// #[pymethods] /// impl Base { /// fn base_name_len(&self) -> usize { /// self.base_name.len() /// } /// } /// /// #[pyclass(extends=Base)] /// struct Sub { /// sub_name: &'static str, /// } /// /// #[pymethods] /// impl Sub { /// #[new] /// fn new() -> (Self, Base) { /// (Self { sub_name: "sub_name" }, Base { base_name: "base_name" }) /// } /// fn sub_name_len(&self) -> usize { /// self.sub_name.len() /// } /// fn format_name_lengths(slf: PyRef<'_, Self>) -> String { /// format!("{} {}", slf.as_super().base_name_len(), slf.sub_name_len()) /// } /// } /// # Python::with_gil(|py| { /// # let sub = Py::new(py, Sub::new()).unwrap(); /// # pyo3::py_run!(py, sub, "assert sub.format_name_lengths() == '9 8'") /// # }); /// ``` pub fn as_super(&self) -> &PyRef<'p, U> { let ptr = ptr_from_ref::<Bound<'p, T>>(&self.inner) // `Bound<T>` has the same layout as `Bound<T::BaseType>` .cast::<Bound<'p, T::BaseType>>() // `Bound<T::BaseType>` has the same layout as `PyRef<T::BaseType>` .cast::<PyRef<'p, T::BaseType>>(); unsafe { &*ptr } } } impl<T: PyClass> Deref for PyRef<'_, T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.inner.get_class_object().get_ptr() } } } impl<T: PyClass> Drop for PyRef<'_, T> { fn drop(&mut self) { self.inner .get_class_object() .borrow_checker() .release_borrow() } } #[allow(deprecated)] impl<T: PyClass> IntoPy<PyObject> for PyRef<'_, T> { fn into_py(self, py: Python<'_>) -> PyObject { unsafe { PyObject::from_borrowed_ptr(py, self.inner.as_ptr()) } } } #[allow(deprecated)] impl<T: PyClass> IntoPy<PyObject> for &'_ PyRef<'_, T> { fn into_py(self, py: Python<'_>) -> PyObject { unsafe { PyObject::from_borrowed_ptr(py, self.inner.as_ptr()) } } } impl<'py, T: PyClass> IntoPyObject<'py> for PyRef<'py, T> { type Target = T; type Output = Bound<'py, T>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.inner.clone()) } } impl<'a, 'py, T: PyClass> IntoPyObject<'py> for &'a PyRef<'py, T> { type Target = T; type Output = Borrowed<'a, 'py, T>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.inner.as_borrowed()) } } unsafe impl<T: PyClass> AsPyPointer for PyRef<'_, T> { fn as_ptr(&self) -> *mut ffi::PyObject { self.inner.as_ptr() } } impl<T: PyClass + fmt::Debug> fmt::Debug for PyRef<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } /// A wrapper type for a mutably borrowed value from a [`Bound<'py, T>`]. /// /// See the [module-level documentation](self) for more information. #[repr(transparent)] pub struct PyRefMut<'p, T: PyClass<Frozen = False>> { // TODO: once the GIL Ref API is removed, consider adding a lifetime parameter to `PyRef` to // store `Borrowed` here instead, avoiding reference counting overhead. inner: Bound<'p, T>, } impl<'p, T: PyClass<Frozen = False>> PyRefMut<'p, T> { /// Returns a `Python` token that is bound to the lifetime of the `PyRefMut`. pub fn py(&self) -> Python<'p> { self.inner.py() } } impl<T, U> AsRef<U> for PyRefMut<'_, T> where T: PyClass<BaseType = U, Frozen = False>, U: PyClass<Frozen = False>, { fn as_ref(&self) -> &T::BaseType { PyRefMut::downgrade(self).as_super() } } impl<T, U> AsMut<U> for PyRefMut<'_, T> where T: PyClass<BaseType = U, Frozen = False>, U: PyClass<Frozen = False>, { fn as_mut(&mut self) -> &mut T::BaseType { self.as_super() } } impl<'py, T: PyClass<Frozen = False>> PyRefMut<'py, T> { /// Returns the raw FFI pointer represented by self. /// /// # Safety /// /// Callers are responsible for ensuring that the pointer does not outlive self. /// /// The reference is borrowed; callers should not decrease the reference count /// when they are finished with the pointer. #[inline] pub fn as_ptr(&self) -> *mut ffi::PyObject { self.inner.as_ptr() } /// Returns an owned raw FFI pointer represented by self. /// /// # Safety /// /// The reference is owned; when finished the caller should either transfer ownership /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)). #[inline] pub fn into_ptr(self) -> *mut ffi::PyObject { self.inner.clone().into_ptr() } #[inline] #[track_caller] pub(crate) fn borrow(obj: &Bound<'py, T>) -> Self { Self::try_borrow(obj).expect("Already borrowed") } pub(crate) fn try_borrow(obj: &Bound<'py, T>) -> Result<Self, PyBorrowMutError> { let cell = obj.get_class_object(); cell.ensure_threadsafe(); cell.borrow_checker() .try_borrow_mut() .map(|_| Self { inner: obj.clone() }) } pub(crate) fn downgrade(slf: &Self) -> &PyRef<'py, T> { // `PyRefMut<T>` and `PyRef<T>` have the same layout unsafe { &*ptr_from_ref(slf).cast() } } } impl<'p, T, U> PyRefMut<'p, T> where T: PyClass<BaseType = U, Frozen = False>, U: PyClass<Frozen = False>, { /// Gets a `PyRef<T::BaseType>`. /// /// See [`PyRef::into_super`] for more. pub fn into_super(self) -> PyRefMut<'p, U> { let py = self.py(); PyRefMut { inner: unsafe { ManuallyDrop::new(self) .as_ptr() .assume_owned_unchecked(py) .downcast_into_unchecked() }, } } /// Borrows a mutable reference to `PyRefMut<T::BaseType>`. /// /// With the help of this method, you can mutate attributes and call mutating /// methods on the superclass without consuming the `PyRefMut<T>`. This method /// can also be chained to access the super-superclass (and so on). /// /// See [`PyRef::as_super`] for more. pub fn as_super(&mut self) -> &mut PyRefMut<'p, U> { let ptr = ptr_from_mut::<Bound<'p, T>>(&mut self.inner) // `Bound<T>` has the same layout as `Bound<T::BaseType>` .cast::<Bound<'p, T::BaseType>>() // `Bound<T::BaseType>` has the same layout as `PyRefMut<T::BaseType>`, // and the mutable borrow on `self` prevents aliasing .cast::<PyRefMut<'p, T::BaseType>>(); unsafe { &mut *ptr } } } impl<T: PyClass<Frozen = False>> Deref for PyRefMut<'_, T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.inner.get_class_object().get_ptr() } } } impl<T: PyClass<Frozen = False>> DerefMut for PyRefMut<'_, T> { #[inline] fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.inner.get_class_object().get_ptr() } } } impl<T: PyClass<Frozen = False>> Drop for PyRefMut<'_, T> { fn drop(&mut self) { self.inner .get_class_object() .borrow_checker() .release_borrow_mut() } } #[allow(deprecated)] impl<T: PyClass<Frozen = False>> IntoPy<PyObject> for PyRefMut<'_, T> { fn into_py(self, py: Python<'_>) -> PyObject { unsafe { PyObject::from_borrowed_ptr(py, self.inner.as_ptr()) } } } #[allow(deprecated)] impl<T: PyClass<Frozen = False>> IntoPy<PyObject> for &'_ PyRefMut<'_, T> { fn into_py(self, py: Python<'_>) -> PyObject { self.inner.clone().into_py(py) } } impl<'py, T: PyClass<Frozen = False>> IntoPyObject<'py> for PyRefMut<'py, T> { type Target = T; type Output = Bound<'py, T>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.inner.clone()) } } impl<'a, 'py, T: PyClass<Frozen = False>> IntoPyObject<'py> for &'a PyRefMut<'py, T> { type Target = T; type Output = Borrowed<'a, 'py, T>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.inner.as_borrowed()) } } impl<T: PyClass<Frozen = False> + fmt::Debug> fmt::Debug for PyRefMut<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self.deref(), f) } } /// An error type returned by [`Bound::try_borrow`]. /// /// If this error is allowed to bubble up into Python code it will raise a `RuntimeError`. pub struct PyBorrowError { _private: (), } impl fmt::Debug for PyBorrowError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PyBorrowError").finish() } } impl fmt::Display for PyBorrowError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt("Already mutably borrowed", f) } } impl From<PyBorrowError> for PyErr { fn from(other: PyBorrowError) -> Self { PyRuntimeError::new_err(other.to_string()) } } /// An error type returned by [`Bound::try_borrow_mut`]. /// /// If this error is allowed to bubble up into Python code it will raise a `RuntimeError`. pub struct PyBorrowMutError { _private: (), } impl fmt::Debug for PyBorrowMutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PyBorrowMutError").finish() } } impl fmt::Display for PyBorrowMutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt("Already borrowed", f) } } impl From<PyBorrowMutError> for PyErr { fn from(other: PyBorrowMutError) -> Self { PyRuntimeError::new_err(other.to_string()) } } #[cfg(test)] #[cfg(feature = "macros")] mod tests { use super::*; #[crate::pyclass] #[pyo3(crate = "crate")] #[derive(Copy, Clone, PartialEq, Eq, Debug)] struct SomeClass(i32); #[test] fn test_as_ptr() { Python::with_gil(|py| { let cell = Bound::new(py, SomeClass(0)).unwrap(); let ptr = cell.as_ptr(); assert_eq!(cell.borrow().as_ptr(), ptr); assert_eq!(cell.borrow_mut().as_ptr(), ptr); }) } #[test] fn test_into_ptr() { Python::with_gil(|py| { let cell = Bound::new(py, SomeClass(0)).unwrap(); let ptr = cell.as_ptr(); assert_eq!(cell.borrow().into_ptr(), ptr); unsafe { ffi::Py_DECREF(ptr) }; assert_eq!(cell.borrow_mut().into_ptr(), ptr); unsafe { ffi::Py_DECREF(ptr) }; }) } #[crate::pyclass] #[pyo3(crate = "crate", subclass)] struct BaseClass { val1: usize, } #[crate::pyclass] #[pyo3(crate = "crate", extends=BaseClass, subclass)] struct SubClass { val2: usize, } #[crate::pyclass] #[pyo3(crate = "crate", extends=SubClass)] struct SubSubClass { val3: usize, } #[crate::pymethods] #[pyo3(crate = "crate")] impl SubSubClass { #[new] fn new(py: Python<'_>) -> crate::Py<SubSubClass> { let init = crate::PyClassInitializer::from(BaseClass { val1: 10 }) .add_subclass(SubClass { val2: 15 }) .add_subclass(SubSubClass { val3: 20 }); crate::Py::new(py, init).expect("allocation error") } 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; } } #[test] fn test_pyref_as_super() { Python::with_gil(|py| { let obj = SubSubClass::new(py).into_bound(py); let pyref = obj.borrow(); assert_eq!(pyref.as_super().as_super().val1, 10); assert_eq!(pyref.as_super().val2, 15); assert_eq!(pyref.as_ref().val2, 15); // `as_ref` also works assert_eq!(pyref.val3, 20); assert_eq!(SubSubClass::get_values(pyref), (10, 15, 20)); }); } #[test] fn test_pyrefmut_as_super() { Python::with_gil(|py| { let obj = SubSubClass::new(py).into_bound(py); assert_eq!(SubSubClass::get_values(obj.borrow()), (10, 15, 20)); { let mut pyrefmut = obj.borrow_mut(); assert_eq!(pyrefmut.as_super().as_ref().val1, 10); pyrefmut.as_super().as_super().val1 -= 5; pyrefmut.as_super().val2 -= 3; pyrefmut.as_mut().val2 -= 2; // `as_mut` also works pyrefmut.val3 -= 5; } assert_eq!(SubSubClass::get_values(obj.borrow()), (5, 10, 15)); SubSubClass::double_values(obj.borrow_mut()); assert_eq!(SubSubClass::get_values(obj.borrow()), (10, 20, 30)); }); } #[test] fn test_pyrefs_in_python() { Python::with_gil(|py| { let obj = SubSubClass::new(py); crate::py_run!(py, obj, "assert obj.get_values() == (10, 15, 20)"); crate::py_run!(py, obj, "assert obj.double_values() is None"); crate::py_run!(py, obj, "assert obj.get_values() == (20, 30, 40)"); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/prelude.rs
//! PyO3's prelude. //! //! The purpose of this module is to alleviate imports of many commonly used items of the PyO3 crate //! by adding a glob import to the top of pyo3 heavy modules: //! //! ``` //! # #![allow(unused_imports)] //! use pyo3::prelude::*; //! ``` pub use crate::conversion::{FromPyObject, IntoPyObject}; #[allow(deprecated)] pub use crate::conversion::{IntoPy, ToPyObject}; pub use crate::err::{PyErr, PyResult}; pub use crate::instance::{Borrowed, Bound, Py, PyObject}; pub use crate::marker::Python; pub use crate::pycell::{PyRef, PyRefMut}; pub use crate::pyclass_init::PyClassInitializer; pub use crate::types::{PyAny, PyModule}; #[cfg(feature = "macros")] pub use pyo3_macros::{ pyclass, pyfunction, pymethods, pymodule, FromPyObject, IntoPyObject, IntoPyObjectRef, }; #[cfg(feature = "macros")] pub use crate::wrap_pyfunction; #[cfg(feature = "macros")] #[allow(deprecated)] pub use crate::wrap_pyfunction_bound; pub use crate::types::any::PyAnyMethods; pub use crate::types::boolobject::PyBoolMethods; pub use crate::types::bytearray::PyByteArrayMethods; pub use crate::types::bytes::PyBytesMethods; pub use crate::types::capsule::PyCapsuleMethods; pub use crate::types::complex::PyComplexMethods; pub use crate::types::dict::PyDictMethods; pub use crate::types::float::PyFloatMethods; pub use crate::types::frozenset::PyFrozenSetMethods; pub use crate::types::list::PyListMethods; pub use crate::types::mapping::PyMappingMethods; pub use crate::types::mappingproxy::PyMappingProxyMethods; pub use crate::types::module::PyModuleMethods; pub use crate::types::sequence::PySequenceMethods; pub use crate::types::set::PySetMethods; pub use crate::types::slice::PySliceMethods; pub use crate::types::string::PyStringMethods; pub use crate::types::traceback::PyTracebackMethods; pub use crate::types::tuple::PyTupleMethods; pub use crate::types::typeobject::PyTypeMethods; pub use crate::types::weakref::PyWeakrefMethods;
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_.rs
#![allow(missing_docs)] //! Internals of PyO3 which are accessed by code expanded from PyO3's procedural macros. //! //! Usage of any of these APIs in downstream code is implicitly acknowledging that these //! APIs may may change at any time without documentation in the CHANGELOG and without //! breaking semver guarantees. pub mod callback; #[cfg(feature = "experimental-async")] pub mod coroutine; pub mod exceptions; pub mod extract_argument; pub mod freelist; pub mod frompyobject; pub(crate) mod not_send; pub mod panic; pub mod pycell; pub mod pyclass; pub mod pyclass_init; pub mod pyfunction; pub mod pymethods; pub mod pymodule; #[doc(hidden)] pub mod trampoline; pub mod wrap;
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/py_result_ext.rs
use crate::{types::any::PyAnyMethods, Bound, PyAny, PyResult, PyTypeCheck}; pub(crate) trait PyResultExt<'py>: crate::sealed::Sealed { fn downcast_into<T: PyTypeCheck>(self) -> PyResult<Bound<'py, T>>; unsafe fn downcast_into_unchecked<T>(self) -> PyResult<Bound<'py, T>>; } impl<'py> PyResultExt<'py> for PyResult<Bound<'py, PyAny>> { #[inline] fn downcast_into<T: PyTypeCheck>(self) -> PyResult<Bound<'py, T>> where { self.and_then(|instance| instance.downcast_into().map_err(Into::into)) } #[inline] unsafe fn downcast_into_unchecked<T>(self) -> PyResult<Bound<'py, T>> { self.map(|instance| instance.downcast_into_unchecked()) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/buffer.rs
#![cfg(any(not(Py_LIMITED_API), Py_3_11))] // Copyright (c) 2017 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //! `PyBuffer` implementation use crate::Bound; use crate::{err, exceptions::PyBufferError, ffi, FromPyObject, PyAny, PyResult, Python}; use std::marker::PhantomData; use std::os::raw; use std::pin::Pin; use std::{cell, mem, ptr, slice}; use std::{ffi::CStr, fmt::Debug}; /// Allows access to the underlying buffer used by a python object such as `bytes`, `bytearray` or `array.array`. // use Pin<Box> because Python expects that the Py_buffer struct has a stable memory address #[repr(transparent)] pub struct PyBuffer<T>(Pin<Box<ffi::Py_buffer>>, PhantomData<T>); // PyBuffer is thread-safe: the shape of the buffer is immutable while a Py_buffer exists. // Accessing the buffer contents is protected using the GIL. unsafe impl<T> Send for PyBuffer<T> {} unsafe impl<T> Sync for PyBuffer<T> {} impl<T> Debug for PyBuffer<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PyBuffer") .field("buf", &self.0.buf) .field("obj", &self.0.obj) .field("len", &self.0.len) .field("itemsize", &self.0.itemsize) .field("readonly", &self.0.readonly) .field("ndim", &self.0.ndim) .field("format", &self.0.format) .field("shape", &self.0.shape) .field("strides", &self.0.strides) .field("suboffsets", &self.0.suboffsets) .field("internal", &self.0.internal) .finish() } } /// Represents the type of a Python buffer element. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum ElementType { /// A signed integer type. SignedInteger { /// The width of the signed integer in bytes. bytes: usize, }, /// An unsigned integer type. UnsignedInteger { /// The width of the unsigned integer in bytes. bytes: usize, }, /// A boolean type. Bool, /// A float type. Float { /// The width of the float in bytes. bytes: usize, }, /// An unknown type. This may occur when parsing has failed. Unknown, } impl ElementType { /// Determines the `ElementType` from a Python `struct` module format string. /// /// See <https://docs.python.org/3/library/struct.html#format-strings> for more information /// about struct format strings. pub fn from_format(format: &CStr) -> ElementType { match format.to_bytes() { [size] | [b'@', size] => native_element_type_from_type_char(*size), [b'=' | b'<' | b'>' | b'!', size] => standard_element_type_from_type_char(*size), _ => ElementType::Unknown, } } } fn native_element_type_from_type_char(type_char: u8) -> ElementType { use self::ElementType::*; match type_char { b'c' => UnsignedInteger { bytes: mem::size_of::<raw::c_char>(), }, b'b' => SignedInteger { bytes: mem::size_of::<raw::c_schar>(), }, b'B' => UnsignedInteger { bytes: mem::size_of::<raw::c_uchar>(), }, b'?' => Bool, b'h' => SignedInteger { bytes: mem::size_of::<raw::c_short>(), }, b'H' => UnsignedInteger { bytes: mem::size_of::<raw::c_ushort>(), }, b'i' => SignedInteger { bytes: mem::size_of::<raw::c_int>(), }, b'I' => UnsignedInteger { bytes: mem::size_of::<raw::c_uint>(), }, b'l' => SignedInteger { bytes: mem::size_of::<raw::c_long>(), }, b'L' => UnsignedInteger { bytes: mem::size_of::<raw::c_ulong>(), }, b'q' => SignedInteger { bytes: mem::size_of::<raw::c_longlong>(), }, b'Q' => UnsignedInteger { bytes: mem::size_of::<raw::c_ulonglong>(), }, b'n' => SignedInteger { bytes: mem::size_of::<libc::ssize_t>(), }, b'N' => UnsignedInteger { bytes: mem::size_of::<libc::size_t>(), }, b'e' => Float { bytes: 2 }, b'f' => Float { bytes: 4 }, b'd' => Float { bytes: 8 }, _ => Unknown, } } fn standard_element_type_from_type_char(type_char: u8) -> ElementType { use self::ElementType::*; match type_char { b'c' | b'B' => UnsignedInteger { bytes: 1 }, b'b' => SignedInteger { bytes: 1 }, b'?' => Bool, b'h' => SignedInteger { bytes: 2 }, b'H' => UnsignedInteger { bytes: 2 }, b'i' | b'l' => SignedInteger { bytes: 4 }, b'I' | b'L' => UnsignedInteger { bytes: 4 }, b'q' => SignedInteger { bytes: 8 }, b'Q' => UnsignedInteger { bytes: 8 }, b'e' => Float { bytes: 2 }, b'f' => Float { bytes: 4 }, b'd' => Float { bytes: 8 }, _ => Unknown, } } #[cfg(target_endian = "little")] fn is_matching_endian(c: u8) -> bool { c == b'@' || c == b'=' || c == b'>' } #[cfg(target_endian = "big")] fn is_matching_endian(c: u8) -> bool { c == b'@' || c == b'=' || c == b'>' || c == b'!' } /// Trait implemented for possible element types of `PyBuffer`. /// /// # Safety /// /// This trait must only be implemented for types which represent valid elements of Python buffers. pub unsafe trait Element: Copy { /// Gets whether the element specified in the format string is potentially compatible. /// Alignment and size are checked separately from this function. fn is_compatible_format(format: &CStr) -> bool; } impl<T: Element> FromPyObject<'_> for PyBuffer<T> { fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<PyBuffer<T>> { Self::get(obj) } } impl<T: Element> PyBuffer<T> { /// Gets the underlying buffer from the specified python object. pub fn get(obj: &Bound<'_, PyAny>) -> PyResult<PyBuffer<T>> { // TODO: use nightly API Box::new_uninit() once our MSRV is 1.82 let mut buf = Box::new(mem::MaybeUninit::uninit()); let buf: Box<ffi::Py_buffer> = { err::error_on_minusone(obj.py(), unsafe { ffi::PyObject_GetBuffer(obj.as_ptr(), buf.as_mut_ptr(), ffi::PyBUF_FULL_RO) })?; // Safety: buf is initialized by PyObject_GetBuffer. // TODO: use nightly API Box::assume_init() once our MSRV is 1.82 unsafe { mem::transmute(buf) } }; // Create PyBuffer immediately so that if validation checks fail, the PyBuffer::drop code // will call PyBuffer_Release (thus avoiding any leaks). let buf = PyBuffer(Pin::from(buf), PhantomData); if buf.0.shape.is_null() { Err(PyBufferError::new_err("shape is null")) } else if buf.0.strides.is_null() { Err(PyBufferError::new_err("strides is null")) } else if mem::size_of::<T>() != buf.item_size() || !T::is_compatible_format(buf.format()) { Err(PyBufferError::new_err(format!( "buffer contents are not compatible with {}", std::any::type_name::<T>() ))) } else if buf.0.buf.align_offset(mem::align_of::<T>()) != 0 { Err(PyBufferError::new_err(format!( "buffer contents are insufficiently aligned for {}", std::any::type_name::<T>() ))) } else { Ok(buf) } } /// Deprecated name for [`PyBuffer::get`]. #[deprecated(since = "0.23.0", note = "renamed to `PyBuffer::get`")] #[inline] pub fn get_bound(obj: &Bound<'_, PyAny>) -> PyResult<PyBuffer<T>> { Self::get(obj) } /// Gets the pointer to the start of the buffer memory. /// /// Warning: the buffer memory might be mutated by other Python functions, /// and thus may only be accessed while the GIL is held. #[inline] pub fn buf_ptr(&self) -> *mut raw::c_void { self.0.buf } /// Gets a pointer to the specified item. /// /// If `indices.len() < self.dimensions()`, returns the start address of the sub-array at the specified dimension. pub fn get_ptr(&self, indices: &[usize]) -> *mut raw::c_void { let shape = &self.shape()[..indices.len()]; for i in 0..indices.len() { assert!(indices[i] < shape[i]); } unsafe { ffi::PyBuffer_GetPointer( #[cfg(Py_3_11)] &*self.0, #[cfg(not(Py_3_11))] { &*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer }, #[cfg(Py_3_11)] { indices.as_ptr().cast() }, #[cfg(not(Py_3_11))] { indices.as_ptr() as *mut ffi::Py_ssize_t }, ) } } /// Gets whether the underlying buffer is read-only. #[inline] pub fn readonly(&self) -> bool { self.0.readonly != 0 } /// Gets the size of a single element, in bytes. /// Important exception: when requesting an unformatted buffer, item_size still has the value #[inline] pub fn item_size(&self) -> usize { self.0.itemsize as usize } /// Gets the total number of items. #[inline] pub fn item_count(&self) -> usize { (self.0.len as usize) / (self.0.itemsize as usize) } /// `item_size() * item_count()`. /// For contiguous arrays, this is the length of the underlying memory block. /// For non-contiguous arrays, it is the length that the logical structure would have if it were copied to a contiguous representation. #[inline] pub fn len_bytes(&self) -> usize { self.0.len as usize } /// Gets the number of dimensions. /// /// May be 0 to indicate a single scalar value. #[inline] pub fn dimensions(&self) -> usize { self.0.ndim as usize } /// Returns an array of length `dimensions`. `shape()[i]` is the length of the array in dimension number `i`. /// /// May return None for single-dimensional arrays or scalar values (`dimensions() <= 1`); /// You can call `item_count()` to get the length of the single dimension. /// /// Despite Python using an array of signed integers, the values are guaranteed to be non-negative. /// However, dimensions of length 0 are possible and might need special attention. #[inline] pub fn shape(&self) -> &[usize] { unsafe { slice::from_raw_parts(self.0.shape.cast(), self.0.ndim as usize) } } /// Returns an array that holds, for each dimension, the number of bytes to skip to get to the next element in the dimension. /// /// Stride values can be any integer. For regular arrays, strides are usually positive, /// but a consumer MUST be able to handle the case `strides[n] <= 0`. #[inline] pub fn strides(&self) -> &[isize] { unsafe { slice::from_raw_parts(self.0.strides, self.0.ndim as usize) } } /// An array of length ndim. /// If `suboffsets[n] >= 0`, the values stored along the nth dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-referencing. /// A suboffset value that is negative indicates that no de-referencing should occur (striding in a contiguous memory block). /// /// If all suboffsets are negative (i.e. no de-referencing is needed), then this field must be NULL (the default value). #[inline] pub fn suboffsets(&self) -> Option<&[isize]> { unsafe { if self.0.suboffsets.is_null() { None } else { Some(slice::from_raw_parts( self.0.suboffsets, self.0.ndim as usize, )) } } } /// A NUL terminated string in struct module style syntax describing the contents of a single item. #[inline] pub fn format(&self) -> &CStr { if self.0.format.is_null() { ffi::c_str!("B") } else { unsafe { CStr::from_ptr(self.0.format) } } } /// Gets whether the buffer is contiguous in C-style order (last index varies fastest when visiting items in order of memory address). #[inline] pub fn is_c_contiguous(&self) -> bool { unsafe { ffi::PyBuffer_IsContiguous(&*self.0, b'C' as std::os::raw::c_char) != 0 } } /// Gets whether the buffer is contiguous in Fortran-style order (first index varies fastest when visiting items in order of memory address). #[inline] pub fn is_fortran_contiguous(&self) -> bool { unsafe { ffi::PyBuffer_IsContiguous(&*self.0, b'F' as std::os::raw::c_char) != 0 } } /// Gets the buffer memory as a slice. /// /// This function succeeds if: /// * the buffer format is compatible with `T` /// * alignment and size of buffer elements is matching the expectations for type `T` /// * the buffer is C-style contiguous /// /// The returned slice uses type `Cell<T>` because it's theoretically possible for any call into the Python runtime /// to modify the values in the slice. pub fn as_slice<'a>(&'a self, _py: Python<'a>) -> Option<&'a [ReadOnlyCell<T>]> { if self.is_c_contiguous() { unsafe { Some(slice::from_raw_parts( self.0.buf as *mut ReadOnlyCell<T>, self.item_count(), )) } } else { None } } /// Gets the buffer memory as a slice. /// /// This function succeeds if: /// * the buffer is not read-only /// * the buffer format is compatible with `T` /// * alignment and size of buffer elements is matching the expectations for type `T` /// * the buffer is C-style contiguous /// /// The returned slice uses type `Cell<T>` because it's theoretically possible for any call into the Python runtime /// to modify the values in the slice. pub fn as_mut_slice<'a>(&'a self, _py: Python<'a>) -> Option<&'a [cell::Cell<T>]> { if !self.readonly() && self.is_c_contiguous() { unsafe { Some(slice::from_raw_parts( self.0.buf as *mut cell::Cell<T>, self.item_count(), )) } } else { None } } /// Gets the buffer memory as a slice. /// /// This function succeeds if: /// * the buffer format is compatible with `T` /// * alignment and size of buffer elements is matching the expectations for type `T` /// * the buffer is Fortran-style contiguous /// /// The returned slice uses type `Cell<T>` because it's theoretically possible for any call into the Python runtime /// to modify the values in the slice. pub fn as_fortran_slice<'a>(&'a self, _py: Python<'a>) -> Option<&'a [ReadOnlyCell<T>]> { if mem::size_of::<T>() == self.item_size() && self.is_fortran_contiguous() { unsafe { Some(slice::from_raw_parts( self.0.buf as *mut ReadOnlyCell<T>, self.item_count(), )) } } else { None } } /// Gets the buffer memory as a slice. /// /// This function succeeds if: /// * the buffer is not read-only /// * the buffer format is compatible with `T` /// * alignment and size of buffer elements is matching the expectations for type `T` /// * the buffer is Fortran-style contiguous /// /// The returned slice uses type `Cell<T>` because it's theoretically possible for any call into the Python runtime /// to modify the values in the slice. pub fn as_fortran_mut_slice<'a>(&'a self, _py: Python<'a>) -> Option<&'a [cell::Cell<T>]> { if !self.readonly() && self.is_fortran_contiguous() { unsafe { Some(slice::from_raw_parts( self.0.buf as *mut cell::Cell<T>, self.item_count(), )) } } else { None } } /// Copies the buffer elements to the specified slice. /// If the buffer is multi-dimensional, the elements are written in C-style order. /// /// * Fails if the slice does not have the correct length (`buf.item_count()`). /// * Fails if the buffer format is not compatible with type `T`. /// /// To check whether the buffer format is compatible before calling this method, /// you can use `<T as buffer::Element>::is_compatible_format(buf.format())`. /// Alternatively, `match buffer::ElementType::from_format(buf.format())`. pub fn copy_to_slice(&self, py: Python<'_>, target: &mut [T]) -> PyResult<()> { self._copy_to_slice(py, target, b'C') } /// Copies the buffer elements to the specified slice. /// If the buffer is multi-dimensional, the elements are written in Fortran-style order. /// /// * Fails if the slice does not have the correct length (`buf.item_count()`). /// * Fails if the buffer format is not compatible with type `T`. /// /// To check whether the buffer format is compatible before calling this method, /// you can use `<T as buffer::Element>::is_compatible_format(buf.format())`. /// Alternatively, `match buffer::ElementType::from_format(buf.format())`. pub fn copy_to_fortran_slice(&self, py: Python<'_>, target: &mut [T]) -> PyResult<()> { self._copy_to_slice(py, target, b'F') } fn _copy_to_slice(&self, py: Python<'_>, target: &mut [T], fort: u8) -> PyResult<()> { if mem::size_of_val(target) != self.len_bytes() { return Err(PyBufferError::new_err(format!( "slice to copy to (of length {}) does not match buffer length of {}", target.len(), self.item_count() ))); } err::error_on_minusone(py, unsafe { ffi::PyBuffer_ToContiguous( target.as_mut_ptr().cast(), #[cfg(Py_3_11)] &*self.0, #[cfg(not(Py_3_11))] { &*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer }, self.0.len, fort as std::os::raw::c_char, ) }) } /// Copies the buffer elements to a newly allocated vector. /// If the buffer is multi-dimensional, the elements are written in C-style order. /// /// Fails if the buffer format is not compatible with type `T`. pub fn to_vec(&self, py: Python<'_>) -> PyResult<Vec<T>> { self._to_vec(py, b'C') } /// Copies the buffer elements to a newly allocated vector. /// If the buffer is multi-dimensional, the elements are written in Fortran-style order. /// /// Fails if the buffer format is not compatible with type `T`. pub fn to_fortran_vec(&self, py: Python<'_>) -> PyResult<Vec<T>> { self._to_vec(py, b'F') } fn _to_vec(&self, py: Python<'_>, fort: u8) -> PyResult<Vec<T>> { let item_count = self.item_count(); let mut vec: Vec<T> = Vec::with_capacity(item_count); // Copy the buffer into the uninitialized space in the vector. // Due to T:Copy, we don't need to be concerned with Drop impls. err::error_on_minusone(py, unsafe { ffi::PyBuffer_ToContiguous( vec.as_ptr() as *mut raw::c_void, #[cfg(Py_3_11)] &*self.0, #[cfg(not(Py_3_11))] { &*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer }, self.0.len, fort as std::os::raw::c_char, ) })?; // set vector length to mark the now-initialized space as usable unsafe { vec.set_len(item_count) }; Ok(vec) } /// Copies the specified slice into the buffer. /// If the buffer is multi-dimensional, the elements in the slice are expected to be in C-style order. /// /// * Fails if the buffer is read-only. /// * Fails if the slice does not have the correct length (`buf.item_count()`). /// * Fails if the buffer format is not compatible with type `T`. /// /// To check whether the buffer format is compatible before calling this method, /// use `<T as buffer::Element>::is_compatible_format(buf.format())`. /// Alternatively, `match buffer::ElementType::from_format(buf.format())`. pub fn copy_from_slice(&self, py: Python<'_>, source: &[T]) -> PyResult<()> { self._copy_from_slice(py, source, b'C') } /// Copies the specified slice into the buffer. /// If the buffer is multi-dimensional, the elements in the slice are expected to be in Fortran-style order. /// /// * Fails if the buffer is read-only. /// * Fails if the slice does not have the correct length (`buf.item_count()`). /// * Fails if the buffer format is not compatible with type `T`. /// /// To check whether the buffer format is compatible before calling this method, /// use `<T as buffer::Element>::is_compatible_format(buf.format())`. /// Alternatively, `match buffer::ElementType::from_format(buf.format())`. pub fn copy_from_fortran_slice(&self, py: Python<'_>, source: &[T]) -> PyResult<()> { self._copy_from_slice(py, source, b'F') } fn _copy_from_slice(&self, py: Python<'_>, source: &[T], fort: u8) -> PyResult<()> { if self.readonly() { return Err(PyBufferError::new_err("cannot write to read-only buffer")); } else if mem::size_of_val(source) != self.len_bytes() { return Err(PyBufferError::new_err(format!( "slice to copy from (of length {}) does not match buffer length of {}", source.len(), self.item_count() ))); } err::error_on_minusone(py, unsafe { ffi::PyBuffer_FromContiguous( #[cfg(Py_3_11)] &*self.0, #[cfg(not(Py_3_11))] { &*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer }, #[cfg(Py_3_11)] { source.as_ptr().cast() }, #[cfg(not(Py_3_11))] { source.as_ptr() as *mut raw::c_void }, self.0.len, fort as std::os::raw::c_char, ) }) } /// Releases the buffer object, freeing the reference to the Python object /// which owns the buffer. /// /// This will automatically be called on drop. pub fn release(self, _py: Python<'_>) { // First move self into a ManuallyDrop, so that PyBuffer::drop will // never be called. (It would acquire the GIL and call PyBuffer_Release // again.) let mut mdself = mem::ManuallyDrop::new(self); unsafe { // Next, make the actual PyBuffer_Release call. ffi::PyBuffer_Release(&mut *mdself.0); // Finally, drop the contained Pin<Box<_>> in place, to free the // Box memory. let inner: *mut Pin<Box<ffi::Py_buffer>> = &mut mdself.0; ptr::drop_in_place(inner); } } } impl<T> Drop for PyBuffer<T> { fn drop(&mut self) { Python::with_gil(|_| unsafe { ffi::PyBuffer_Release(&mut *self.0) }); } } /// Like [std::cell::Cell], but only provides read-only access to the data. /// /// `&ReadOnlyCell<T>` is basically a safe version of `*const T`: /// The data cannot be modified through the reference, but other references may /// be modifying the data. #[repr(transparent)] pub struct ReadOnlyCell<T: Element>(cell::UnsafeCell<T>); impl<T: Element> ReadOnlyCell<T> { /// Returns a copy of the current value. #[inline] pub fn get(&self) -> T { unsafe { *self.0.get() } } /// Returns a pointer to the current value. #[inline] pub fn as_ptr(&self) -> *const T { self.0.get() } } macro_rules! impl_element( ($t:ty, $f:ident) => { unsafe impl Element for $t { fn is_compatible_format(format: &CStr) -> bool { let slice = format.to_bytes(); if slice.len() > 1 && !is_matching_endian(slice[0]) { return false; } ElementType::from_format(format) == ElementType::$f { bytes: mem::size_of::<$t>() } } } } ); impl_element!(u8, UnsignedInteger); impl_element!(u16, UnsignedInteger); impl_element!(u32, UnsignedInteger); impl_element!(u64, UnsignedInteger); impl_element!(usize, UnsignedInteger); impl_element!(i8, SignedInteger); impl_element!(i16, SignedInteger); impl_element!(i32, SignedInteger); impl_element!(i64, SignedInteger); impl_element!(isize, SignedInteger); impl_element!(f32, Float); impl_element!(f64, Float); #[cfg(test)] mod tests { use super::PyBuffer; use crate::ffi; use crate::types::any::PyAnyMethods; use crate::Python; #[test] fn test_debug() { Python::with_gil(|py| { let bytes = py.eval(ffi::c_str!("b'abcde'"), None, None).unwrap(); let buffer: PyBuffer<u8> = PyBuffer::get(&bytes).unwrap(); let expected = format!( concat!( "PyBuffer {{ buf: {:?}, obj: {:?}, ", "len: 5, itemsize: 1, readonly: 1, ", "ndim: 1, format: {:?}, shape: {:?}, ", "strides: {:?}, suboffsets: {:?}, internal: {:?} }}", ), buffer.0.buf, buffer.0.obj, buffer.0.format, buffer.0.shape, buffer.0.strides, buffer.0.suboffsets, buffer.0.internal ); let debug_repr = format!("{:?}", buffer); assert_eq!(debug_repr, expected); }); } #[test] fn test_element_type_from_format() { use super::ElementType; use super::ElementType::*; use std::mem::size_of; use std::os::raw; for (cstr, expected) in [ // @ prefix goes to native_element_type_from_type_char ( ffi::c_str!("@b"), SignedInteger { bytes: size_of::<raw::c_schar>(), }, ), ( ffi::c_str!("@c"), UnsignedInteger { bytes: size_of::<raw::c_char>(), }, ), ( ffi::c_str!("@b"), SignedInteger { bytes: size_of::<raw::c_schar>(), }, ), ( ffi::c_str!("@B"), UnsignedInteger { bytes: size_of::<raw::c_uchar>(), }, ), (ffi::c_str!("@?"), Bool), ( ffi::c_str!("@h"), SignedInteger { bytes: size_of::<raw::c_short>(), }, ), ( ffi::c_str!("@H"), UnsignedInteger { bytes: size_of::<raw::c_ushort>(), }, ), ( ffi::c_str!("@i"), SignedInteger { bytes: size_of::<raw::c_int>(), }, ), ( ffi::c_str!("@I"), UnsignedInteger { bytes: size_of::<raw::c_uint>(), }, ), ( ffi::c_str!("@l"), SignedInteger { bytes: size_of::<raw::c_long>(), }, ), ( ffi::c_str!("@L"), UnsignedInteger { bytes: size_of::<raw::c_ulong>(), }, ), ( ffi::c_str!("@q"), SignedInteger { bytes: size_of::<raw::c_longlong>(), }, ), ( ffi::c_str!("@Q"), UnsignedInteger { bytes: size_of::<raw::c_ulonglong>(), }, ), ( ffi::c_str!("@n"), SignedInteger { bytes: size_of::<libc::ssize_t>(), }, ), ( ffi::c_str!("@N"), UnsignedInteger { bytes: size_of::<libc::size_t>(), }, ), (ffi::c_str!("@e"), Float { bytes: 2 }), (ffi::c_str!("@f"), Float { bytes: 4 }), (ffi::c_str!("@d"), Float { bytes: 8 }), (ffi::c_str!("@z"), Unknown), // = prefix goes to standard_element_type_from_type_char (ffi::c_str!("=b"), SignedInteger { bytes: 1 }), (ffi::c_str!("=c"), UnsignedInteger { bytes: 1 }), (ffi::c_str!("=B"), UnsignedInteger { bytes: 1 }), (ffi::c_str!("=?"), Bool), (ffi::c_str!("=h"), SignedInteger { bytes: 2 }), (ffi::c_str!("=H"), UnsignedInteger { bytes: 2 }), (ffi::c_str!("=l"), SignedInteger { bytes: 4 }), (ffi::c_str!("=l"), SignedInteger { bytes: 4 }), (ffi::c_str!("=I"), UnsignedInteger { bytes: 4 }), (ffi::c_str!("=L"), UnsignedInteger { bytes: 4 }), (ffi::c_str!("=q"), SignedInteger { bytes: 8 }), (ffi::c_str!("=Q"), UnsignedInteger { bytes: 8 }), (ffi::c_str!("=e"), Float { bytes: 2 }), (ffi::c_str!("=f"), Float { bytes: 4 }), (ffi::c_str!("=d"), Float { bytes: 8 }), (ffi::c_str!("=z"), Unknown), (ffi::c_str!("=0"), Unknown), // unknown prefix -> Unknown (ffi::c_str!(":b"), Unknown), ] { assert_eq!( ElementType::from_format(cstr), expected, "element from format &Cstr: {:?}", cstr, ); } } #[test] fn test_compatible_size() { // for the cast in PyBuffer::shape() assert_eq!( std::mem::size_of::<ffi::Py_ssize_t>(), std::mem::size_of::<usize>() ); } #[test] fn test_bytes_buffer() { Python::with_gil(|py| { let bytes = py.eval(ffi::c_str!("b'abcde'"), None, None).unwrap(); let buffer = PyBuffer::get(&bytes).unwrap(); assert_eq!(buffer.dimensions(), 1); assert_eq!(buffer.item_count(), 5); assert_eq!(buffer.format().to_str().unwrap(), "B"); assert_eq!(buffer.shape(), [5]); // single-dimensional buffer is always contiguous assert!(buffer.is_c_contiguous()); assert!(buffer.is_fortran_contiguous()); let slice = buffer.as_slice(py).unwrap(); assert_eq!(slice.len(), 5); assert_eq!(slice[0].get(), b'a'); assert_eq!(slice[2].get(), b'c'); assert_eq!(unsafe { *(buffer.get_ptr(&[1]) as *mut u8) }, b'b'); assert!(buffer.as_mut_slice(py).is_none()); assert!(buffer.copy_to_slice(py, &mut [0u8]).is_err()); let mut arr = [0; 5]; buffer.copy_to_slice(py, &mut arr).unwrap(); assert_eq!(arr, b"abcde" as &[u8]); assert!(buffer.copy_from_slice(py, &[0u8; 5]).is_err()); assert_eq!(buffer.to_vec(py).unwrap(), b"abcde"); }); } #[test] fn test_array_buffer() { Python::with_gil(|py| { let array = py .import("array") .unwrap() .call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None) .unwrap(); let buffer = PyBuffer::get(&array).unwrap(); assert_eq!(buffer.dimensions(), 1); assert_eq!(buffer.item_count(), 4); assert_eq!(buffer.format().to_str().unwrap(), "f"); assert_eq!(buffer.shape(), [4]); // array creates a 1D contiguious buffer, so it's both C and F contiguous. This would // be more interesting if we can come up with a 2D buffer but I think it would need a // third-party lib or a custom class. // C-contiguous fns let slice = buffer.as_slice(py).unwrap(); assert_eq!(slice.len(), 4); assert_eq!(slice[0].get(), 1.0); assert_eq!(slice[3].get(), 2.5); let mut_slice = buffer.as_mut_slice(py).unwrap(); assert_eq!(mut_slice.len(), 4); assert_eq!(mut_slice[0].get(), 1.0); mut_slice[3].set(2.75); assert_eq!(slice[3].get(), 2.75); buffer .copy_from_slice(py, &[10.0f32, 11.0, 12.0, 13.0]) .unwrap(); assert_eq!(slice[2].get(), 12.0); assert_eq!(buffer.to_vec(py).unwrap(), [10.0, 11.0, 12.0, 13.0]); // F-contiguous fns let buffer = PyBuffer::get(&array).unwrap(); let slice = buffer.as_fortran_slice(py).unwrap(); assert_eq!(slice.len(), 4); assert_eq!(slice[1].get(), 11.0); let mut_slice = buffer.as_fortran_mut_slice(py).unwrap(); assert_eq!(mut_slice.len(), 4); assert_eq!(mut_slice[2].get(), 12.0); mut_slice[3].set(2.75); assert_eq!(slice[3].get(), 2.75); buffer .copy_from_fortran_slice(py, &[10.0f32, 11.0, 12.0, 13.0]) .unwrap(); assert_eq!(slice[2].get(), 12.0); assert_eq!(buffer.to_fortran_vec(py).unwrap(), [10.0, 11.0, 12.0, 13.0]); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/marker.rs
//! Fundamental properties of objects tied to the Python interpreter. //! //! The Python interpreter is not threadsafe. To protect the Python interpreter in multithreaded //! scenarios there is a global lock, the *global interpreter lock* (hereafter referred to as *GIL*) //! that must be held to safely interact with Python objects. This is why in PyO3 when you acquire //! the GIL you get a [`Python`] marker token that carries the *lifetime* of holding the GIL and all //! borrowed references to Python objects carry this lifetime as well. This will statically ensure //! that you can never use Python objects after dropping the lock - if you mess this up it will be //! caught at compile time and your program will fail to compile. //! //! It also supports this pattern that many extension modules employ: //! - Drop the GIL, so that other Python threads can acquire it and make progress themselves //! - Do something independently of the Python interpreter, like IO, a long running calculation or //! awaiting a future //! - Once that is done, reacquire the GIL //! //! That API is provided by [`Python::allow_threads`] and enforced via the [`Ungil`] bound on the //! closure and the return type. This is done by relying on the [`Send`] auto trait. `Ungil` is //! defined as the following: //! //! ```rust //! # #![allow(dead_code)] //! pub unsafe trait Ungil {} //! //! unsafe impl<T: Send> Ungil for T {} //! ``` //! //! We piggy-back off the `Send` auto trait because it is not possible to implement custom auto //! traits on stable Rust. This is the solution which enables it for as many types as possible while //! making the API usable. //! //! In practice this API works quite well, but it comes with some drawbacks: //! //! ## Drawbacks //! //! There is no reason to prevent `!Send` types like [`Rc`] from crossing the closure. After all, //! [`Python::allow_threads`] just lets other Python threads run - it does not itself launch a new //! thread. //! //! ```rust, compile_fail //! # #[cfg(feature = "nightly")] //! # compile_error!("this actually works on nightly") //! use pyo3::prelude::*; //! use std::rc::Rc; //! //! fn main() { //! Python::with_gil(|py| { //! let rc = Rc::new(5); //! //! py.allow_threads(|| { //! // This would actually be fine... //! println!("{:?}", *rc); //! }); //! }); //! } //! ``` //! //! Because we are using `Send` for something it's not quite meant for, other code that //! (correctly) upholds the invariants of [`Send`] can cause problems. //! //! [`SendWrapper`] is one of those. Per its documentation: //! //! > A wrapper which allows you to move around non-Send-types between threads, as long as you //! > access the contained value only from within the original thread and make sure that it is //! > dropped from within the original thread. //! //! This will "work" to smuggle Python references across the closure, because we're not actually //! doing anything with threads: //! //! ```rust, no_run //! use pyo3::prelude::*; //! use pyo3::types::PyString; //! use send_wrapper::SendWrapper; //! //! Python::with_gil(|py| { //! let string = PyString::new(py, "foo"); //! //! let wrapped = SendWrapper::new(string); //! //! py.allow_threads(|| { //! # #[cfg(not(feature = "nightly"))] //! # { //! // 💥 Unsound! 💥 //! let smuggled: &Bound<'_, PyString> = &*wrapped; //! println!("{:?}", smuggled); //! # } //! }); //! }); //! ``` //! //! For now the answer to that is "don't do that". //! //! # A proper implementation using an auto trait //! //! However on nightly Rust and when PyO3's `nightly` feature is //! enabled, `Ungil` is defined as the following: //! //! ```rust //! # #[cfg(any())] //! # { //! #![feature(auto_traits, negative_impls)] //! //! pub unsafe auto trait Ungil {} //! //! // It is unimplemented for the `Python` struct and Python objects. //! impl !Ungil for Python<'_> {} //! impl !Ungil for ffi::PyObject {} //! //! // `Py` wraps it in a safe api, so this is OK //! unsafe impl<T> Ungil for Py<T> {} //! # } //! ``` //! //! With this feature enabled, the above two examples will start working and not working, respectively. //! //! [`SendWrapper`]: https://docs.rs/send_wrapper/latest/send_wrapper/struct.SendWrapper.html //! [`Rc`]: std::rc::Rc //! [`Py`]: crate::Py use crate::conversion::IntoPyObject; #[cfg(any(doc, not(Py_3_10)))] use crate::err::PyErr; use crate::err::{self, PyResult}; use crate::ffi_ptr_ext::FfiPtrExt; use crate::gil::{GILGuard, SuspendGIL}; use crate::impl_::not_send::NotSend; use crate::py_result_ext::PyResultExt; use crate::types::any::PyAnyMethods; use crate::types::{ PyAny, PyDict, PyEllipsis, PyModule, PyNone, PyNotImplemented, PyString, PyType, }; use crate::version::PythonVersionInfo; #[allow(deprecated)] use crate::IntoPy; use crate::{ffi, Bound, Py, PyObject, PyTypeInfo}; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::os::raw::c_int; /// Types that are safe to access while the GIL is not held. /// /// # Safety /// /// The type must not carry borrowed Python references or, if it does, not allow access to them if /// the GIL is not held. /// /// See the [module-level documentation](self) for more information. /// /// # Examples /// /// This tracking is currently imprecise as it relies on the [`Send`] auto trait on stable Rust. /// For example, an `Rc` smart pointer should be usable without the GIL, but we currently prevent that: /// /// ```compile_fail /// # use pyo3::prelude::*; /// use std::rc::Rc; /// /// Python::with_gil(|py| { /// let rc = Rc::new(42); /// /// py.allow_threads(|| { /// println!("{:?}", rc); /// }); /// }); /// ``` /// /// This also implies that the interplay between `with_gil` and `allow_threads` is unsound, for example /// one can circumvent this protection using the [`send_wrapper`](https://docs.rs/send_wrapper/) crate: /// /// ```no_run /// # use pyo3::prelude::*; /// # use pyo3::types::PyString; /// use send_wrapper::SendWrapper; /// /// Python::with_gil(|py| { /// let string = PyString::new(py, "foo"); /// /// let wrapped = SendWrapper::new(string); /// /// py.allow_threads(|| { /// let sneaky: &Bound<'_, PyString> = &*wrapped; /// /// println!("{:?}", sneaky); /// }); /// }); /// ``` /// /// Fixing this loophole on stable Rust has significant ergonomic issues, but it is fixed when using /// nightly Rust and the `nightly` feature, c.f. [#2141](https://github.com/PyO3/pyo3/issues/2141). #[cfg_attr(docsrs, doc(cfg(all())))] // Hide the cfg flag #[cfg(not(feature = "nightly"))] pub unsafe trait Ungil {} #[cfg_attr(docsrs, doc(cfg(all())))] // Hide the cfg flag #[cfg(not(feature = "nightly"))] unsafe impl<T: Send> Ungil for T {} #[cfg(feature = "nightly")] mod nightly { macro_rules! define { ($($tt:tt)*) => { $($tt)* } } define! { /// Types that are safe to access while the GIL is not held. /// /// # Safety /// /// The type must not carry borrowed Python references or, if it does, not allow access to them if /// the GIL is not held. /// /// See the [module-level documentation](self) for more information. /// /// # Examples /// /// Types which are `Ungil` cannot be used in contexts where the GIL was released, e.g. /// /// ```compile_fail /// # use pyo3::prelude::*; /// # use pyo3::types::PyString; /// Python::with_gil(|py| { /// let string = PyString::new_bound(py, "foo"); /// /// py.allow_threads(|| { /// println!("{:?}", string); /// }); /// }); /// ``` /// /// This applies to the GIL token `Python` itself as well, e.g. /// /// ```compile_fail /// # use pyo3::prelude::*; /// Python::with_gil(|py| { /// py.allow_threads(|| { /// drop(py); /// }); /// }); /// ``` /// /// On nightly Rust, this is not based on the [`Send`] auto trait and hence we are able /// to prevent incorrectly circumventing it using e.g. the [`send_wrapper`](https://docs.rs/send_wrapper/) crate: /// /// ```compile_fail /// # use pyo3::prelude::*; /// # use pyo3::types::PyString; /// use send_wrapper::SendWrapper; /// /// Python::with_gil(|py| { /// let string = PyString::new_bound(py, "foo"); /// /// let wrapped = SendWrapper::new(string); /// /// py.allow_threads(|| { /// let sneaky: &PyString = *wrapped; /// /// println!("{:?}", sneaky); /// }); /// }); /// ``` /// /// This also enables using non-[`Send`] types in `allow_threads`, /// at least if they are not also bound to the GIL: /// /// ```rust /// # use pyo3::prelude::*; /// use std::rc::Rc; /// /// Python::with_gil(|py| { /// let rc = Rc::new(42); /// /// py.allow_threads(|| { /// println!("{:?}", rc); /// }); /// }); /// ``` pub unsafe auto trait Ungil {} } impl !Ungil for crate::Python<'_> {} // This means that PyString, PyList, etc all inherit !Ungil from this. impl !Ungil for crate::PyAny {} impl<T> !Ungil for crate::PyRef<'_, T> {} impl<T> !Ungil for crate::PyRefMut<'_, T> {} // FFI pointees impl !Ungil for crate::ffi::PyObject {} impl !Ungil for crate::ffi::PyLongObject {} impl !Ungil for crate::ffi::PyThreadState {} impl !Ungil for crate::ffi::PyInterpreterState {} impl !Ungil for crate::ffi::PyWeakReference {} impl !Ungil for crate::ffi::PyFrameObject {} impl !Ungil for crate::ffi::PyCodeObject {} #[cfg(not(Py_LIMITED_API))] impl !Ungil for crate::ffi::PyDictKeysObject {} #[cfg(not(any(Py_LIMITED_API, Py_3_10)))] impl !Ungil for crate::ffi::PyArena {} } #[cfg(feature = "nightly")] pub use nightly::Ungil; /// A marker token that represents holding the GIL. /// /// It serves three main purposes: /// - It provides a global API for the Python interpreter, such as [`Python::eval_bound`]. /// - It can be passed to functions that require a proof of holding the GIL, such as /// [`Py::clone_ref`]. /// - Its lifetime represents the scope of holding the GIL which can be used to create Rust /// references that are bound to it, such as [`Bound<'py, PyAny>`]. /// /// Note that there are some caveats to using it that you might need to be aware of. See the /// [Deadlocks](#deadlocks) and [Releasing and freeing memory](#releasing-and-freeing-memory) /// paragraphs for more information about that. /// /// # Obtaining a Python token /// /// The following are the recommended ways to obtain a [`Python<'py>`] token, in order of preference: /// - If you already have something with a lifetime bound to the GIL, such as [`Bound<'py, PyAny>`], you can /// use its `.py()` method to get a token. /// - In a function or method annotated with [`#[pyfunction]`](crate::pyfunction) or [`#[pymethods]`](crate::pymethods) you can declare it /// as a parameter, and PyO3 will pass in the token when Python code calls it. /// - When you need to acquire the GIL yourself, such as when calling Python code from Rust, you /// should call [`Python::with_gil`] to do that and pass your code as a closure to it. /// /// The first two options are zero-cost; [`Python::with_gil`] requires runtime checking and may need to block /// to acquire the GIL. /// /// # Deadlocks /// /// Note that the GIL can be temporarily released by the Python interpreter during a function call /// (e.g. importing a module). In general, you don't need to worry about this because the GIL is /// reacquired before returning to the Rust code: /// /// ```text /// `Python` exists |=====================================| /// GIL actually held |==========| |================| /// Rust code running |=======| |==| |======| /// ``` /// /// This behaviour can cause deadlocks when trying to lock a Rust mutex while holding the GIL: /// /// * Thread 1 acquires the GIL /// * Thread 1 locks a mutex /// * Thread 1 makes a call into the Python interpreter which releases the GIL /// * Thread 2 acquires the GIL /// * Thread 2 tries to locks the mutex, blocks /// * Thread 1's Python interpreter call blocks trying to reacquire the GIL held by thread 2 /// /// To avoid deadlocking, you should release the GIL before trying to lock a mutex or `await`ing in /// asynchronous code, e.g. with [`Python::allow_threads`]. /// /// # Releasing and freeing memory /// /// The [`Python<'py>`] type can be used to create references to variables owned by the Python /// interpreter, using functions such as [`Python::eval_bound`] and [`PyModule::import`]. #[derive(Copy, Clone)] pub struct Python<'py>(PhantomData<(&'py GILGuard, NotSend)>); impl Python<'_> { /// Acquires the global interpreter lock, allowing access to the Python interpreter. The /// provided closure `F` will be executed with the acquired `Python` marker token. /// /// If implementing [`#[pymethods]`](crate::pymethods) or [`#[pyfunction]`](crate::pyfunction), /// declare `py: Python` as an argument. PyO3 will pass in the token to grant access to the GIL /// context in which the function is running, avoiding the need to call `with_gil`. /// /// If the [`auto-initialize`] feature is enabled and the Python runtime is not already /// initialized, this function will initialize it. See #[cfg_attr( not(any(PyPy, GraalPy)), doc = "[`prepare_freethreaded_python`](crate::prepare_freethreaded_python)" )] #[cfg_attr(PyPy, doc = "`prepare_freethreaded_python`")] /// for details. /// /// If the current thread does not yet have a Python "thread state" associated with it, /// a new one will be automatically created before `F` is executed and destroyed after `F` /// completes. /// /// # Panics /// /// - If the [`auto-initialize`] feature is not enabled and the Python interpreter is not /// initialized. /// /// # Examples /// /// ``` /// use pyo3::prelude::*; /// use pyo3::ffi::c_str; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let x: i32 = py.eval(c_str!("5"), None, None)?.extract()?; /// assert_eq!(x, 5); /// Ok(()) /// }) /// # } /// ``` /// /// [`auto-initialize`]: https://pyo3.rs/main/features.html#auto-initialize #[inline] pub fn with_gil<F, R>(f: F) -> R where F: for<'py> FnOnce(Python<'py>) -> R, { let guard = GILGuard::acquire(); // SAFETY: Either the GIL was already acquired or we just created a new `GILGuard`. f(guard.python()) } /// Like [`Python::with_gil`] except Python interpreter state checking is skipped. /// /// Normally when the GIL is acquired, we check that the Python interpreter is an /// appropriate state (e.g. it is fully initialized). This function skips those /// checks. /// /// # Safety /// /// If [`Python::with_gil`] would succeed, it is safe to call this function. /// /// In most cases, you should use [`Python::with_gil`]. /// /// A justified scenario for calling this function is during multi-phase interpreter /// initialization when [`Python::with_gil`] would fail before // this link is only valid on 3.8+not pypy and up. #[cfg_attr( all(Py_3_8, not(PyPy)), doc = "[`_Py_InitializeMain`](crate::ffi::_Py_InitializeMain)" )] #[cfg_attr(any(not(Py_3_8), PyPy), doc = "`_Py_InitializeMain`")] /// is called because the interpreter is only partially initialized. /// /// Behavior in other scenarios is not documented. #[inline] pub unsafe fn with_gil_unchecked<F, R>(f: F) -> R where F: for<'py> FnOnce(Python<'py>) -> R, { let guard = GILGuard::acquire_unchecked(); f(guard.python()) } } impl<'py> Python<'py> { /// Temporarily releases the GIL, thus allowing other Python threads to run. The GIL will be /// reacquired when `F`'s scope ends. /// /// If you don't need to touch the Python /// interpreter for some time and have other Python threads around, this will let you run /// Rust-only code while letting those other Python threads make progress. /// /// Only types that implement [`Ungil`] can cross the closure. See the /// [module level documentation](self) for more information. /// /// If you need to pass Python objects into the closure you can use [`Py`]`<T>`to create a /// reference independent of the GIL lifetime. However, you cannot do much with those without a /// [`Python`] token, for which you'd need to reacquire the GIL. /// /// # Example: Releasing the GIL while running a computation in Rust-only code /// /// ``` /// use pyo3::prelude::*; /// /// #[pyfunction] /// fn sum_numbers(py: Python<'_>, numbers: Vec<u32>) -> PyResult<u32> { /// // We release the GIL here so any other Python threads get a chance to run. /// py.allow_threads(move || { /// // An example of an "expensive" Rust calculation /// let sum = numbers.iter().sum(); /// /// Ok(sum) /// }) /// } /// # /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| -> PyResult<()> { /// # let fun = pyo3::wrap_pyfunction!(sum_numbers, py)?; /// # let res = fun.call1((vec![1_u32, 2, 3],))?; /// # assert_eq!(res.extract::<u32>()?, 6_u32); /// # Ok(()) /// # }) /// # } /// ``` /// /// Please see the [Parallelism] chapter of the guide for a thorough discussion of using /// [`Python::allow_threads`] in this manner. /// /// # Example: Passing borrowed Python references into the closure is not allowed /// /// ```compile_fail /// use pyo3::prelude::*; /// use pyo3::types::PyString; /// /// fn parallel_print(py: Python<'_>) { /// let s = PyString::new_bound(py, "This object cannot be accessed without holding the GIL >_<"); /// py.allow_threads(move || { /// println!("{:?}", s); // This causes a compile error. /// }); /// } /// ``` /// /// [`Py`]: crate::Py /// [`PyString`]: crate::types::PyString /// [auto-traits]: https://doc.rust-lang.org/nightly/unstable-book/language-features/auto-traits.html /// [Parallelism]: https://pyo3.rs/main/parallelism.html pub fn allow_threads<T, F>(self, f: F) -> T where F: Ungil + FnOnce() -> T, T: Ungil, { // Use a guard pattern to handle reacquiring the GIL, // so that the GIL will be reacquired even if `f` panics. // The `Send` bound on the closure prevents the user from // transferring the `Python` token into the closure. let _guard = unsafe { SuspendGIL::new() }; f() } /// Evaluates a Python expression in the given context and returns the result. /// /// If `globals` is `None`, it defaults to Python module `__main__`. /// If `locals` is `None`, it defaults to the value of `globals`. /// /// If `globals` doesn't contain `__builtins__`, default `__builtins__` /// will be added automatically. /// /// # Examples /// /// ``` /// # use pyo3::prelude::*; /// # use pyo3::ffi::c_str; /// # Python::with_gil(|py| { /// let result = py.eval(c_str!("[i * 10 for i in range(5)]"), None, None).unwrap(); /// let res: Vec<i64> = result.extract().unwrap(); /// assert_eq!(res, vec![0, 10, 20, 30, 40]) /// # }); /// ``` pub fn eval( self, code: &CStr, globals: Option<&Bound<'py, PyDict>>, locals: Option<&Bound<'py, PyDict>>, ) -> PyResult<Bound<'py, PyAny>> { self.run_code(code, ffi::Py_eval_input, globals, locals) } /// Deprecated name for [`Python::eval`]. #[deprecated(since = "0.23.0", note = "renamed to `Python::eval`")] #[track_caller] #[inline] pub fn eval_bound( self, code: &str, globals: Option<&Bound<'py, PyDict>>, locals: Option<&Bound<'py, PyDict>>, ) -> PyResult<Bound<'py, PyAny>> { let code = CString::new(code)?; self.eval(&code, globals, locals) } /// Executes one or more Python statements in the given context. /// /// If `globals` is `None`, it defaults to Python module `__main__`. /// If `locals` is `None`, it defaults to the value of `globals`. /// /// If `globals` doesn't contain `__builtins__`, default `__builtins__` /// will be added automatically. /// /// # Examples /// ``` /// use pyo3::{ /// prelude::*, /// types::{PyBytes, PyDict}, /// ffi::c_str, /// }; /// Python::with_gil(|py| { /// let locals = PyDict::new(py); /// py.run(c_str!( /// r#" /// import base64 /// s = 'Hello Rust!' /// ret = base64.b64encode(s.encode('utf-8')) /// "#), /// None, /// Some(&locals), /// ) /// .unwrap(); /// let ret = locals.get_item("ret").unwrap().unwrap(); /// let b64 = ret.downcast::<PyBytes>().unwrap(); /// assert_eq!(b64.as_bytes(), b"SGVsbG8gUnVzdCE="); /// }); /// ``` /// /// You can use [`py_run!`](macro.py_run.html) for a handy alternative of `run` /// if you don't need `globals` and unwrapping is OK. pub fn run( self, code: &CStr, globals: Option<&Bound<'py, PyDict>>, locals: Option<&Bound<'py, PyDict>>, ) -> PyResult<()> { let res = self.run_code(code, ffi::Py_file_input, globals, locals); res.map(|obj| { debug_assert!(obj.is_none()); }) } /// Deprecated name for [`Python::run`]. #[deprecated(since = "0.23.0", note = "renamed to `Python::run`")] #[track_caller] #[inline] pub fn run_bound( self, code: &str, globals: Option<&Bound<'py, PyDict>>, locals: Option<&Bound<'py, PyDict>>, ) -> PyResult<()> { let code = CString::new(code)?; self.run(&code, globals, locals) } /// Runs code in the given context. /// /// `start` indicates the type of input expected: one of `Py_single_input`, /// `Py_file_input`, or `Py_eval_input`. /// /// If `globals` is `None`, it defaults to Python module `__main__`. /// If `locals` is `None`, it defaults to the value of `globals`. fn run_code( self, code: &CStr, start: c_int, globals: Option<&Bound<'py, PyDict>>, locals: Option<&Bound<'py, PyDict>>, ) -> PyResult<Bound<'py, PyAny>> { let mptr = unsafe { ffi::compat::PyImport_AddModuleRef(ffi::c_str!("__main__").as_ptr()) .assume_owned_or_err(self)? }; let attr = mptr.getattr(crate::intern!(self, "__dict__"))?; let globals = match globals { Some(globals) => globals, None => attr.downcast::<PyDict>()?, }; let locals = locals.unwrap_or(globals); #[cfg(not(Py_3_10))] { // If `globals` don't provide `__builtins__`, most of the code will fail if Python // version is <3.10. That's probably not what user intended, so insert `__builtins__` // for them. // // See also: // - https://github.com/python/cpython/pull/24564 (the same fix in CPython 3.10) // - https://github.com/PyO3/pyo3/issues/3370 let builtins_s = crate::intern!(self, "__builtins__").as_ptr(); let has_builtins = unsafe { ffi::PyDict_Contains(globals.as_ptr(), builtins_s) }; if has_builtins == -1 { return Err(PyErr::fetch(self)); } if has_builtins == 0 { // Inherit current builtins. let builtins = unsafe { ffi::PyEval_GetBuiltins() }; // `PyDict_SetItem` doesn't take ownership of `builtins`, but `PyEval_GetBuiltins` // seems to return a borrowed reference, so no leak here. if unsafe { ffi::PyDict_SetItem(globals.as_ptr(), builtins_s, builtins) } == -1 { return Err(PyErr::fetch(self)); } } } let code_obj = unsafe { ffi::Py_CompileString(code.as_ptr(), ffi::c_str!("<string>").as_ptr(), start) .assume_owned_or_err(self)? }; unsafe { ffi::PyEval_EvalCode(code_obj.as_ptr(), globals.as_ptr(), locals.as_ptr()) .assume_owned_or_err(self) .downcast_into_unchecked() } } /// Gets the Python type object for type `T`. #[inline] pub fn get_type<T>(self) -> Bound<'py, PyType> where T: PyTypeInfo, { T::type_object(self) } /// Deprecated name for [`Python::get_type`]. #[deprecated(since = "0.23.0", note = "renamed to `Python::get_type`")] #[track_caller] #[inline] pub fn get_type_bound<T>(self) -> Bound<'py, PyType> where T: PyTypeInfo, { self.get_type::<T>() } /// Imports the Python module with the specified name. pub fn import<N>(self, name: N) -> PyResult<Bound<'py, PyModule>> where N: IntoPyObject<'py, Target = PyString>, { PyModule::import(self, name) } /// Deprecated name for [`Python::import`]. #[deprecated(since = "0.23.0", note = "renamed to `Python::import`")] #[allow(deprecated)] #[track_caller] #[inline] pub fn import_bound<N>(self, name: N) -> PyResult<Bound<'py, PyModule>> where N: IntoPy<Py<PyString>>, { self.import(name.into_py(self)) } /// Gets the Python builtin value `None`. #[allow(non_snake_case)] // the Python keyword starts with uppercase #[inline] pub fn None(self) -> PyObject { PyNone::get(self).to_owned().into_any().unbind() } /// Gets the Python builtin value `Ellipsis`, or `...`. #[allow(non_snake_case)] // the Python keyword starts with uppercase #[inline] pub fn Ellipsis(self) -> PyObject { PyEllipsis::get(self).to_owned().into_any().unbind() } /// Gets the Python builtin value `NotImplemented`. #[allow(non_snake_case)] // the Python keyword starts with uppercase #[inline] pub fn NotImplemented(self) -> PyObject { PyNotImplemented::get(self).to_owned().into_any().unbind() } /// Gets the running Python interpreter version as a string. /// /// # Examples /// ```rust /// # use pyo3::Python; /// Python::with_gil(|py| { /// // The full string could be, for example: /// // "3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]" /// assert!(py.version().starts_with("3.")); /// }); /// ``` pub fn version(self) -> &'py str { unsafe { CStr::from_ptr(ffi::Py_GetVersion()) .to_str() .expect("Python version string not UTF-8") } } /// Gets the running Python interpreter version as a struct similar to /// `sys.version_info`. /// /// # Examples /// ```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)); /// }); /// ``` pub fn version_info(self) -> PythonVersionInfo<'py> { let version_str = self.version(); // Portion of the version string returned by Py_GetVersion up to the first space is the // version number. let version_number_str = version_str.split(' ').next().unwrap_or(version_str); PythonVersionInfo::from_str(version_number_str).unwrap() } /// Lets the Python interpreter check and handle any pending signals. This will invoke the /// corresponding signal handlers registered in Python (if any). /// /// Returns `Err(`[`PyErr`]`)` if any signal handler raises an exception. /// /// These signals include `SIGINT` (normally raised by CTRL + C), which by default raises /// `KeyboardInterrupt`. For this reason it is good practice to call this function regularly /// as part of long-running Rust functions so that users can cancel it. /// /// # Example /// /// ```rust /// # #![allow(dead_code)] // this example is quite impractical to test /// use pyo3::prelude::*; /// /// # fn main() { /// #[pyfunction] /// fn loop_forever(py: Python<'_>) -> PyResult<()> { /// loop { /// // As this loop is infinite it should check for signals every once in a while. /// // Using `?` causes any `PyErr` (potentially containing `KeyboardInterrupt`) /// // to break out of the loop. /// py.check_signals()?; /// /// // do work here /// # break Ok(()) // don't actually loop forever /// } /// } /// # } /// ``` /// /// # Note /// /// This function calls [`PyErr_CheckSignals()`][1] which in turn may call signal handlers. /// As Python's [`signal`][2] API allows users to define custom signal handlers, calling this /// function allows arbitrary Python code inside signal handlers to run. /// /// If the function is called from a non-main thread, or under a non-main Python interpreter, /// it does nothing yet still returns `Ok(())`. /// /// [1]: https://docs.python.org/3/c-api/exceptions.html?highlight=pyerr_checksignals#c.PyErr_CheckSignals /// [2]: https://docs.python.org/3/library/signal.html pub fn check_signals(self) -> PyResult<()> { err::error_on_minusone(self, unsafe { ffi::PyErr_CheckSignals() }) } } impl<'unbound> Python<'unbound> { /// Unsafely creates a Python token with an unbounded lifetime. /// /// Many of PyO3 APIs use `Python<'_>` as proof that the GIL is held, but this function can be /// used to call them unsafely. /// /// # Safety /// /// - This token and any borrowed Python references derived from it can only be safely used /// whilst the currently executing thread is actually holding the GIL. /// - This function creates a token with an *unbounded* lifetime. Safe code can assume that /// holding a `Python<'py>` token means the GIL is and stays acquired for the lifetime `'py`. /// If you let it or borrowed Python references escape to safe code you are /// responsible for bounding the lifetime `'unbound` appropriately. For more on unbounded /// lifetimes, see the [nomicon]. /// /// [nomicon]: https://doc.rust-lang.org/nomicon/unbounded-lifetimes.html #[inline] pub unsafe fn assume_gil_acquired() -> Python<'unbound> { Python(PhantomData) } } #[cfg(test)] mod tests { use super::*; use crate::types::{IntoPyDict, PyList}; #[test] fn test_eval() { Python::with_gil(|py| { // Make sure builtin names are accessible let v: i32 = py .eval(ffi::c_str!("min(1, 2)"), None, None) .map_err(|e| e.display(py)) .unwrap() .extract() .unwrap(); assert_eq!(v, 1); let d = [("foo", 13)].into_py_dict(py).unwrap(); // Inject our own global namespace let v: i32 = py .eval(ffi::c_str!("foo + 29"), Some(&d), None) .unwrap() .extract() .unwrap(); assert_eq!(v, 42); // Inject our own local namespace let v: i32 = py .eval(ffi::c_str!("foo + 29"), None, Some(&d)) .unwrap() .extract() .unwrap(); assert_eq!(v, 42); // Make sure builtin names are still accessible when using a local namespace let v: i32 = py .eval(ffi::c_str!("min(foo, 2)"), None, Some(&d)) .unwrap() .extract() .unwrap(); assert_eq!(v, 2); }); } #[test] #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled fn test_allow_threads_releases_and_acquires_gil() { Python::with_gil(|py| { let b = std::sync::Arc::new(std::sync::Barrier::new(2)); let b2 = b.clone(); std::thread::spawn(move || Python::with_gil(|_| b2.wait())); py.allow_threads(|| { // If allow_threads does not release the GIL, this will deadlock because // the thread spawned above will never be able to acquire the GIL. b.wait(); }); unsafe { // If the GIL is not reacquired at the end of allow_threads, this call // will crash the Python interpreter. let tstate = ffi::PyEval_SaveThread(); ffi::PyEval_RestoreThread(tstate); } }); } #[test] fn test_allow_threads_panics_safely() { Python::with_gil(|py| { let result = std::panic::catch_unwind(|| unsafe { let py = Python::assume_gil_acquired(); py.allow_threads(|| { panic!("There was a panic!"); }); }); // Check panic was caught assert!(result.is_err()); // If allow_threads is implemented correctly, this thread still owns the GIL here // so the following Python calls should not cause crashes. let list = PyList::new(py, [1, 2, 3, 4]).unwrap(); assert_eq!(list.extract::<Vec<i32>>().unwrap(), vec![1, 2, 3, 4]); }); } #[cfg(not(pyo3_disable_reference_pool))] #[test] fn test_allow_threads_pass_stuff_in() { let list = Python::with_gil(|py| PyList::new(py, vec!["foo", "bar"]).unwrap().unbind()); let mut v = vec![1, 2, 3]; let a = std::sync::Arc::new(String::from("foo")); Python::with_gil(|py| { py.allow_threads(|| { drop((list, &mut v, a)); }); }); } #[test] #[cfg(not(Py_LIMITED_API))] fn test_acquire_gil() { const GIL_NOT_HELD: c_int = 0; const GIL_HELD: c_int = 1; // Before starting the interpreter the state of calling `PyGILState_Check` // seems to be undefined, so let's ensure that Python is up. #[cfg(not(any(PyPy, GraalPy)))] crate::prepare_freethreaded_python(); let state = unsafe { crate::ffi::PyGILState_Check() }; assert_eq!(state, GIL_NOT_HELD); Python::with_gil(|_| { let state = unsafe { crate::ffi::PyGILState_Check() }; assert_eq!(state, GIL_HELD); }); let state = unsafe { crate::ffi::PyGILState_Check() }; assert_eq!(state, GIL_NOT_HELD); } #[test] fn test_ellipsis() { Python::with_gil(|py| { assert_eq!(py.Ellipsis().to_string(), "Ellipsis"); let v = py .eval(ffi::c_str!("..."), None, None) .map_err(|e| e.display(py)) .unwrap(); assert!(v.eq(py.Ellipsis()).unwrap()); }); } #[test] fn test_py_run_inserts_globals() { use crate::types::dict::PyDictMethods; Python::with_gil(|py| { let namespace = PyDict::new(py); py.run( ffi::c_str!("class Foo: pass\na = int(3)"), Some(&namespace), Some(&namespace), ) .unwrap(); assert!(matches!(namespace.get_item("Foo"), Ok(Some(..)))); assert!(matches!(namespace.get_item("a"), Ok(Some(..)))); // 3.9 and older did not automatically insert __builtins__ if it wasn't inserted "by hand" #[cfg(not(Py_3_10))] assert!(matches!(namespace.get_item("__builtins__"), Ok(Some(..)))); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/internal.rs
//! Holding place for code which is not intended to be reachable from outside of PyO3. pub(crate) mod get_slot;
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pyclass.rs
//! `PyClass` and related traits. use crate::{ffi, impl_::pyclass::PyClassImpl, PyTypeInfo}; use std::{cmp::Ordering, os::raw::c_int}; mod create_type_object; mod gc; pub(crate) use self::create_type_object::{create_type_object, PyClassTypeObject}; pub use self::gc::{PyTraverseError, PyVisit}; /// Types that can be used as Python classes. /// /// The `#[pyclass]` attribute implements this trait for your Rust struct - /// you shouldn't implement this trait directly. pub trait PyClass: PyTypeInfo + PyClassImpl { /// Whether the pyclass is frozen. /// /// This can be enabled via `#[pyclass(frozen)]`. type Frozen: Frozen; } /// Operators for the `__richcmp__` method #[derive(Debug, Clone, Copy)] pub enum CompareOp { /// The *less than* operator. Lt = ffi::Py_LT as isize, /// The *less than or equal to* operator. Le = ffi::Py_LE as isize, /// The equality operator. Eq = ffi::Py_EQ as isize, /// The *not equal to* operator. Ne = ffi::Py_NE as isize, /// The *greater than* operator. Gt = ffi::Py_GT as isize, /// The *greater than or equal to* operator. Ge = ffi::Py_GE as isize, } impl CompareOp { /// Conversion from the C enum. pub fn from_raw(op: c_int) -> Option<Self> { match op { ffi::Py_LT => Some(CompareOp::Lt), ffi::Py_LE => Some(CompareOp::Le), ffi::Py_EQ => Some(CompareOp::Eq), ffi::Py_NE => Some(CompareOp::Ne), ffi::Py_GT => Some(CompareOp::Gt), ffi::Py_GE => Some(CompareOp::Ge), _ => None, } } /// Returns if a Rust [`std::cmp::Ordering`] matches this ordering query. /// /// Usage example: /// /// ```rust /// # use pyo3::prelude::*; /// # use pyo3::class::basic::CompareOp; /// /// #[pyclass] /// struct Size { /// size: usize, /// } /// /// #[pymethods] /// impl Size { /// fn __richcmp__(&self, other: &Size, op: CompareOp) -> bool { /// op.matches(self.size.cmp(&other.size)) /// } /// } /// ``` pub fn matches(&self, result: Ordering) -> bool { match self { CompareOp::Eq => result == Ordering::Equal, CompareOp::Ne => result != Ordering::Equal, CompareOp::Lt => result == Ordering::Less, CompareOp::Le => result != Ordering::Greater, CompareOp::Gt => result == Ordering::Greater, CompareOp::Ge => result != Ordering::Less, } } } /// A workaround for [associated const equality](https://github.com/rust-lang/rust/issues/92827). /// /// This serves to have True / False values in the [`PyClass`] trait's `Frozen` type. #[doc(hidden)] pub mod boolean_struct { pub(crate) mod private { use super::*; /// A way to "seal" the boolean traits. pub trait Boolean { const VALUE: bool; } impl Boolean for True { const VALUE: bool = true; } impl Boolean for False { const VALUE: bool = false; } } pub struct True(()); pub struct False(()); } /// A trait which is used to describe whether a `#[pyclass]` is frozen. #[doc(hidden)] pub trait Frozen: boolean_struct::private::Boolean {} impl Frozen for boolean_struct::True {} impl Frozen for boolean_struct::False {} mod tests { #[test] fn test_compare_op_matches() { use super::CompareOp; use std::cmp::Ordering; assert!(CompareOp::Eq.matches(Ordering::Equal)); assert!(CompareOp::Ne.matches(Ordering::Less)); assert!(CompareOp::Ge.matches(Ordering::Greater)); assert!(CompareOp::Gt.matches(Ordering::Greater)); assert!(CompareOp::Le.matches(Ordering::Equal)); assert!(CompareOp::Lt.matches(Ordering::Less)); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/ffi_ptr_ext.rs
use crate::sealed::Sealed; use crate::{ ffi, instance::{Borrowed, Bound}, PyAny, PyResult, Python, }; pub(crate) trait FfiPtrExt: Sealed { /// Assumes this pointer carries a Python reference which needs to be decref'd. /// /// If the pointer is NULL, this function will fetch an error. unsafe fn assume_owned_or_err(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>>; /// Same as `assume_owned_or_err`, but doesn't fetch an error on NULL. unsafe fn assume_owned_or_opt(self, py: Python<'_>) -> Option<Bound<'_, PyAny>>; /// Same as `assume_owned_or_err`, but panics on NULL. unsafe fn assume_owned(self, py: Python<'_>) -> Bound<'_, PyAny>; /// Same as `assume_owned_or_err`, but does not check for NULL. unsafe fn assume_owned_unchecked(self, py: Python<'_>) -> Bound<'_, PyAny>; /// Assumes this pointer is borrowed from a parent object. /// /// Warning: the lifetime `'a` is not bounded by the function arguments; the caller is /// responsible to ensure this is tied to some appropriate lifetime. unsafe fn assume_borrowed_or_err<'a>(self, py: Python<'_>) -> PyResult<Borrowed<'a, '_, PyAny>>; /// Same as `assume_borrowed_or_err`, but doesn't fetch an error on NULL. unsafe fn assume_borrowed_or_opt<'a>(self, py: Python<'_>) -> Option<Borrowed<'a, '_, PyAny>>; /// Same as `assume_borrowed_or_err`, but panics on NULL. unsafe fn assume_borrowed<'a>(self, py: Python<'_>) -> Borrowed<'a, '_, PyAny>; /// Same as `assume_borrowed_or_err`, but does not check for NULL. unsafe fn assume_borrowed_unchecked<'a>(self, py: Python<'_>) -> Borrowed<'a, '_, PyAny>; } impl FfiPtrExt for *mut ffi::PyObject { #[inline] unsafe fn assume_owned_or_err(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> { Bound::from_owned_ptr_or_err(py, self) } #[inline] unsafe fn assume_owned_or_opt(self, py: Python<'_>) -> Option<Bound<'_, PyAny>> { Bound::from_owned_ptr_or_opt(py, self) } #[inline] #[track_caller] unsafe fn assume_owned(self, py: Python<'_>) -> Bound<'_, PyAny> { Bound::from_owned_ptr(py, self) } #[inline] unsafe fn assume_owned_unchecked(self, py: Python<'_>) -> Bound<'_, PyAny> { Bound::from_owned_ptr_unchecked(py, self) } #[inline] unsafe fn assume_borrowed_or_err<'a>( self, py: Python<'_>, ) -> PyResult<Borrowed<'a, '_, PyAny>> { Borrowed::from_ptr_or_err(py, self) } #[inline] unsafe fn assume_borrowed_or_opt<'a>(self, py: Python<'_>) -> Option<Borrowed<'a, '_, PyAny>> { Borrowed::from_ptr_or_opt(py, self) } #[inline] #[track_caller] unsafe fn assume_borrowed<'a>(self, py: Python<'_>) -> Borrowed<'a, '_, PyAny> { Borrowed::from_ptr(py, self) } #[inline] unsafe fn assume_borrowed_unchecked<'a>(self, py: Python<'_>) -> Borrowed<'a, '_, PyAny> { Borrowed::from_ptr_unchecked(py, self) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/exceptions.rs
//! Exception and warning types defined by Python. //! //! The structs in this module represent Python's built-in exceptions and //! warnings, while the modules comprise structs representing errors defined in //! Python code. //! //! The latter are created with the //! [`import_exception`](crate::import_exception) macro, which you can use //! yourself to import Python classes that are ultimately derived from //! `BaseException`. use crate::{ffi, Bound, PyResult, Python}; use std::ffi::CStr; use std::ops; /// The boilerplate to convert between a Rust type and a Python exception. #[doc(hidden)] #[macro_export] macro_rules! impl_exception_boilerplate { ($name: ident) => { $crate::impl_exception_boilerplate_bound!($name); impl $crate::ToPyErr for $name {} }; } #[doc(hidden)] #[macro_export] macro_rules! impl_exception_boilerplate_bound { ($name: ident) => { impl $name { /// Creates a new [`PyErr`] of this type. /// /// [`PyErr`]: https://docs.rs/pyo3/latest/pyo3/struct.PyErr.html "PyErr in pyo3" #[inline] #[allow(dead_code)] pub fn new_err<A>(args: A) -> $crate::PyErr where A: $crate::PyErrArguments + ::std::marker::Send + ::std::marker::Sync + 'static, { $crate::PyErr::new::<$name, A>(args) } } }; } /// Defines a Rust type for an exception defined in Python code. /// /// # Syntax /// /// ```import_exception!(module, MyError)``` /// /// * `module` is the name of the containing module. /// * `MyError` is the name of the new exception type. /// /// # Examples /// ``` /// use pyo3::import_exception; /// use pyo3::types::IntoPyDict; /// use pyo3::Python; /// /// import_exception!(socket, gaierror); /// /// # fn main() -> pyo3::PyResult<()> { /// Python::with_gil(|py| { /// let ctx = [("gaierror", py.get_type::<gaierror>())].into_py_dict(py)?; /// pyo3::py_run!(py, *ctx, "import socket; assert gaierror is socket.gaierror"); /// # Ok(()) /// }) /// # } /// /// ``` #[macro_export] macro_rules! import_exception { ($module: expr, $name: ident) => { /// A Rust type representing an exception defined in Python code. /// /// This type was created by the [`pyo3::import_exception!`] macro - see its documentation /// for more information. /// /// [`pyo3::import_exception!`]: https://docs.rs/pyo3/latest/pyo3/macro.import_exception.html "import_exception in pyo3" #[repr(transparent)] #[allow(non_camel_case_types)] // E.g. `socket.herror` pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate!($name); $crate::pyobject_native_type_core!( $name, $name::type_object_raw, #module=::std::option::Option::Some(stringify!($module)) ); impl $name { fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject { use $crate::types::PyTypeMethods; static TYPE_OBJECT: $crate::impl_::exceptions::ImportedExceptionTypeObject = $crate::impl_::exceptions::ImportedExceptionTypeObject::new(stringify!($module), stringify!($name)); TYPE_OBJECT.get(py).as_type_ptr() } } }; } /// Variant of [`import_exception`](crate::import_exception) that does not emit code needed to /// use the imported exception type as a GIL Ref. /// /// This is useful only during migration as a way to avoid generating needless code. #[macro_export] macro_rules! import_exception_bound { ($module: expr, $name: ident) => { /// A Rust type representing an exception defined in Python code. /// /// This type was created by the [`pyo3::import_exception_bound!`] macro - see its documentation /// for more information. /// /// [`pyo3::import_exception_bound!`]: https://docs.rs/pyo3/latest/pyo3/macro.import_exception.html "import_exception in pyo3" #[repr(transparent)] #[allow(non_camel_case_types)] // E.g. `socket.herror` pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate_bound!($name); $crate::pyobject_native_type_info!( $name, $name::type_object_raw, ::std::option::Option::Some(stringify!($module)) ); impl $crate::types::DerefToPyAny for $name {} impl $name { fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject { use $crate::types::PyTypeMethods; static TYPE_OBJECT: $crate::impl_::exceptions::ImportedExceptionTypeObject = $crate::impl_::exceptions::ImportedExceptionTypeObject::new( stringify!($module), stringify!($name), ); TYPE_OBJECT.get(py).as_type_ptr() } } }; } /// Defines a new exception type. /// /// # Syntax /// /// * `module` is the name of the containing module. /// * `name` is the name of the new exception type. /// * `base` is the base class of `MyError`, usually [`PyException`]. /// * `doc` (optional) is the docstring visible to users (with `.__doc__` and `help()`) and /// /// accompanies your error type in your crate's documentation. /// /// # Examples /// /// ``` /// use pyo3::prelude::*; /// use pyo3::create_exception; /// use pyo3::exceptions::PyException; /// /// create_exception!(my_module, MyError, PyException, "Some description."); /// /// #[pyfunction] /// fn raise_myerror() -> PyResult<()> { /// let err = MyError::new_err("Some error happened."); /// Err(err) /// } /// /// #[pymodule] /// fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> { /// m.add("MyError", m.py().get_type::<MyError>())?; /// m.add_function(wrap_pyfunction!(raise_myerror, m)?)?; /// Ok(()) /// } /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| -> PyResult<()> { /// # let fun = wrap_pyfunction!(raise_myerror, py)?; /// # let locals = pyo3::types::PyDict::new(py); /// # locals.set_item("MyError", py.get_type::<MyError>())?; /// # locals.set_item("raise_myerror", fun)?; /// # /// # py.run(pyo3::ffi::c_str!( /// # "try: /// # raise_myerror() /// # except MyError as e: /// # assert e.__doc__ == 'Some description.' /// # assert str(e) == 'Some error happened.'"), /// # None, /// # Some(&locals), /// # )?; /// # /// # Ok(()) /// # }) /// # } /// ``` /// /// Python code can handle this exception like any other exception: /// /// ```python /// from my_module import MyError, raise_myerror /// /// try: /// raise_myerror() /// except MyError as e: /// assert e.__doc__ == 'Some description.' /// assert str(e) == 'Some error happened.' /// ``` /// #[macro_export] macro_rules! create_exception { ($module: expr, $name: ident, $base: ty) => { #[repr(transparent)] #[allow(non_camel_case_types)] // E.g. `socket.herror` pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate!($name); $crate::create_exception_type_object!($module, $name, $base, None); }; ($module: expr, $name: ident, $base: ty, $doc: expr) => { #[repr(transparent)] #[allow(non_camel_case_types)] // E.g. `socket.herror` #[doc = $doc] pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate!($name); $crate::create_exception_type_object!($module, $name, $base, Some($doc)); }; } /// `impl PyTypeInfo for $name` where `$name` is an /// exception newly defined in Rust code. #[doc(hidden)] #[macro_export] macro_rules! create_exception_type_object { ($module: expr, $name: ident, $base: ty, None) => { $crate::create_exception_type_object!($module, $name, $base, ::std::option::Option::None); }; ($module: expr, $name: ident, $base: ty, Some($doc: expr)) => { $crate::create_exception_type_object!($module, $name, $base, ::std::option::Option::Some($crate::ffi::c_str!($doc))); }; ($module: expr, $name: ident, $base: ty, $doc: expr) => { $crate::pyobject_native_type_core!( $name, $name::type_object_raw, #module=::std::option::Option::Some(stringify!($module)) ); impl $name { fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject { use $crate::sync::GILOnceCell; static TYPE_OBJECT: GILOnceCell<$crate::Py<$crate::types::PyType>> = GILOnceCell::new(); TYPE_OBJECT .get_or_init(py, || $crate::PyErr::new_type( py, $crate::ffi::c_str!(concat!(stringify!($module), ".", stringify!($name))), $doc, ::std::option::Option::Some(&py.get_type::<$base>()), ::std::option::Option::None, ).expect("Failed to initialize new exception type.") ).as_ptr() as *mut $crate::ffi::PyTypeObject } } }; } macro_rules! impl_native_exception ( ($name:ident, $exc_name:ident, $doc:expr, $layout:path $(, #checkfunction=$checkfunction:path)?) => ( #[doc = $doc] #[allow(clippy::upper_case_acronyms)] pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate!($name); $crate::pyobject_native_type!($name, $layout, |_py| unsafe { $crate::ffi::$exc_name as *mut $crate::ffi::PyTypeObject } $(, #checkfunction=$checkfunction)?); $crate::pyobject_subclassable_native_type!($name, $layout); ); ($name:ident, $exc_name:ident, $doc:expr) => ( impl_native_exception!($name, $exc_name, $doc, $crate::ffi::PyBaseExceptionObject); ) ); #[cfg(windows)] macro_rules! impl_windows_native_exception ( ($name:ident, $exc_name:ident, $doc:expr, $layout:path) => ( #[cfg(windows)] #[doc = $doc] #[allow(clippy::upper_case_acronyms)] pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate!($name); $crate::pyobject_native_type!($name, $layout, |_py| unsafe { $crate::ffi::$exc_name as *mut $crate::ffi::PyTypeObject }); ); ($name:ident, $exc_name:ident, $doc:expr) => ( impl_windows_native_exception!($name, $exc_name, $doc, $crate::ffi::PyBaseExceptionObject); ) ); macro_rules! native_doc( ($name: literal, $alt: literal) => ( concat!( "Represents Python's [`", $name, "`](https://docs.python.org/3/library/exceptions.html#", $name, ") exception. ", $alt ) ); ($name: literal) => ( concat!( " Represents Python's [`", $name, "`](https://docs.python.org/3/library/exceptions.html#", $name, ") exception. # Example: Raising ", $name, " from Rust This exception can be sent to Python code by converting it into a [`PyErr`](crate::PyErr), where Python code can then catch it. ``` use pyo3::prelude::*; use pyo3::exceptions::Py", $name, "; #[pyfunction] fn always_throws() -> PyResult<()> { let message = \"I'm ", $name ,", and I was raised from Rust.\"; Err(Py", $name, "::new_err(message)) } # # Python::with_gil(|py| { # let fun = pyo3::wrap_pyfunction!(always_throws, py).unwrap(); # let err = fun.call0().expect_err(\"called a function that should always return an error but the return value was Ok\"); # assert!(err.is_instance_of::<Py", $name, ">(py)) # }); ``` Python code: ```python from my_module import always_throws try: always_throws() except ", $name, " as e: print(f\"Caught an exception: {e}\") ``` # Example: Catching ", $name, " in Rust ``` use pyo3::prelude::*; use pyo3::exceptions::Py", $name, "; use pyo3::ffi::c_str; Python::with_gil(|py| { let result: PyResult<()> = py.run(c_str!(\"raise ", $name, "\"), None, None); let error_type = match result { Ok(_) => \"Not an error\", Err(error) if error.is_instance_of::<Py", $name, ">(py) => \"" , $name, "\", Err(_) => \"Some other error\", }; assert_eq!(error_type, \"", $name, "\"); }); ``` " ) ); ); impl_native_exception!( PyBaseException, PyExc_BaseException, native_doc!("BaseException"), ffi::PyBaseExceptionObject, #checkfunction=ffi::PyExceptionInstance_Check ); impl_native_exception!(PyException, PyExc_Exception, native_doc!("Exception")); impl_native_exception!( PyStopAsyncIteration, PyExc_StopAsyncIteration, native_doc!("StopAsyncIteration") ); impl_native_exception!( PyStopIteration, PyExc_StopIteration, native_doc!("StopIteration"), ffi::PyStopIterationObject ); impl_native_exception!( PyGeneratorExit, PyExc_GeneratorExit, native_doc!("GeneratorExit") ); impl_native_exception!( PyArithmeticError, PyExc_ArithmeticError, native_doc!("ArithmeticError") ); impl_native_exception!(PyLookupError, PyExc_LookupError, native_doc!("LookupError")); impl_native_exception!( PyAssertionError, PyExc_AssertionError, native_doc!("AssertionError") ); impl_native_exception!( PyAttributeError, PyExc_AttributeError, native_doc!("AttributeError") ); impl_native_exception!(PyBufferError, PyExc_BufferError, native_doc!("BufferError")); impl_native_exception!(PyEOFError, PyExc_EOFError, native_doc!("EOFError")); impl_native_exception!( PyFloatingPointError, PyExc_FloatingPointError, native_doc!("FloatingPointError") ); #[cfg(not(any(PyPy, GraalPy)))] impl_native_exception!( PyOSError, PyExc_OSError, native_doc!("OSError"), ffi::PyOSErrorObject ); #[cfg(any(PyPy, GraalPy))] impl_native_exception!(PyOSError, PyExc_OSError, native_doc!("OSError")); impl_native_exception!(PyImportError, PyExc_ImportError, native_doc!("ImportError")); impl_native_exception!( PyModuleNotFoundError, PyExc_ModuleNotFoundError, native_doc!("ModuleNotFoundError") ); impl_native_exception!(PyIndexError, PyExc_IndexError, native_doc!("IndexError")); impl_native_exception!(PyKeyError, PyExc_KeyError, native_doc!("KeyError")); impl_native_exception!( PyKeyboardInterrupt, PyExc_KeyboardInterrupt, native_doc!("KeyboardInterrupt") ); impl_native_exception!(PyMemoryError, PyExc_MemoryError, native_doc!("MemoryError")); impl_native_exception!(PyNameError, PyExc_NameError, native_doc!("NameError")); impl_native_exception!( PyOverflowError, PyExc_OverflowError, native_doc!("OverflowError") ); impl_native_exception!( PyRuntimeError, PyExc_RuntimeError, native_doc!("RuntimeError") ); impl_native_exception!( PyRecursionError, PyExc_RecursionError, native_doc!("RecursionError") ); impl_native_exception!( PyNotImplementedError, PyExc_NotImplementedError, native_doc!("NotImplementedError") ); #[cfg(not(any(PyPy, GraalPy)))] impl_native_exception!( PySyntaxError, PyExc_SyntaxError, native_doc!("SyntaxError"), ffi::PySyntaxErrorObject ); #[cfg(any(PyPy, GraalPy))] impl_native_exception!(PySyntaxError, PyExc_SyntaxError, native_doc!("SyntaxError")); impl_native_exception!( PyReferenceError, PyExc_ReferenceError, native_doc!("ReferenceError") ); impl_native_exception!(PySystemError, PyExc_SystemError, native_doc!("SystemError")); #[cfg(not(any(PyPy, GraalPy)))] impl_native_exception!( PySystemExit, PyExc_SystemExit, native_doc!("SystemExit"), ffi::PySystemExitObject ); #[cfg(any(PyPy, GraalPy))] impl_native_exception!(PySystemExit, PyExc_SystemExit, native_doc!("SystemExit")); impl_native_exception!(PyTypeError, PyExc_TypeError, native_doc!("TypeError")); impl_native_exception!( PyUnboundLocalError, PyExc_UnboundLocalError, native_doc!("UnboundLocalError") ); #[cfg(not(any(PyPy, GraalPy)))] impl_native_exception!( PyUnicodeError, PyExc_UnicodeError, native_doc!("UnicodeError"), ffi::PyUnicodeErrorObject ); #[cfg(any(PyPy, GraalPy))] impl_native_exception!( PyUnicodeError, PyExc_UnicodeError, native_doc!("UnicodeError") ); // these four errors need arguments, so they're too annoying to write tests for using macros... impl_native_exception!( PyUnicodeDecodeError, PyExc_UnicodeDecodeError, native_doc!("UnicodeDecodeError", "") ); impl_native_exception!( PyUnicodeEncodeError, PyExc_UnicodeEncodeError, native_doc!("UnicodeEncodeError", "") ); impl_native_exception!( PyUnicodeTranslateError, PyExc_UnicodeTranslateError, native_doc!("UnicodeTranslateError", "") ); #[cfg(Py_3_11)] impl_native_exception!( PyBaseExceptionGroup, PyExc_BaseExceptionGroup, native_doc!("BaseExceptionGroup", "") ); impl_native_exception!(PyValueError, PyExc_ValueError, native_doc!("ValueError")); impl_native_exception!( PyZeroDivisionError, PyExc_ZeroDivisionError, native_doc!("ZeroDivisionError") ); impl_native_exception!( PyBlockingIOError, PyExc_BlockingIOError, native_doc!("BlockingIOError") ); impl_native_exception!( PyBrokenPipeError, PyExc_BrokenPipeError, native_doc!("BrokenPipeError") ); impl_native_exception!( PyChildProcessError, PyExc_ChildProcessError, native_doc!("ChildProcessError") ); impl_native_exception!( PyConnectionError, PyExc_ConnectionError, native_doc!("ConnectionError") ); impl_native_exception!( PyConnectionAbortedError, PyExc_ConnectionAbortedError, native_doc!("ConnectionAbortedError") ); impl_native_exception!( PyConnectionRefusedError, PyExc_ConnectionRefusedError, native_doc!("ConnectionRefusedError") ); impl_native_exception!( PyConnectionResetError, PyExc_ConnectionResetError, native_doc!("ConnectionResetError") ); impl_native_exception!( PyFileExistsError, PyExc_FileExistsError, native_doc!("FileExistsError") ); impl_native_exception!( PyFileNotFoundError, PyExc_FileNotFoundError, native_doc!("FileNotFoundError") ); impl_native_exception!( PyInterruptedError, PyExc_InterruptedError, native_doc!("InterruptedError") ); impl_native_exception!( PyIsADirectoryError, PyExc_IsADirectoryError, native_doc!("IsADirectoryError") ); impl_native_exception!( PyNotADirectoryError, PyExc_NotADirectoryError, native_doc!("NotADirectoryError") ); impl_native_exception!( PyPermissionError, PyExc_PermissionError, native_doc!("PermissionError") ); impl_native_exception!( PyProcessLookupError, PyExc_ProcessLookupError, native_doc!("ProcessLookupError") ); impl_native_exception!( PyTimeoutError, PyExc_TimeoutError, native_doc!("TimeoutError") ); impl_native_exception!( PyEnvironmentError, PyExc_EnvironmentError, native_doc!("EnvironmentError") ); impl_native_exception!(PyIOError, PyExc_IOError, native_doc!("IOError")); #[cfg(windows)] impl_windows_native_exception!( PyWindowsError, PyExc_WindowsError, native_doc!("WindowsError") ); impl PyUnicodeDecodeError { /// Creates a Python `UnicodeDecodeError`. pub fn new<'py>( py: Python<'py>, encoding: &CStr, input: &[u8], range: ops::Range<usize>, reason: &CStr, ) -> PyResult<Bound<'py, PyUnicodeDecodeError>> { use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; unsafe { ffi::PyUnicodeDecodeError_Create( encoding.as_ptr(), input.as_ptr().cast(), input.len() as ffi::Py_ssize_t, range.start as ffi::Py_ssize_t, range.end as ffi::Py_ssize_t, reason.as_ptr(), ) .assume_owned_or_err(py) } .downcast_into() } /// Deprecated name for [`PyUnicodeDecodeError::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyUnicodeDecodeError::new`")] #[inline] pub fn new_bound<'py>( py: Python<'py>, encoding: &CStr, input: &[u8], range: ops::Range<usize>, reason: &CStr, ) -> PyResult<Bound<'py, PyUnicodeDecodeError>> { Self::new(py, encoding, input, range, reason) } /// Creates a Python `UnicodeDecodeError` from a Rust UTF-8 decoding error. /// /// # Examples /// /// ``` /// #![cfg_attr(invalid_from_utf8_lint, allow(invalid_from_utf8))] /// use pyo3::prelude::*; /// use pyo3::exceptions::PyUnicodeDecodeError; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let invalid_utf8 = b"fo\xd8o"; /// let err = std::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); /// let decode_err = PyUnicodeDecodeError::new_utf8(py, invalid_utf8, err)?; /// assert_eq!( /// decode_err.to_string(), /// "'utf-8' codec can't decode byte 0xd8 in position 2: invalid utf-8" /// ); /// Ok(()) /// }) /// # } pub fn new_utf8<'py>( py: Python<'py>, input: &[u8], err: std::str::Utf8Error, ) -> PyResult<Bound<'py, PyUnicodeDecodeError>> { let pos = err.valid_up_to(); PyUnicodeDecodeError::new( py, ffi::c_str!("utf-8"), input, pos..(pos + 1), ffi::c_str!("invalid utf-8"), ) } /// Deprecated name for [`PyUnicodeDecodeError::new_utf8`]. #[deprecated(since = "0.23.0", note = "renamed to `PyUnicodeDecodeError::new_utf8`")] #[inline] pub fn new_utf8_bound<'py>( py: Python<'py>, input: &[u8], err: std::str::Utf8Error, ) -> PyResult<Bound<'py, PyUnicodeDecodeError>> { Self::new_utf8(py, input, err) } } impl_native_exception!(PyWarning, PyExc_Warning, native_doc!("Warning")); impl_native_exception!(PyUserWarning, PyExc_UserWarning, native_doc!("UserWarning")); impl_native_exception!( PyDeprecationWarning, PyExc_DeprecationWarning, native_doc!("DeprecationWarning") ); impl_native_exception!( PyPendingDeprecationWarning, PyExc_PendingDeprecationWarning, native_doc!("PendingDeprecationWarning") ); impl_native_exception!( PySyntaxWarning, PyExc_SyntaxWarning, native_doc!("SyntaxWarning") ); impl_native_exception!( PyRuntimeWarning, PyExc_RuntimeWarning, native_doc!("RuntimeWarning") ); impl_native_exception!( PyFutureWarning, PyExc_FutureWarning, native_doc!("FutureWarning") ); impl_native_exception!( PyImportWarning, PyExc_ImportWarning, native_doc!("ImportWarning") ); impl_native_exception!( PyUnicodeWarning, PyExc_UnicodeWarning, native_doc!("UnicodeWarning") ); impl_native_exception!( PyBytesWarning, PyExc_BytesWarning, native_doc!("BytesWarning") ); impl_native_exception!( PyResourceWarning, PyExc_ResourceWarning, native_doc!("ResourceWarning") ); #[cfg(Py_3_10)] impl_native_exception!( PyEncodingWarning, PyExc_EncodingWarning, native_doc!("EncodingWarning") ); #[cfg(test)] macro_rules! test_exception { ($exc_ty:ident $(, |$py:tt| $constructor:expr )?) => { #[allow(non_snake_case)] #[test] fn $exc_ty () { use super::$exc_ty; $crate::Python::with_gil(|py| { use $crate::types::PyAnyMethods; let err: $crate::PyErr = { None $( .or(Some({ let $py = py; $constructor })) )? .unwrap_or($exc_ty::new_err("a test exception")) }; assert!(err.is_instance_of::<$exc_ty>(py)); let value = err.value(py).as_any().downcast::<$exc_ty>().unwrap(); assert!($crate::PyErr::from(value.clone()).is_instance_of::<$exc_ty>(py)); }) } }; } /// Exceptions defined in Python's [`asyncio`](https://docs.python.org/3/library/asyncio.html) /// module. pub mod asyncio { import_exception!(asyncio, CancelledError); import_exception!(asyncio, InvalidStateError); import_exception!(asyncio, TimeoutError); import_exception!(asyncio, IncompleteReadError); import_exception!(asyncio, LimitOverrunError); import_exception!(asyncio, QueueEmpty); import_exception!(asyncio, QueueFull); #[cfg(test)] mod tests { test_exception!(CancelledError); test_exception!(InvalidStateError); test_exception!(TimeoutError); test_exception!(IncompleteReadError, |_| IncompleteReadError::new_err(( "partial", "expected" ))); test_exception!(LimitOverrunError, |_| LimitOverrunError::new_err(( "message", "consumed" ))); test_exception!(QueueEmpty); test_exception!(QueueFull); } } /// Exceptions defined in Python's [`socket`](https://docs.python.org/3/library/socket.html) /// module. pub mod socket { import_exception!(socket, herror); import_exception!(socket, gaierror); import_exception!(socket, timeout); #[cfg(test)] mod tests { test_exception!(herror); test_exception!(gaierror); test_exception!(timeout); } } #[cfg(test)] mod tests { use super::*; use crate::types::any::PyAnyMethods; use crate::types::{IntoPyDict, PyDict}; use crate::PyErr; import_exception_bound!(socket, gaierror); import_exception_bound!(email.errors, MessageError); #[test] fn test_check_exception() { Python::with_gil(|py| { let err: PyErr = gaierror::new_err(()); let socket = py .import("socket") .map_err(|e| e.display(py)) .expect("could not import socket"); let d = PyDict::new(py); d.set_item("socket", socket) .map_err(|e| e.display(py)) .expect("could not setitem"); d.set_item("exc", err) .map_err(|e| e.display(py)) .expect("could not setitem"); py.run( ffi::c_str!("assert isinstance(exc, socket.gaierror)"), None, Some(&d), ) .map_err(|e| e.display(py)) .expect("assertion failed"); }); } #[test] fn test_check_exception_nested() { Python::with_gil(|py| { let err: PyErr = MessageError::new_err(()); let email = py .import("email") .map_err(|e| e.display(py)) .expect("could not import email"); let d = PyDict::new(py); d.set_item("email", email) .map_err(|e| e.display(py)) .expect("could not setitem"); d.set_item("exc", err) .map_err(|e| e.display(py)) .expect("could not setitem"); py.run( ffi::c_str!("assert isinstance(exc, email.errors.MessageError)"), None, Some(&d), ) .map_err(|e| e.display(py)) .expect("assertion failed"); }); } #[test] fn custom_exception() { create_exception!(mymodule, CustomError, PyException); Python::with_gil(|py| { let error_type = py.get_type::<CustomError>(); let ctx = [("CustomError", error_type)].into_py_dict(py).unwrap(); let type_description: String = py .eval(ffi::c_str!("str(CustomError)"), None, Some(&ctx)) .unwrap() .extract() .unwrap(); assert_eq!(type_description, "<class 'mymodule.CustomError'>"); py.run( ffi::c_str!("assert CustomError('oops').args == ('oops',)"), None, Some(&ctx), ) .unwrap(); py.run( ffi::c_str!("assert CustomError.__doc__ is None"), None, Some(&ctx), ) .unwrap(); }); } #[test] fn custom_exception_dotted_module() { create_exception!(mymodule.exceptions, CustomError, PyException); Python::with_gil(|py| { let error_type = py.get_type::<CustomError>(); let ctx = [("CustomError", error_type)].into_py_dict(py).unwrap(); let type_description: String = py .eval(ffi::c_str!("str(CustomError)"), None, Some(&ctx)) .unwrap() .extract() .unwrap(); assert_eq!( type_description, "<class 'mymodule.exceptions.CustomError'>" ); }); } #[test] fn custom_exception_doc() { create_exception!(mymodule, CustomError, PyException, "Some docs"); Python::with_gil(|py| { let error_type = py.get_type::<CustomError>(); let ctx = [("CustomError", error_type)].into_py_dict(py).unwrap(); let type_description: String = py .eval(ffi::c_str!("str(CustomError)"), None, Some(&ctx)) .unwrap() .extract() .unwrap(); assert_eq!(type_description, "<class 'mymodule.CustomError'>"); py.run( ffi::c_str!("assert CustomError('oops').args == ('oops',)"), None, Some(&ctx), ) .unwrap(); py.run( ffi::c_str!("assert CustomError.__doc__ == 'Some docs'"), None, Some(&ctx), ) .unwrap(); }); } #[test] fn custom_exception_doc_expr() { create_exception!( mymodule, CustomError, PyException, concat!("Some", " more ", stringify!(docs)) ); Python::with_gil(|py| { let error_type = py.get_type::<CustomError>(); let ctx = [("CustomError", error_type)].into_py_dict(py).unwrap(); let type_description: String = py .eval(ffi::c_str!("str(CustomError)"), None, Some(&ctx)) .unwrap() .extract() .unwrap(); assert_eq!(type_description, "<class 'mymodule.CustomError'>"); py.run( ffi::c_str!("assert CustomError('oops').args == ('oops',)"), None, Some(&ctx), ) .unwrap(); py.run( ffi::c_str!("assert CustomError.__doc__ == 'Some more docs'"), None, Some(&ctx), ) .unwrap(); }); } #[test] fn native_exception_debug() { Python::with_gil(|py| { let exc = py .run(ffi::c_str!("raise Exception('banana')"), None, None) .expect_err("raising should have given us an error") .into_value(py) .into_bound(py); assert_eq!( format!("{:?}", exc), exc.repr().unwrap().extract::<String>().unwrap() ); }); } #[test] fn native_exception_display() { Python::with_gil(|py| { let exc = py .run(ffi::c_str!("raise Exception('banana')"), None, None) .expect_err("raising should have given us an error") .into_value(py) .into_bound(py); assert_eq!( exc.to_string(), exc.str().unwrap().extract::<String>().unwrap() ); }); } #[test] fn unicode_decode_error() { let invalid_utf8 = b"fo\xd8o"; #[cfg_attr(invalid_from_utf8_lint, allow(invalid_from_utf8))] let err = std::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); Python::with_gil(|py| { let decode_err = PyUnicodeDecodeError::new_utf8(py, invalid_utf8, err).unwrap(); assert_eq!( format!("{:?}", decode_err), "UnicodeDecodeError('utf-8', b'fo\\xd8o', 2, 3, 'invalid utf-8')" ); // Restoring should preserve the same error let e: PyErr = decode_err.into(); e.restore(py); assert_eq!( PyErr::fetch(py).to_string(), "UnicodeDecodeError: \'utf-8\' codec can\'t decode byte 0xd8 in position 2: invalid utf-8" ); }); } #[cfg(Py_3_11)] test_exception!(PyBaseExceptionGroup, |_| PyBaseExceptionGroup::new_err(( "msg", vec![PyValueError::new_err("err")] ))); test_exception!(PyBaseException); test_exception!(PyException); test_exception!(PyStopAsyncIteration); test_exception!(PyStopIteration); test_exception!(PyGeneratorExit); test_exception!(PyArithmeticError); test_exception!(PyLookupError); test_exception!(PyAssertionError); test_exception!(PyAttributeError); test_exception!(PyBufferError); test_exception!(PyEOFError); test_exception!(PyFloatingPointError); test_exception!(PyOSError); test_exception!(PyImportError); test_exception!(PyModuleNotFoundError); test_exception!(PyIndexError); test_exception!(PyKeyError); test_exception!(PyKeyboardInterrupt); test_exception!(PyMemoryError); test_exception!(PyNameError); test_exception!(PyOverflowError); test_exception!(PyRuntimeError); test_exception!(PyRecursionError); test_exception!(PyNotImplementedError); test_exception!(PySyntaxError); test_exception!(PyReferenceError); test_exception!(PySystemError); test_exception!(PySystemExit); test_exception!(PyTypeError); test_exception!(PyUnboundLocalError); test_exception!(PyUnicodeError); test_exception!(PyUnicodeDecodeError, |py| { let invalid_utf8 = b"fo\xd8o"; #[cfg_attr(invalid_from_utf8_lint, allow(invalid_from_utf8))] let err = std::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); PyErr::from_value( PyUnicodeDecodeError::new_utf8(py, invalid_utf8, err) .unwrap() .into_any(), ) }); test_exception!(PyUnicodeEncodeError, |py| py .eval(ffi::c_str!("chr(40960).encode('ascii')"), None, None) .unwrap_err()); test_exception!(PyUnicodeTranslateError, |_| { PyUnicodeTranslateError::new_err(("\u{3042}", 0, 1, "ouch")) }); test_exception!(PyValueError); test_exception!(PyZeroDivisionError); test_exception!(PyBlockingIOError); test_exception!(PyBrokenPipeError); test_exception!(PyChildProcessError); test_exception!(PyConnectionError); test_exception!(PyConnectionAbortedError); test_exception!(PyConnectionRefusedError); test_exception!(PyConnectionResetError); test_exception!(PyFileExistsError); test_exception!(PyFileNotFoundError); test_exception!(PyInterruptedError); test_exception!(PyIsADirectoryError); test_exception!(PyNotADirectoryError); test_exception!(PyPermissionError); test_exception!(PyProcessLookupError); test_exception!(PyTimeoutError); test_exception!(PyEnvironmentError); test_exception!(PyIOError); #[cfg(windows)] test_exception!(PyWindowsError); test_exception!(PyWarning); test_exception!(PyUserWarning); test_exception!(PyDeprecationWarning); test_exception!(PyPendingDeprecationWarning); test_exception!(PySyntaxWarning); test_exception!(PyRuntimeWarning); test_exception!(PyFutureWarning); test_exception!(PyImportWarning); test_exception!(PyUnicodeWarning); test_exception!(PyBytesWarning); #[cfg(Py_3_10)] test_exception!(PyEncodingWarning); }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/sealed.rs
use crate::types::{ PyBool, PyByteArray, PyBytes, PyCapsule, PyComplex, PyDict, PyFloat, PyFrozenSet, PyList, PyMapping, PyMappingProxy, PyModule, PySequence, PySet, PySlice, PyString, PyTraceback, PyTuple, PyType, PyWeakref, PyWeakrefProxy, PyWeakrefReference, }; use crate::{ffi, Bound, PyAny, PyResult}; use crate::pyclass_init::PyClassInitializer; use crate::impl_::{ pyclass_init::PyNativeTypeInitializer, pymethods::PyMethodDef, pymodule::{AddClassToModule, AddTypeToModule, ModuleDef}, }; pub trait Sealed {} // for FfiPtrExt impl Sealed for *mut ffi::PyObject {} // for PyResultExt impl Sealed for PyResult<Bound<'_, PyAny>> {} // for Py(...)Methods impl Sealed for Bound<'_, PyAny> {} impl Sealed for Bound<'_, PyBool> {} impl Sealed for Bound<'_, PyByteArray> {} impl Sealed for Bound<'_, PyBytes> {} impl Sealed for Bound<'_, PyCapsule> {} impl Sealed for Bound<'_, PyComplex> {} impl Sealed for Bound<'_, PyDict> {} impl Sealed for Bound<'_, PyFloat> {} impl Sealed for Bound<'_, PyFrozenSet> {} impl Sealed for Bound<'_, PyList> {} impl Sealed for Bound<'_, PyMapping> {} impl Sealed for Bound<'_, PyMappingProxy> {} impl Sealed for Bound<'_, PyModule> {} impl Sealed for Bound<'_, PySequence> {} impl Sealed for Bound<'_, PySet> {} impl Sealed for Bound<'_, PySlice> {} impl Sealed for Bound<'_, PyString> {} impl Sealed for Bound<'_, PyTraceback> {} impl Sealed for Bound<'_, PyTuple> {} impl Sealed for Bound<'_, PyType> {} impl Sealed for Bound<'_, PyWeakref> {} impl Sealed for Bound<'_, PyWeakrefProxy> {} impl Sealed for Bound<'_, PyWeakrefReference> {} impl<T> Sealed for AddTypeToModule<T> {} impl<T> Sealed for AddClassToModule<T> {} impl Sealed for PyMethodDef {} impl Sealed for ModuleDef {} impl<T: crate::type_object::PyTypeInfo> Sealed for PyNativeTypeInitializer<T> {} impl<T: crate::pyclass::PyClass> Sealed for PyClassInitializer<T> {} impl Sealed for std::sync::Once {}
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/test_utils.rs
use crate as pyo3; include!("../tests/common.rs");
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/conversion.rs
//! Defines conversions between Rust and Python types. use crate::err::PyResult; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; use crate::pyclass::boolean_struct::False; use crate::types::any::PyAnyMethods; use crate::types::PyTuple; use crate::{ ffi, Borrowed, Bound, BoundObject, Py, PyAny, PyClass, PyErr, PyObject, PyRef, PyRefMut, Python, }; use std::convert::Infallible; /// Returns a borrowed pointer to a Python object. /// /// The returned pointer will be valid for as long as `self` is. It may be null depending on the /// implementation. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::ffi; /// /// Python::with_gil(|py| { /// let s = "foo".into_pyobject(py)?; /// let ptr = s.as_ptr(); /// /// let is_really_a_pystring = unsafe { ffi::PyUnicode_CheckExact(ptr) }; /// assert_eq!(is_really_a_pystring, 1); /// # Ok::<_, PyErr>(()) /// }) /// # .unwrap(); /// ``` /// /// # Safety /// /// For callers, it is your responsibility to make sure that the underlying Python object is not dropped too /// early. For example, the following code will cause undefined behavior: /// /// ```rust,no_run /// # use pyo3::prelude::*; /// # use pyo3::ffi; /// # /// Python::with_gil(|py| { /// // ERROR: calling `.as_ptr()` will throw away the temporary object and leave `ptr` dangling. /// let ptr: *mut ffi::PyObject = 0xabad1dea_u32.into_pyobject(py)?.as_ptr(); /// /// let isnt_a_pystring = unsafe { /// // `ptr` is dangling, this is UB /// ffi::PyUnicode_CheckExact(ptr) /// }; /// # assert_eq!(isnt_a_pystring, 0); /// # Ok::<_, PyErr>(()) /// }) /// # .unwrap(); /// ``` /// /// This happens because the pointer returned by `as_ptr` does not carry any lifetime information /// and the Python object is dropped immediately after the `0xabad1dea_u32.into_pyobject(py).as_ptr()` /// expression is evaluated. To fix the problem, bind Python object to a local variable like earlier /// to keep the Python object alive until the end of its scope. /// /// Implementors must ensure this returns a valid pointer to a Python object, which borrows a reference count from `&self`. pub unsafe trait AsPyPointer { /// Returns the underlying FFI pointer as a borrowed pointer. fn as_ptr(&self) -> *mut ffi::PyObject; } /// Conversion trait that allows various objects to be converted into `PyObject`. #[deprecated( since = "0.23.0", note = "`ToPyObject` is going to be replaced by `IntoPyObject`. See the migration guide (https://pyo3.rs/v0.23/migration) for more information." )] pub trait ToPyObject { /// Converts self into a Python object. fn to_object(&self, py: Python<'_>) -> PyObject; } /// Defines a conversion from a Rust type to a Python object. /// /// It functions similarly to std's [`Into`] trait, but requires a [GIL token](Python) /// as an argument. Many functions and traits internal to PyO3 require this trait as a bound, /// so a lack of this trait can manifest itself in different error messages. /// /// # Examples /// ## With `#[pyclass]` /// The easiest way to implement `IntoPy` is by exposing a struct as a native Python object /// by annotating it with [`#[pyclass]`](crate::prelude::pyclass). /// /// ```rust /// use pyo3::prelude::*; /// /// # #[allow(dead_code)] /// #[pyclass] /// struct Number { /// #[pyo3(get, set)] /// value: i32, /// } /// ``` /// Python code will see this as an instance of the `Number` class with a `value` attribute. /// /// ## Conversion to a Python object /// /// However, it may not be desirable to expose the existence of `Number` to Python code. /// `IntoPy` allows us to define a conversion to an appropriate Python object. /// ```rust /// #![allow(deprecated)] /// use pyo3::prelude::*; /// /// # #[allow(dead_code)] /// struct Number { /// value: i32, /// } /// /// impl IntoPy<PyObject> for Number { /// fn into_py(self, py: Python<'_>) -> PyObject { /// // delegates to i32's IntoPy implementation. /// self.value.into_py(py) /// } /// } /// ``` /// Python code will see this as an `int` object. /// /// ## Dynamic conversion into Python objects. /// It is also possible to return a different Python object depending on some condition. /// This is useful for types like enums that can carry different types. /// /// ```rust /// #![allow(deprecated)] /// use pyo3::prelude::*; /// /// enum Value { /// Integer(i32), /// String(String), /// None, /// } /// /// impl IntoPy<PyObject> for Value { /// fn into_py(self, py: Python<'_>) -> PyObject { /// match self { /// Self::Integer(val) => val.into_py(py), /// Self::String(val) => val.into_py(py), /// Self::None => py.None(), /// } /// } /// } /// # fn main() { /// # Python::with_gil(|py| { /// # let v = Value::Integer(73).into_py(py); /// # let v = v.extract::<i32>(py).unwrap(); /// # /// # let v = Value::String("foo".into()).into_py(py); /// # let v = v.extract::<String>(py).unwrap(); /// # /// # let v = Value::None.into_py(py); /// # let v = v.extract::<Option<Vec<i32>>>(py).unwrap(); /// # }); /// # } /// ``` /// Python code will see this as any of the `int`, `string` or `None` objects. #[cfg_attr( diagnostic_namespace, diagnostic::on_unimplemented( message = "`{Self}` cannot be converted to a Python object", note = "`IntoPy` is automatically implemented by the `#[pyclass]` macro", note = "if you do not wish to have a corresponding Python type, implement it manually", note = "if you do not own `{Self}` you can perform a manual conversion to one of the types in `pyo3::types::*`" ) )] #[deprecated( since = "0.23.0", note = "`IntoPy` is going to be replaced by `IntoPyObject`. See the migration guide (https://pyo3.rs/v0.23/migration) for more information." )] pub trait IntoPy<T>: Sized { /// Performs the conversion. fn into_py(self, py: Python<'_>) -> T; } /// Defines a conversion from a Rust type to a Python object, which may fail. /// /// It functions similarly to std's [`TryInto`] trait, but requires a [GIL token](Python) /// as an argument. #[cfg_attr( diagnostic_namespace, diagnostic::on_unimplemented( message = "`{Self}` cannot be converted to a Python object", note = "`IntoPyObject` is automatically implemented by the `#[pyclass]` macro", note = "if you do not wish to have a corresponding Python type, implement it manually", note = "if you do not own `{Self}` you can perform a manual conversion to one of the types in `pyo3::types::*`" ) )] pub trait IntoPyObject<'py>: Sized { /// The Python output type type Target; /// The smart pointer type to use. /// /// This will usually be [`Bound<'py, Target>`], but in special cases [`Borrowed<'a, 'py, Target>`] can be /// used to minimize reference counting overhead. type Output: BoundObject<'py, Self::Target>; /// The type returned in the event of a conversion error. type Error: Into<PyErr>; /// Performs the conversion. fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>; /// Extracts the type hint information for this type when it appears as a return value. /// /// For example, `Vec<u32>` would return `List[int]`. /// The default implementation returns `Any`, which is correct for any type. /// /// For most types, the return value for this method will be identical to that of [`FromPyObject::type_input`]. /// It may be different for some types, such as `Dict`, to allow duck-typing: functions return `Dict` but take `Mapping` as argument. #[cfg(feature = "experimental-inspect")] fn type_output() -> TypeInfo { TypeInfo::Any } /// Converts sequence of Self into a Python object. Used to specialize `Vec<u8>`, `[u8; N]` /// and `SmallVec<[u8; N]>` as a sequence of bytes into a `bytes` object. #[doc(hidden)] fn owned_sequence_into_pyobject<I>( iter: I, py: Python<'py>, _: private::Token, ) -> Result<Bound<'py, PyAny>, PyErr> where I: IntoIterator<Item = Self> + AsRef<[Self]>, I::IntoIter: ExactSizeIterator<Item = Self>, { let mut iter = iter.into_iter().map(|e| { e.into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::into_bound) .map_err(Into::into) }); let list = crate::types::list::try_new_from_iter(py, &mut iter); list.map(Bound::into_any) } /// Converts sequence of Self into a Python object. Used to specialize `&[u8]` and `Cow<[u8]>` /// as a sequence of bytes into a `bytes` object. #[doc(hidden)] fn borrowed_sequence_into_pyobject<I>( iter: I, py: Python<'py>, _: private::Token, ) -> Result<Bound<'py, PyAny>, PyErr> where Self: private::Reference, I: IntoIterator<Item = Self> + AsRef<[<Self as private::Reference>::BaseType]>, I::IntoIter: ExactSizeIterator<Item = Self>, { let mut iter = iter.into_iter().map(|e| { e.into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::into_bound) .map_err(Into::into) }); let list = crate::types::list::try_new_from_iter(py, &mut iter); list.map(Bound::into_any) } } pub(crate) mod private { pub struct Token; pub trait Reference { type BaseType; } impl<T> Reference for &'_ T { type BaseType = T; } } impl<'py, T> IntoPyObject<'py> for Bound<'py, T> { type Target = T; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self) } } impl<'a, 'py, T> IntoPyObject<'py> for &'a Bound<'py, T> { type Target = T; type Output = Borrowed<'a, 'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.as_borrowed()) } } impl<'a, 'py, T> IntoPyObject<'py> for Borrowed<'a, 'py, T> { type Target = T; type Output = Borrowed<'a, 'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self) } } impl<'a, 'py, T> IntoPyObject<'py> for &Borrowed<'a, 'py, T> { type Target = T; type Output = Borrowed<'a, 'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(*self) } } impl<'py, T> IntoPyObject<'py> for Py<T> { type Target = T; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.into_bound(py)) } } impl<'a, 'py, T> IntoPyObject<'py> for &'a Py<T> { type Target = T; type Output = Borrowed<'a, 'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.bind_borrowed(py)) } } impl<'a, 'py, T> IntoPyObject<'py> for &&'a T where &'a T: IntoPyObject<'py>, { type Target = <&'a T as IntoPyObject<'py>>::Target; type Output = <&'a T as IntoPyObject<'py>>::Output; type Error = <&'a T as IntoPyObject<'py>>::Error; #[inline] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { (*self).into_pyobject(py) } } /// Extract a type from a Python object. /// /// /// Normal usage is through the `extract` methods on [`Bound`] and [`Py`], which forward to this trait. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyString; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// // Calling `.extract()` on a `Bound` smart pointer /// let obj: Bound<'_, PyString> = PyString::new(py, "blah"); /// let s: String = obj.extract()?; /// # assert_eq!(s, "blah"); /// /// // Calling `.extract(py)` on a `Py` smart pointer /// let obj: Py<PyString> = obj.unbind(); /// let s: String = obj.extract(py)?; /// # assert_eq!(s, "blah"); /// # Ok(()) /// }) /// # } /// ``` /// // /// FIXME: until `FromPyObject` can pick up a second lifetime, the below commentary is no longer // /// true. Update and restore this documentation at that time. // /// // /// Note: depending on the implementation, the lifetime of the extracted result may // /// depend on the lifetime of the `obj` or the `prepared` variable. // /// // /// For example, when extracting `&str` from a Python byte string, the resulting string slice will // /// point to the existing string data (lifetime: `'py`). // /// On the other hand, when extracting `&str` from a Python Unicode string, the preparation step // /// will convert the string to UTF-8, and the resulting string slice will have lifetime `'prepared`. // /// Since which case applies depends on the runtime type of the Python object, // /// both the `obj` and `prepared` variables must outlive the resulting string slice. /// /// During the migration of PyO3 from the "GIL Refs" API to the `Bound<T>` smart pointer, this trait /// has two methods `extract` and `extract_bound` which are defaulted to call each other. To avoid /// infinite recursion, implementors must implement at least one of these methods. The recommendation /// is to implement `extract_bound` and leave `extract` as the default implementation. pub trait FromPyObject<'py>: Sized { /// Extracts `Self` from the bound smart pointer `obj`. /// /// Implementors are encouraged to implement this method and leave `extract` defaulted, as /// this will be most compatible with PyO3's future API. fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self>; /// Extracts the type hint information for this type when it appears as an argument. /// /// For example, `Vec<u32>` would return `Sequence[int]`. /// The default implementation returns `Any`, which is correct for any type. /// /// For most types, the return value for this method will be identical to that of /// [`IntoPyObject::type_output`]. It may be different for some types, such as `Dict`, /// to allow duck-typing: functions return `Dict` but take `Mapping` as argument. #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { TypeInfo::Any } } mod from_py_object_bound_sealed { /// Private seal for the `FromPyObjectBound` trait. /// /// This prevents downstream types from implementing the trait before /// PyO3 is ready to declare the trait as public API. pub trait Sealed {} // This generic implementation is why the seal is separate from // `crate::sealed::Sealed`. impl<'py, T> Sealed for T where T: super::FromPyObject<'py> {} impl Sealed for &'_ str {} impl Sealed for std::borrow::Cow<'_, str> {} impl Sealed for &'_ [u8] {} impl Sealed for std::borrow::Cow<'_, [u8]> {} } /// Expected form of [`FromPyObject`] to be used in a future PyO3 release. /// /// The difference between this and `FromPyObject` is that this trait takes an /// additional lifetime `'a`, which is the lifetime of the input `Bound`. /// /// This allows implementations for `&'a str` and `&'a [u8]`, which could not /// be expressed by the existing `FromPyObject` trait once the GIL Refs API was /// removed. /// /// # Usage /// /// Users are prevented from implementing this trait, instead they should implement /// the normal `FromPyObject` trait. This trait has a blanket implementation /// for `T: FromPyObject`. /// /// The only case where this trait may have a use case to be implemented is when the /// lifetime of the extracted value is tied to the lifetime `'a` of the input `Bound` /// instead of the GIL lifetime `py`, as is the case for the `&'a str` implementation. /// /// Please contact the PyO3 maintainers if you believe you have a use case for implementing /// this trait before PyO3 is ready to change the main `FromPyObject` trait to take an /// additional lifetime. /// /// Similarly, users should typically not call these trait methods and should instead /// use this via the `extract` method on `Bound` and `Py`. pub trait FromPyObjectBound<'a, 'py>: Sized + from_py_object_bound_sealed::Sealed { /// Extracts `Self` from the bound smart pointer `obj`. /// /// Users are advised against calling this method directly: instead, use this via /// [`Bound<'_, PyAny>::extract`] or [`Py::extract`]. fn from_py_object_bound(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self>; /// Extracts the type hint information for this type when it appears as an argument. /// /// For example, `Vec<u32>` would return `Sequence[int]`. /// The default implementation returns `Any`, which is correct for any type. /// /// For most types, the return value for this method will be identical to that of /// [`IntoPyObject::type_output`]. It may be different for some types, such as `Dict`, /// to allow duck-typing: functions return `Dict` but take `Mapping` as argument. #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { TypeInfo::Any } } impl<'py, T> FromPyObjectBound<'_, 'py> for T where T: FromPyObject<'py>, { fn from_py_object_bound(ob: Borrowed<'_, 'py, PyAny>) -> PyResult<Self> { Self::extract_bound(&ob) } #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { <T as FromPyObject>::type_input() } } /// Identity conversion: allows using existing `PyObject` instances where /// `T: ToPyObject` is expected. #[allow(deprecated)] impl<T: ?Sized + ToPyObject> ToPyObject for &'_ T { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { <T as ToPyObject>::to_object(*self, py) } } impl<T> FromPyObject<'_> for T where T: PyClass + Clone, { fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> { let bound = obj.downcast::<Self>()?; Ok(bound.try_borrow()?.clone()) } } impl<'py, T> FromPyObject<'py> for PyRef<'py, T> where T: PyClass, { fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> { obj.downcast::<T>()?.try_borrow().map_err(Into::into) } } impl<'py, T> FromPyObject<'py> for PyRefMut<'py, T> where T: PyClass<Frozen = False>, { fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> { obj.downcast::<T>()?.try_borrow_mut().map_err(Into::into) } } /// Converts `()` to an empty Python tuple. #[allow(deprecated)] impl IntoPy<Py<PyTuple>> for () { fn into_py(self, py: Python<'_>) -> Py<PyTuple> { PyTuple::empty(py).unbind() } } impl<'py> IntoPyObject<'py> for () { type Target = PyTuple; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PyTuple::empty(py)) } } /// ```rust,compile_fail /// use pyo3::prelude::*; /// /// #[pyclass] /// struct TestClass { /// num: u32, /// } /// /// let t = TestClass { num: 10 }; /// /// Python::with_gil(|py| { /// let pyvalue = Py::new(py, t).unwrap().to_object(py); /// let t: TestClass = pyvalue.extract(py).unwrap(); /// }) /// ``` mod test_no_clone {}
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/panic.rs
//! Helper to convert Rust panics to Python exceptions. use crate::exceptions::PyBaseException; use crate::PyErr; use std::any::Any; pyo3_exception!( " The exception raised when Rust code called from Python panics. Like SystemExit, this exception is derived from BaseException so that it will typically propagate all the way through the stack and cause the Python interpreter to exit. ", PanicException, PyBaseException ); impl PanicException { /// Creates a new PanicException from a panic payload. /// /// Attempts to format the error in the same way panic does. #[cold] pub(crate) fn from_panic_payload(payload: Box<dyn Any + Send + 'static>) -> PyErr { if let Some(string) = payload.downcast_ref::<String>() { Self::new_err((string.clone(),)) } else if let Some(s) = payload.downcast_ref::<&str>() { Self::new_err((s.to_string(),)) } else { Self::new_err(("panic from Rust code",)) } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pybacked.rs
//! Contains types for working with Python objects that own the underlying data. use std::{convert::Infallible, ops::Deref, ptr::NonNull, sync::Arc}; use crate::{ types::{ any::PyAnyMethods, bytearray::PyByteArrayMethods, bytes::PyBytesMethods, string::PyStringMethods, PyByteArray, PyBytes, PyString, }, Bound, DowncastError, FromPyObject, IntoPyObject, Py, PyAny, PyErr, PyResult, Python, }; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; /// A wrapper around `str` where the storage is owned by a Python `bytes` or `str` object. /// /// This type gives access to the underlying data via a `Deref` implementation. #[cfg_attr(feature = "py-clone", derive(Clone))] pub struct PyBackedStr { #[allow(dead_code)] // only held so that the storage is not dropped storage: Py<PyAny>, data: NonNull<str>, } impl Deref for PyBackedStr { type Target = str; fn deref(&self) -> &str { // Safety: `data` is known to be immutable and owned by self unsafe { self.data.as_ref() } } } impl AsRef<str> for PyBackedStr { fn as_ref(&self) -> &str { self } } impl AsRef<[u8]> for PyBackedStr { fn as_ref(&self) -> &[u8] { self.as_bytes() } } // Safety: the underlying Python str (or bytes) is immutable and // safe to share between threads unsafe impl Send for PyBackedStr {} unsafe impl Sync for PyBackedStr {} impl std::fmt::Display for PyBackedStr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.deref().fmt(f) } } impl_traits!(PyBackedStr, str); impl TryFrom<Bound<'_, PyString>> for PyBackedStr { type Error = PyErr; fn try_from(py_string: Bound<'_, PyString>) -> Result<Self, Self::Error> { #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] { let s = py_string.to_str()?; let data = NonNull::from(s); Ok(Self { storage: py_string.into_any().unbind(), data, }) } #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] { let bytes = py_string.encode_utf8()?; let s = unsafe { std::str::from_utf8_unchecked(bytes.as_bytes()) }; let data = NonNull::from(s); Ok(Self { storage: bytes.into_any().unbind(), data, }) } } } impl FromPyObject<'_> for PyBackedStr { fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> { let py_string = obj.downcast::<PyString>()?.to_owned(); Self::try_from(py_string) } } #[allow(deprecated)] impl ToPyObject for PyBackedStr { #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn to_object(&self, py: Python<'_>) -> Py<PyAny> { self.storage.as_any().clone_ref(py) } #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] fn to_object(&self, py: Python<'_>) -> Py<PyAny> { PyString::new(py, self).into_any().unbind() } } #[allow(deprecated)] impl IntoPy<Py<PyAny>> for PyBackedStr { #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn into_py(self, _py: Python<'_>) -> Py<PyAny> { self.storage.into_any() } #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] fn into_py(self, py: Python<'_>) -> Py<PyAny> { PyString::new(py, &self).into_any().unbind() } } impl<'py> IntoPyObject<'py> for PyBackedStr { type Target = PyAny; type Output = Bound<'py, Self::Target>; type Error = Infallible; #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.storage.into_bound(py)) } #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PyString::new(py, &self).into_any()) } } impl<'py> IntoPyObject<'py> for &PyBackedStr { type Target = PyAny; type Output = Bound<'py, Self::Target>; type Error = Infallible; #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.storage.bind(py).to_owned()) } #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PyString::new(py, self).into_any()) } } /// A wrapper around `[u8]` where the storage is either owned by a Python `bytes` object, or a Rust `Box<[u8]>`. /// /// This type gives access to the underlying data via a `Deref` implementation. #[cfg_attr(feature = "py-clone", derive(Clone))] pub struct PyBackedBytes { #[allow(dead_code)] // only held so that the storage is not dropped storage: PyBackedBytesStorage, data: NonNull<[u8]>, } #[allow(dead_code)] #[cfg_attr(feature = "py-clone", derive(Clone))] enum PyBackedBytesStorage { Python(Py<PyBytes>), Rust(Arc<[u8]>), } impl Deref for PyBackedBytes { type Target = [u8]; fn deref(&self) -> &[u8] { // Safety: `data` is known to be immutable and owned by self unsafe { self.data.as_ref() } } } impl AsRef<[u8]> for PyBackedBytes { fn as_ref(&self) -> &[u8] { self } } // Safety: the underlying Python bytes or Rust bytes is immutable and // safe to share between threads unsafe impl Send for PyBackedBytes {} unsafe impl Sync for PyBackedBytes {} impl<const N: usize> PartialEq<[u8; N]> for PyBackedBytes { fn eq(&self, other: &[u8; N]) -> bool { self.deref() == other } } impl<const N: usize> PartialEq<PyBackedBytes> for [u8; N] { fn eq(&self, other: &PyBackedBytes) -> bool { self == other.deref() } } impl<const N: usize> PartialEq<&[u8; N]> for PyBackedBytes { fn eq(&self, other: &&[u8; N]) -> bool { self.deref() == *other } } impl<const N: usize> PartialEq<PyBackedBytes> for &[u8; N] { fn eq(&self, other: &PyBackedBytes) -> bool { self == &other.deref() } } impl_traits!(PyBackedBytes, [u8]); impl From<Bound<'_, PyBytes>> for PyBackedBytes { fn from(py_bytes: Bound<'_, PyBytes>) -> Self { let b = py_bytes.as_bytes(); let data = NonNull::from(b); Self { storage: PyBackedBytesStorage::Python(py_bytes.to_owned().unbind()), data, } } } impl From<Bound<'_, PyByteArray>> for PyBackedBytes { fn from(py_bytearray: Bound<'_, PyByteArray>) -> Self { let s = Arc::<[u8]>::from(py_bytearray.to_vec()); let data = NonNull::from(s.as_ref()); Self { storage: PyBackedBytesStorage::Rust(s), data, } } } impl FromPyObject<'_> for PyBackedBytes { fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> { if let Ok(bytes) = obj.downcast::<PyBytes>() { Ok(Self::from(bytes.to_owned())) } else if let Ok(bytearray) = obj.downcast::<PyByteArray>() { Ok(Self::from(bytearray.to_owned())) } else { Err(DowncastError::new(obj, "`bytes` or `bytearray`").into()) } } } #[allow(deprecated)] impl ToPyObject for PyBackedBytes { fn to_object(&self, py: Python<'_>) -> Py<PyAny> { match &self.storage { PyBackedBytesStorage::Python(bytes) => bytes.to_object(py), PyBackedBytesStorage::Rust(bytes) => PyBytes::new(py, bytes).into_any().unbind(), } } } #[allow(deprecated)] impl IntoPy<Py<PyAny>> for PyBackedBytes { fn into_py(self, py: Python<'_>) -> Py<PyAny> { match self.storage { PyBackedBytesStorage::Python(bytes) => bytes.into_any(), PyBackedBytesStorage::Rust(bytes) => PyBytes::new(py, &bytes).into_any().unbind(), } } } impl<'py> IntoPyObject<'py> for PyBackedBytes { type Target = PyBytes; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { match self.storage { PyBackedBytesStorage::Python(bytes) => Ok(bytes.into_bound(py)), PyBackedBytesStorage::Rust(bytes) => Ok(PyBytes::new(py, &bytes)), } } } impl<'py> IntoPyObject<'py> for &PyBackedBytes { type Target = PyBytes; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { match &self.storage { PyBackedBytesStorage::Python(bytes) => Ok(bytes.bind(py).clone()), PyBackedBytesStorage::Rust(bytes) => Ok(PyBytes::new(py, bytes)), } } } macro_rules! impl_traits { ($slf:ty, $equiv:ty) => { impl std::fmt::Debug for $slf { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.deref().fmt(f) } } impl PartialEq for $slf { fn eq(&self, other: &Self) -> bool { self.deref() == other.deref() } } impl PartialEq<$equiv> for $slf { fn eq(&self, other: &$equiv) -> bool { self.deref() == other } } impl PartialEq<&$equiv> for $slf { fn eq(&self, other: &&$equiv) -> bool { self.deref() == *other } } impl PartialEq<$slf> for $equiv { fn eq(&self, other: &$slf) -> bool { self == other.deref() } } impl PartialEq<$slf> for &$equiv { fn eq(&self, other: &$slf) -> bool { self == &other.deref() } } impl Eq for $slf {} impl PartialOrd for $slf { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl PartialOrd<$equiv> for $slf { fn partial_cmp(&self, other: &$equiv) -> Option<std::cmp::Ordering> { self.deref().partial_cmp(other) } } impl PartialOrd<$slf> for $equiv { fn partial_cmp(&self, other: &$slf) -> Option<std::cmp::Ordering> { self.partial_cmp(other.deref()) } } impl Ord for $slf { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.deref().cmp(other.deref()) } } impl std::hash::Hash for $slf { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.deref().hash(state) } } }; } use impl_traits; #[cfg(test)] mod test { use super::*; use crate::{IntoPyObject, Python}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[test] fn py_backed_str_empty() { Python::with_gil(|py| { let s = PyString::new(py, ""); let py_backed_str = s.extract::<PyBackedStr>().unwrap(); assert_eq!(&*py_backed_str, ""); }); } #[test] fn py_backed_str() { Python::with_gil(|py| { let s = PyString::new(py, "hello"); let py_backed_str = s.extract::<PyBackedStr>().unwrap(); assert_eq!(&*py_backed_str, "hello"); }); } #[test] fn py_backed_str_try_from() { Python::with_gil(|py| { let s = PyString::new(py, "hello"); let py_backed_str = PyBackedStr::try_from(s).unwrap(); assert_eq!(&*py_backed_str, "hello"); }); } #[test] fn py_backed_str_into_pyobject() { Python::with_gil(|py| { let orig_str = PyString::new(py, "hello"); let py_backed_str = orig_str.extract::<PyBackedStr>().unwrap(); let new_str = py_backed_str.into_pyobject(py).unwrap(); assert_eq!(new_str.extract::<PyBackedStr>().unwrap(), "hello"); #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] assert!(new_str.is(&orig_str)); }); } #[test] #[allow(deprecated)] fn py_backed_str_into_py() { Python::with_gil(|py| { let orig_str = PyString::new(py, "hello"); let py_backed_str = orig_str.extract::<PyBackedStr>().unwrap(); let new_str = py_backed_str.into_py(py); assert_eq!(new_str.extract::<PyBackedStr>(py).unwrap(), "hello"); #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] assert!(new_str.is(&orig_str)); }); } #[test] fn py_backed_bytes_empty() { Python::with_gil(|py| { let b = PyBytes::new(py, b""); let py_backed_bytes = b.extract::<PyBackedBytes>().unwrap(); assert_eq!(&*py_backed_bytes, b""); }); } #[test] fn py_backed_bytes() { Python::with_gil(|py| { let b = PyBytes::new(py, b"abcde"); let py_backed_bytes = b.extract::<PyBackedBytes>().unwrap(); assert_eq!(&*py_backed_bytes, b"abcde"); }); } #[test] fn py_backed_bytes_from_bytes() { Python::with_gil(|py| { let b = PyBytes::new(py, b"abcde"); let py_backed_bytes = PyBackedBytes::from(b); assert_eq!(&*py_backed_bytes, b"abcde"); }); } #[test] fn py_backed_bytes_from_bytearray() { Python::with_gil(|py| { let b = PyByteArray::new(py, b"abcde"); let py_backed_bytes = PyBackedBytes::from(b); assert_eq!(&*py_backed_bytes, b"abcde"); }); } #[test] #[allow(deprecated)] fn py_backed_bytes_into_pyobject() { Python::with_gil(|py| { let orig_bytes = PyBytes::new(py, b"abcde"); let py_backed_bytes = PyBackedBytes::from(orig_bytes.clone()); assert!((&py_backed_bytes) .into_pyobject(py) .unwrap() .is(&orig_bytes)); assert!(py_backed_bytes.into_py(py).is(&orig_bytes)); }); } #[test] #[allow(deprecated)] fn rust_backed_bytes_into_pyobject() { Python::with_gil(|py| { let orig_bytes = PyByteArray::new(py, b"abcde"); let rust_backed_bytes = PyBackedBytes::from(orig_bytes); assert!(matches!( rust_backed_bytes.storage, PyBackedBytesStorage::Rust(_) )); let to_object = (&rust_backed_bytes).into_pyobject(py).unwrap(); assert!(&to_object.is_exact_instance_of::<PyBytes>()); assert_eq!(&to_object.extract::<PyBackedBytes>().unwrap(), b"abcde"); let into_py = rust_backed_bytes.into_py(py).into_bound(py); assert!(&into_py.is_exact_instance_of::<PyBytes>()); assert_eq!(&into_py.extract::<PyBackedBytes>().unwrap(), b"abcde"); }); } #[test] fn test_backed_types_send_sync() { fn is_send<T: Send>() {} fn is_sync<T: Sync>() {} is_send::<PyBackedStr>(); is_sync::<PyBackedStr>(); is_send::<PyBackedBytes>(); is_sync::<PyBackedBytes>(); } #[cfg(feature = "py-clone")] #[test] fn test_backed_str_clone() { Python::with_gil(|py| { let s1: PyBackedStr = PyString::new(py, "hello").try_into().unwrap(); let s2 = s1.clone(); assert_eq!(s1, s2); drop(s1); assert_eq!(s2, "hello"); }); } #[test] fn test_backed_str_eq() { Python::with_gil(|py| { let s1: PyBackedStr = PyString::new(py, "hello").try_into().unwrap(); let s2: PyBackedStr = PyString::new(py, "hello").try_into().unwrap(); assert_eq!(s1, "hello"); assert_eq!(s1, s2); let s3: PyBackedStr = PyString::new(py, "abcde").try_into().unwrap(); assert_eq!("abcde", s3); assert_ne!(s1, s3); }); } #[test] fn test_backed_str_hash() { Python::with_gil(|py| { let h = { let mut hasher = DefaultHasher::new(); "abcde".hash(&mut hasher); hasher.finish() }; let s1: PyBackedStr = PyString::new(py, "abcde").try_into().unwrap(); let h1 = { let mut hasher = DefaultHasher::new(); s1.hash(&mut hasher); hasher.finish() }; assert_eq!(h, h1); }); } #[test] fn test_backed_str_ord() { Python::with_gil(|py| { let mut a = vec!["a", "c", "d", "b", "f", "g", "e"]; let mut b = a .iter() .map(|s| PyString::new(py, s).try_into().unwrap()) .collect::<Vec<PyBackedStr>>(); a.sort(); b.sort(); assert_eq!(a, b); }) } #[cfg(feature = "py-clone")] #[test] fn test_backed_bytes_from_bytes_clone() { Python::with_gil(|py| { let b1: PyBackedBytes = PyBytes::new(py, b"abcde").into(); let b2 = b1.clone(); assert_eq!(b1, b2); drop(b1); assert_eq!(b2, b"abcde"); }); } #[cfg(feature = "py-clone")] #[test] fn test_backed_bytes_from_bytearray_clone() { Python::with_gil(|py| { let b1: PyBackedBytes = PyByteArray::new(py, b"abcde").into(); let b2 = b1.clone(); assert_eq!(b1, b2); drop(b1); assert_eq!(b2, b"abcde"); }); } #[test] fn test_backed_bytes_eq() { Python::with_gil(|py| { let b1: PyBackedBytes = PyBytes::new(py, b"abcde").into(); let b2: PyBackedBytes = PyByteArray::new(py, b"abcde").into(); assert_eq!(b1, b"abcde"); assert_eq!(b1, b2); let b3: PyBackedBytes = PyBytes::new(py, b"hello").into(); assert_eq!(b"hello", b3); assert_ne!(b1, b3); }); } #[test] fn test_backed_bytes_hash() { Python::with_gil(|py| { let h = { let mut hasher = DefaultHasher::new(); b"abcde".hash(&mut hasher); hasher.finish() }; let b1: PyBackedBytes = PyBytes::new(py, b"abcde").into(); let h1 = { let mut hasher = DefaultHasher::new(); b1.hash(&mut hasher); hasher.finish() }; let b2: PyBackedBytes = PyByteArray::new(py, b"abcde").into(); let h2 = { let mut hasher = DefaultHasher::new(); b2.hash(&mut hasher); hasher.finish() }; assert_eq!(h, h1); assert_eq!(h, h2); }); } #[test] fn test_backed_bytes_ord() { Python::with_gil(|py| { let mut a = vec![b"a", b"c", b"d", b"b", b"f", b"g", b"e"]; let mut b = a .iter() .map(|&b| PyBytes::new(py, b).into()) .collect::<Vec<PyBackedBytes>>(); a.sort(); b.sort(); assert_eq!(a, b); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pyclass_init.rs
//! Contains initialization utilities for `#[pyclass]`. use crate::ffi_ptr_ext::FfiPtrExt; use crate::impl_::callback::IntoPyCallbackOutput; use crate::impl_::pyclass::{PyClassBaseType, PyClassDict, PyClassThreadChecker, PyClassWeakRef}; use crate::impl_::pyclass_init::{PyNativeTypeInitializer, PyObjectInit}; use crate::types::PyAnyMethods; use crate::{ffi, Bound, Py, PyClass, PyResult, Python}; use crate::{ ffi::PyTypeObject, pycell::impl_::{PyClassBorrowChecker, PyClassMutability, PyClassObjectContents}, }; use std::{ cell::UnsafeCell, marker::PhantomData, mem::{ManuallyDrop, MaybeUninit}, }; /// Initializer for our `#[pyclass]` system. /// /// You can use this type to initialize complicatedly nested `#[pyclass]`. /// /// # Examples /// /// ``` /// # use pyo3::prelude::*; /// # use pyo3::py_run; /// #[pyclass(subclass)] /// struct BaseClass { /// #[pyo3(get)] /// basename: &'static str, /// } /// #[pyclass(extends=BaseClass, subclass)] /// struct SubClass { /// #[pyo3(get)] /// subname: &'static str, /// } /// #[pyclass(extends=SubClass)] /// struct SubSubClass { /// #[pyo3(get)] /// subsubname: &'static str, /// } /// /// #[pymethods] /// impl SubSubClass { /// #[new] /// fn new() -> PyClassInitializer<Self> { /// PyClassInitializer::from(BaseClass { basename: "base" }) /// .add_subclass(SubClass { subname: "sub" }) /// .add_subclass(SubSubClass { /// subsubname: "subsub", /// }) /// } /// } /// Python::with_gil(|py| { /// let typeobj = py.get_type::<SubSubClass>(); /// let sub_sub_class = typeobj.call((), None).unwrap(); /// py_run!( /// py, /// sub_sub_class, /// r#" /// assert sub_sub_class.basename == 'base' /// assert sub_sub_class.subname == 'sub' /// assert sub_sub_class.subsubname == 'subsub'"# /// ); /// }); /// ``` pub struct PyClassInitializer<T: PyClass>(PyClassInitializerImpl<T>); enum PyClassInitializerImpl<T: PyClass> { Existing(Py<T>), New { init: T, super_init: <T::BaseType as PyClassBaseType>::Initializer, }, } impl<T: PyClass> PyClassInitializer<T> { /// Constructs a new initializer from value `T` and base class' initializer. /// /// It is recommended to use `add_subclass` instead of this method for most usage. #[track_caller] #[inline] pub fn new(init: T, super_init: <T::BaseType as PyClassBaseType>::Initializer) -> Self { // This is unsound; see https://github.com/PyO3/pyo3/issues/4452. assert!( super_init.can_be_subclassed(), "you cannot add a subclass to an existing value", ); Self(PyClassInitializerImpl::New { init, super_init }) } /// Constructs a new initializer from an initializer for the base class. /// /// # Examples /// ``` /// use pyo3::prelude::*; /// /// #[pyclass(subclass)] /// struct BaseClass { /// #[pyo3(get)] /// value: i32, /// } /// /// impl BaseClass { /// fn new(value: i32) -> PyResult<Self> { /// Ok(Self { value }) /// } /// } /// /// #[pyclass(extends=BaseClass)] /// struct SubClass {} /// /// #[pymethods] /// impl SubClass { /// #[new] /// fn new(value: i32) -> PyResult<PyClassInitializer<Self>> { /// let base_init = PyClassInitializer::from(BaseClass::new(value)?); /// Ok(base_init.add_subclass(SubClass {})) /// } /// } /// /// fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let m = PyModule::new(py, "example")?; /// m.add_class::<SubClass>()?; /// m.add_class::<BaseClass>()?; /// /// let instance = m.getattr("SubClass")?.call1((92,))?; /// /// // `SubClass` does not have a `value` attribute, but `BaseClass` does. /// let n = instance.getattr("value")?.extract::<i32>()?; /// assert_eq!(n, 92); /// /// Ok(()) /// }) /// } /// ``` #[track_caller] #[inline] pub fn add_subclass<S>(self, subclass_value: S) -> PyClassInitializer<S> where S: PyClass<BaseType = T>, S::BaseType: PyClassBaseType<Initializer = Self>, { PyClassInitializer::new(subclass_value, self) } /// Creates a new PyCell and initializes it. pub(crate) fn create_class_object(self, py: Python<'_>) -> PyResult<Bound<'_, T>> where T: PyClass, { unsafe { self.create_class_object_of_type(py, T::type_object_raw(py)) } } /// Creates a new class object and initializes it given a typeobject `subtype`. /// /// # Safety /// `subtype` must be a valid pointer to the type object of T or a subclass. pub(crate) unsafe fn create_class_object_of_type( self, py: Python<'_>, target_type: *mut crate::ffi::PyTypeObject, ) -> PyResult<Bound<'_, T>> where T: PyClass, { /// Layout of a PyClassObject after base new has been called, but the contents have not yet been /// written. #[repr(C)] struct PartiallyInitializedClassObject<T: PyClass> { _ob_base: <T::BaseType as PyClassBaseType>::LayoutAsBase, contents: MaybeUninit<PyClassObjectContents<T>>, } let (init, super_init) = match self.0 { PyClassInitializerImpl::Existing(value) => return Ok(value.into_bound(py)), PyClassInitializerImpl::New { init, super_init } => (init, super_init), }; let obj = super_init.into_new_object(py, target_type)?; let part_init: *mut PartiallyInitializedClassObject<T> = obj.cast(); std::ptr::write( (*part_init).contents.as_mut_ptr(), PyClassObjectContents { value: ManuallyDrop::new(UnsafeCell::new(init)), borrow_checker: <T::PyClassMutability as PyClassMutability>::Storage::new(), thread_checker: T::ThreadChecker::new(), dict: T::Dict::INIT, weakref: T::WeakRef::INIT, }, ); // Safety: obj is a valid pointer to an object of type `target_type`, which` is a known // subclass of `T` Ok(obj.assume_owned(py).downcast_into_unchecked()) } } impl<T: PyClass> PyObjectInit<T> for PyClassInitializer<T> { unsafe fn into_new_object( self, py: Python<'_>, subtype: *mut PyTypeObject, ) -> PyResult<*mut ffi::PyObject> { self.create_class_object_of_type(py, subtype) .map(Bound::into_ptr) } #[inline] fn can_be_subclassed(&self) -> bool { !matches!(self.0, PyClassInitializerImpl::Existing(..)) } } impl<T> From<T> for PyClassInitializer<T> where T: PyClass, T::BaseType: PyClassBaseType<Initializer = PyNativeTypeInitializer<T::BaseType>>, { #[inline] fn from(value: T) -> PyClassInitializer<T> { Self::new(value, PyNativeTypeInitializer(PhantomData)) } } impl<S, B> From<(S, B)> for PyClassInitializer<S> where S: PyClass<BaseType = B>, B: PyClass + PyClassBaseType<Initializer = PyClassInitializer<B>>, B::BaseType: PyClassBaseType<Initializer = PyNativeTypeInitializer<B::BaseType>>, { #[track_caller] #[inline] fn from(sub_and_base: (S, B)) -> PyClassInitializer<S> { let (sub, base) = sub_and_base; PyClassInitializer::from(base).add_subclass(sub) } } impl<T: PyClass> From<Py<T>> for PyClassInitializer<T> { #[inline] fn from(value: Py<T>) -> PyClassInitializer<T> { PyClassInitializer(PyClassInitializerImpl::Existing(value)) } } impl<'py, T: PyClass> From<Bound<'py, T>> for PyClassInitializer<T> { #[inline] fn from(value: Bound<'py, T>) -> PyClassInitializer<T> { PyClassInitializer::from(value.unbind()) } } // Implementation used by proc macros to allow anything convertible to PyClassInitializer<T> to be // the return value of pyclass #[new] method (optionally wrapped in `Result<U, E>`). impl<T, U> IntoPyCallbackOutput<'_, PyClassInitializer<T>> for U where T: PyClass, U: Into<PyClassInitializer<T>>, { #[inline] fn convert(self, _py: Python<'_>) -> PyResult<PyClassInitializer<T>> { Ok(self.into()) } } #[cfg(all(test, feature = "macros"))] mod tests { //! See https://github.com/PyO3/pyo3/issues/4452. use crate::prelude::*; #[pyclass(crate = "crate", subclass)] struct BaseClass {} #[pyclass(crate = "crate", extends=BaseClass)] struct SubClass { _data: i32, } #[test] #[should_panic] fn add_subclass_to_py_is_unsound() { Python::with_gil(|py| { let base = Py::new(py, BaseClass {}).unwrap(); let _subclass = PyClassInitializer::from(base).add_subclass(SubClass { _data: 42 }); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/macros.rs
/// A convenient macro to execute a Python code snippet, with some local variables set. /// /// # Panics /// /// This macro internally calls [`Python::run_bound`](crate::Python::run_bound) and panics /// if it returns `Err`, after printing the error to stdout. /// /// If you need to handle failures, please use [`Python::run_bound`](crate::marker::Python::run_bound) instead. /// /// # Examples /// ``` /// use pyo3::{prelude::*, py_run, types::PyList}; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let list = PyList::new(py, &[1, 2, 3])?; /// py_run!(py, list, "assert list == [1, 2, 3]"); /// # Ok(()) /// }) /// # } /// ``` /// /// You can use this macro to test pyfunctions or pyclasses quickly. /// /// ``` /// use pyo3::{prelude::*, py_run}; /// /// #[pyclass] /// #[derive(Debug)] /// struct Time { /// hour: u32, /// minute: u32, /// second: u32, /// } /// /// #[pymethods] /// impl Time { /// fn repl_japanese(&self) -> String { /// format!("{}時{}分{}秒", self.hour, self.minute, self.second) /// } /// #[getter] /// fn hour(&self) -> u32 { /// self.hour /// } /// fn as_tuple(&self) -> (u32, u32, u32) { /// (self.hour, self.minute, self.second) /// } /// } /// /// Python::with_gil(|py| { /// let time = Py::new(py, Time {hour: 8, minute: 43, second: 16}).unwrap(); /// let time_as_tuple = (8, 43, 16); /// py_run!(py, time time_as_tuple, r#" /// assert time.hour == 8 /// assert time.repl_japanese() == "8時43分16秒" /// assert time.as_tuple() == time_as_tuple /// "#); /// }); /// ``` /// /// If you need to prepare the `locals` dict by yourself, you can pass it as `*locals`. /// /// ``` /// use pyo3::prelude::*; /// use pyo3::types::IntoPyDict; /// /// #[pyclass] /// struct MyClass; /// /// #[pymethods] /// impl MyClass { /// #[new] /// fn new() -> Self { /// MyClass {} /// } /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let locals = [("C", py.get_type::<MyClass>())].into_py_dict(py)?; /// pyo3::py_run!(py, *locals, "c = C()"); /// # Ok(()) /// }) /// # } /// ``` #[macro_export] macro_rules! py_run { ($py:expr, $($val:ident)+, $code:literal) => {{ $crate::py_run_impl!($py, $($val)+, $crate::indoc::indoc!($code)) }}; ($py:expr, $($val:ident)+, $code:expr) => {{ $crate::py_run_impl!($py, $($val)+, $crate::unindent::unindent($code)) }}; ($py:expr, *$dict:expr, $code:literal) => {{ $crate::py_run_impl!($py, *$dict, $crate::indoc::indoc!($code)) }}; ($py:expr, *$dict:expr, $code:expr) => {{ $crate::py_run_impl!($py, *$dict, $crate::unindent::unindent($code)) }}; } #[macro_export] #[doc(hidden)] macro_rules! py_run_impl { ($py:expr, $($val:ident)+, $code:expr) => {{ use $crate::types::IntoPyDict; use $crate::conversion::IntoPyObject; use $crate::BoundObject; let d = [$((stringify!($val), (&$val).into_pyobject($py).unwrap().into_any().into_bound()),)+].into_py_dict($py).unwrap(); $crate::py_run_impl!($py, *d, $code) }}; ($py:expr, *$dict:expr, $code:expr) => {{ use ::std::option::Option::*; #[allow(unused_imports)] if let ::std::result::Result::Err(e) = $py.run(&::std::ffi::CString::new($code).unwrap(), None, Some(&$dict)) { e.print($py); // So when this c api function the last line called printed the error to stderr, // the output is only written into a buffer which is never flushed because we // panic before flushing. This is where this hack comes into place $py.run($crate::ffi::c_str!("import sys; sys.stderr.flush()"), None, None) .unwrap(); ::std::panic!("{}", $code) } }}; } /// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction). /// /// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to /// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more /// information. #[macro_export] macro_rules! wrap_pyfunction { ($function:path) => { &|py_or_module| { use $function as wrapped_pyfunction; $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction( py_or_module, &wrapped_pyfunction::_PYO3_DEF, ) } }; ($function:path, $py_or_module:expr) => {{ use $function as wrapped_pyfunction; $crate::impl_::pyfunction::WrapPyFunctionArg::wrap_pyfunction( $py_or_module, &wrapped_pyfunction::_PYO3_DEF, ) }}; } /// Wraps a Rust function annotated with [`#[pyfunction]`](macro@crate::pyfunction). /// /// This can be used with [`PyModule::add_function`](crate::types::PyModuleMethods::add_function) to /// add free functions to a [`PyModule`](crate::types::PyModule) - see its documentation for more /// information. #[deprecated(since = "0.23.0", note = "renamed to `wrap_pyfunction!`")] #[macro_export] macro_rules! wrap_pyfunction_bound { ($function:path) => { $crate::wrap_pyfunction!($function) }; ($function:path, $py_or_module:expr) => { $crate::wrap_pyfunction!($function, $py_or_module) }; } /// Returns a function that takes a [`Python`](crate::Python) instance and returns a /// Python module. /// /// Use this together with [`#[pymodule]`](crate::pymodule) and /// [`PyModule::add_wrapped`](crate::types::PyModuleMethods::add_wrapped). #[macro_export] macro_rules! wrap_pymodule { ($module:path) => { &|py| { use $module as wrapped_pymodule; wrapped_pymodule::_PYO3_DEF .make_module(py, wrapped_pymodule::__PYO3_GIL_USED) .expect("failed to wrap pymodule") } }; } /// Add the module to the initialization table in order to make embedded Python code to use it. /// Module name is the argument. /// /// Use it before [`prepare_freethreaded_python`](crate::prepare_freethreaded_python) and /// leave feature `auto-initialize` off #[cfg(not(any(PyPy, GraalPy)))] #[macro_export] macro_rules! append_to_inittab { ($module:ident) => { unsafe { if $crate::ffi::Py_IsInitialized() != 0 { ::std::panic!( "called `append_to_inittab` but a Python interpreter is already running." ); } $crate::ffi::PyImport_AppendInittab( $module::__PYO3_NAME.as_ptr(), ::std::option::Option::Some($module::__pyo3_init), ); } }; }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/lib.rs
#![warn(missing_docs)] #![cfg_attr( feature = "nightly", feature(auto_traits, negative_impls, try_trait_v2) )] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] // Deny some lints in doctests. // Use `#[allow(...)]` locally to override. #![doc(test(attr( deny( rust_2018_idioms, unused_lifetimes, rust_2021_prelude_collisions, warnings ), allow( unused_variables, unused_assignments, unused_extern_crates, // FIXME https://github.com/rust-lang/rust/issues/121621#issuecomment-1965156376 unknown_lints, non_local_definitions, ) )))] //! Rust bindings to the Python interpreter. //! //! PyO3 can be used to write native Python modules or run Python code and modules from Rust. //! //! See [the guide] for a detailed introduction. //! //! # PyO3's object types //! //! PyO3 has several core types that you should familiarize yourself with: //! //! ## The `Python<'py>` object, and the `'py` lifetime //! //! Holding the [global interpreter lock] (GIL) is modeled with the [`Python<'py>`](Python) token. Many //! Python APIs require that the GIL is held, and PyO3 uses this token as proof that these APIs //! can be called safely. It can be explicitly acquired and is also implicitly acquired by PyO3 //! as it wraps Rust functions and structs into Python functions and objects. //! //! The [`Python<'py>`](Python) token's lifetime `'py` is common to many PyO3 APIs: //! - Types that also have the `'py` lifetime, such as the [`Bound<'py, T>`](Bound) smart pointer, are //! bound to the Python GIL and rely on this to offer their functionality. These types often //! have a [`.py()`](Bound::py) method to get the associated [`Python<'py>`](Python) token. //! - Functions which depend on the `'py` lifetime, such as [`PyList::new`](types::PyList::new), //! require a [`Python<'py>`](Python) token as an input. Sometimes the token is passed implicitly by //! taking a [`Bound<'py, T>`](Bound) or other type which is bound to the `'py` lifetime. //! - Traits which depend on the `'py` lifetime, such as [`FromPyObject<'py>`](FromPyObject), usually have //! inputs or outputs which depend on the lifetime. Adding the lifetime to the trait allows //! these inputs and outputs to express their binding to the GIL in the Rust type system. //! //! ## Python object smart pointers //! //! PyO3 has two core smart pointers to refer to Python objects, [`Py<T>`](Py) and its GIL-bound //! form [`Bound<'py, T>`](Bound) which carries the `'py` lifetime. (There is also //! [`Borrowed<'a, 'py, T>`](instance::Borrowed), but it is used much more rarely). //! //! The type parameter `T` in these smart pointers can be filled by: //! - [`PyAny`], e.g. `Py<PyAny>` or `Bound<'py, PyAny>`, where the Python object type is not //! known. `Py<PyAny>` is so common it has a type alias [`PyObject`]. //! - Concrete Python types like [`PyList`](types::PyList) or [`PyTuple`](types::PyTuple). //! - Rust types which are exposed to Python using the [`#[pyclass]`](macro@pyclass) macro. //! //! See the [guide][types] for an explanation of the different Python object types. //! //! ## PyErr //! //! The vast majority of operations in this library will return [`PyResult<...>`](PyResult). //! This is an alias for the type `Result<..., PyErr>`. //! //! A `PyErr` represents a Python exception. A `PyErr` returned to Python code will be raised as a //! Python exception. Errors from `PyO3` itself are also exposed as Python exceptions. //! //! # Feature flags //! //! PyO3 uses [feature flags] to enable you to opt-in to additional functionality. For a detailed //! description, see the [Features chapter of the guide]. //! //! ## Default feature flags //! //! The following features are turned on by default: //! - `macros`: Enables various macros, including all the attribute macros. //! //! ## Optional feature flags //! //! The following features customize PyO3's behavior: //! //! - `abi3`: Restricts PyO3's API to a subset of the full Python API which is guaranteed by //! [PEP 384] to be forward-compatible with future Python versions. //! - `auto-initialize`: Changes [`Python::with_gil`] to automatically initialize the Python //! interpreter if needed. //! - `extension-module`: This will tell the linker to keep the Python symbols unresolved, so that //! your module can also be used with statically linked Python interpreters. Use this feature when //! building an extension module. //! - `multiple-pymethods`: Enables the use of multiple [`#[pymethods]`](macro@crate::pymethods) //! blocks per [`#[pyclass]`](macro@crate::pyclass). This adds a dependency on the [inventory] //! crate, which is not supported on all platforms. //! //! The following features enable interactions with other crates in the Rust ecosystem: //! - [`anyhow`]: Enables a conversion from [anyhow]’s [`Error`][anyhow_error] type to [`PyErr`]. //! - [`chrono`]: Enables a conversion from [chrono]'s structures to the equivalent Python ones. //! - [`chrono-tz`]: Enables a conversion from [chrono-tz]'s `Tz` enum. Requires Python 3.9+. //! - [`either`]: Enables conversions between Python objects and [either]'s [`Either`] type. //! - [`eyre`]: Enables a conversion from [eyre]’s [`Report`] type to [`PyErr`]. //! - [`hashbrown`]: Enables conversions between Python objects and [hashbrown]'s [`HashMap`] and //! [`HashSet`] types. //! - [`indexmap`][indexmap_feature]: Enables conversions between Python dictionary and [indexmap]'s [`IndexMap`]. //! - [`num-bigint`]: Enables conversions between Python objects and [num-bigint]'s [`BigInt`] and //! [`BigUint`] types. //! - [`num-complex`]: Enables conversions between Python objects and [num-complex]'s [`Complex`] //! type. //! - [`num-rational`]: Enables conversions between Python's fractions.Fraction and [num-rational]'s types //! - [`rust_decimal`]: Enables conversions between Python's decimal.Decimal and [rust_decimal]'s //! [`Decimal`] type. //! - [`serde`]: Allows implementing [serde]'s [`Serialize`] and [`Deserialize`] traits for //! [`Py`]`<T>` for all `T` that implement [`Serialize`] and [`Deserialize`]. //! - [`smallvec`][smallvec]: Enables conversions between Python list and [smallvec]'s [`SmallVec`]. //! //! ## Unstable features //! //! - `nightly`: Uses `#![feature(auto_traits, negative_impls)]` to define [`Ungil`] as an auto trait. // //! ## `rustc` environment flags //! - `Py_3_7`, `Py_3_8`, `Py_3_9`, `Py_3_10`, `Py_3_11`, `Py_3_12`, `Py_3_13`: Marks code that is //! only enabled when compiling for a given minimum Python version. //! - `Py_LIMITED_API`: Marks code enabled when the `abi3` feature flag is enabled. //! - `Py_GIL_DISABLED`: Marks code that runs only in the free-threaded build of CPython. //! - `PyPy` - Marks code enabled when compiling for PyPy. //! - `GraalPy` - Marks code enabled when compiling for GraalPy. //! //! Additionally, you can query for the values `Py_DEBUG`, `Py_REF_DEBUG`, //! `Py_TRACE_REFS`, and `COUNT_ALLOCS` from `py_sys_config` to query for the //! corresponding C build-time defines. For example, to conditionally define //! debug code using `Py_DEBUG`, you could do: //! //! ```rust,ignore //! #[cfg(py_sys_config = "Py_DEBUG")] //! println!("only runs if python was compiled with Py_DEBUG") //! ``` //! To use these attributes, add [`pyo3-build-config`] as a build dependency in //! your `Cargo.toml` and call `pyo3_build_config::use_pyo3_cfgs()` in a //! `build.rs` file. //! //! # Minimum supported Rust and Python versions //! //! Requires Rust 1.63 or greater. //! //! PyO3 supports the following Python distributions: //! - CPython 3.7 or greater //! - PyPy 7.3 (Python 3.9+) //! - GraalPy 24.0 or greater (Python 3.10+) //! //! # Example: Building a native Python module //! //! PyO3 can be used to generate a native Python module. The easiest way to try this out for the //! first time is to use [`maturin`]. `maturin` is a tool for building and publishing Rust-based //! Python packages with minimal configuration. The following steps set up some files for an example //! Python module, install `maturin`, and then show how to build and import the Python module. //! //! First, create a new folder (let's call it `string_sum`) containing the following two files: //! //! **`Cargo.toml`** //! //! ```toml //! [package] //! name = "string-sum" //! version = "0.1.0" //! edition = "2021" //! //! [lib] //! name = "string_sum" //! # "cdylib" is necessary to produce a shared library for Python to import from. //! # //! # Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able //! # to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.: //! # crate-type = ["cdylib", "rlib"] //! crate-type = ["cdylib"] //! //! [dependencies.pyo3] #![doc = concat!("version = \"", env!("CARGO_PKG_VERSION"), "\"")] //! features = ["extension-module"] //! ``` //! //! **`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. //! #[pymodule] //! fn string_sum(m: &Bound<'_, PyModule>) -> PyResult<()> { //! m.add_function(wrap_pyfunction!(sum_as_string, m)?)?; //! //! Ok(()) //! } //! ``` //! //! With those two files in place, now `maturin` needs to be installed. This can be done using //! Python's package manager `pip`. First, load up a new Python `virtualenv`, and install `maturin` //! into it: //! ```bash //! $ cd string_sum //! $ python -m venv .env //! $ source .env/bin/activate //! $ pip install maturin //! ``` //! //! Now build and execute the module: //! ```bash //! $ maturin develop //! # lots of progress output as maturin runs the compilation... //! $ python //! >>> import string_sum //! >>> string_sum.sum_as_string(5, 20) //! '25' //! ``` //! //! As well as with `maturin`, it is possible to build using [setuptools-rust] or //! [manually][manual_builds]. Both offer more flexibility than `maturin` but require further //! configuration. //! //! # Example: Using Python from Rust //! //! To embed Python into a Rust binary, you need to ensure that your Python installation contains a //! shared library. The following steps demonstrate how to ensure this (for Ubuntu), and then give //! some example code which runs an embedded Python interpreter. //! //! To install the Python shared library on Ubuntu: //! ```bash //! sudo apt install python3-dev //! ``` //! //! Start a new project with `cargo new` and add `pyo3` to the `Cargo.toml` like this: //! ```toml //! [dependencies.pyo3] #![doc = concat!("version = \"", env!("CARGO_PKG_VERSION"), "\"")] //! # this is necessary to automatically initialize the Python interpreter //! features = ["auto-initialize"] //! ``` //! //! Example program displaying the value of `sys.version` and the current user name: //! ```rust //! use pyo3::prelude::*; //! use pyo3::types::IntoPyDict; //! use pyo3::ffi::c_str; //! //! fn main() -> PyResult<()> { //! Python::with_gil(|py| { //! let sys = py.import("sys")?; //! let version: String = sys.getattr("version")?.extract()?; //! //! let locals = [("os", py.import("os")?)].into_py_dict(py)?; //! let code = c_str!("os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"); //! let user: String = py.eval(code, None, Some(&locals))?.extract()?; //! //! println!("Hello {}, I'm Python {}", user, version); //! Ok(()) //! }) //! } //! ``` //! //! The guide has [a section][calling_rust] with lots of examples about this topic. //! //! # Other Examples //! //! The PyO3 [README](https://github.com/PyO3/pyo3#readme) contains quick-start examples for both //! using [Rust from Python] and [Python from Rust]. //! //! The PyO3 repository's [examples subdirectory] //! contains some basic packages to demonstrate usage of PyO3. //! //! There are many projects using PyO3 - see a list of some at //! <https://github.com/PyO3/pyo3#examples>. //! //! [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" //! [`anyhow`]: ./anyhow/index.html "Documentation about the `anyhow` feature." //! [inventory]: https://docs.rs/inventory //! [`HashMap`]: https://docs.rs/hashbrown/latest/hashbrown/struct.HashMap.html //! [`HashSet`]: https://docs.rs/hashbrown/latest/hashbrown/struct.HashSet.html //! [`SmallVec`]: https://docs.rs/smallvec/latest/smallvec/struct.SmallVec.html //! [`IndexMap`]: https://docs.rs/indexmap/latest/indexmap/map/struct.IndexMap.html //! [`BigInt`]: https://docs.rs/num-bigint/latest/num_bigint/struct.BigInt.html //! [`BigUint`]: https://docs.rs/num-bigint/latest/num_bigint/struct.BigUint.html //! [`Complex`]: https://docs.rs/num-complex/latest/num_complex/struct.Complex.html //! [`Deserialize`]: https://docs.rs/serde/latest/serde/trait.Deserialize.html //! [`Serialize`]: https://docs.rs/serde/latest/serde/trait.Serialize.html //! [chrono]: https://docs.rs/chrono/ "Date and Time for Rust." //! [chrono-tz]: https://docs.rs/chrono-tz/ "TimeZone implementations for chrono from the IANA database." //! [`chrono`]: ./chrono/index.html "Documentation about the `chrono` feature." //! [`chrono-tz`]: ./chrono-tz/index.html "Documentation about the `chrono-tz` feature." //! [either]: https://docs.rs/either/ "A type that represents one of two alternatives." //! [`either`]: ./either/index.html "Documentation about the `either` feature." //! [`Either`]: https://docs.rs/either/latest/either/enum.Either.html //! [eyre]: https://docs.rs/eyre/ "A library for easy idiomatic error handling and reporting in Rust applications." //! [`Report`]: https://docs.rs/eyre/latest/eyre/struct.Report.html //! [`eyre`]: ./eyre/index.html "Documentation about the `eyre` feature." //! [`hashbrown`]: ./hashbrown/index.html "Documentation about the `hashbrown` feature." //! [indexmap_feature]: ./indexmap/index.html "Documentation about the `indexmap` feature." //! [`maturin`]: https://github.com/PyO3/maturin "Build and publish crates with pyo3, rust-cpython and cffi bindings as well as rust binaries as python packages" //! [`num-bigint`]: ./num_bigint/index.html "Documentation about the `num-bigint` feature." //! [`num-complex`]: ./num_complex/index.html "Documentation about the `num-complex` feature." //! [`num-rational`]: ./num_rational/index.html "Documentation about the `num-rational` feature." //! [`pyo3-build-config`]: https://docs.rs/pyo3-build-config //! [rust_decimal]: https://docs.rs/rust_decimal //! [`rust_decimal`]: ./rust_decimal/index.html "Documenation about the `rust_decimal` feature." //! [`Decimal`]: https://docs.rs/rust_decimal/latest/rust_decimal/struct.Decimal.html //! [`serde`]: <./serde/index.html> "Documentation about the `serde` feature." #![doc = concat!("[calling_rust]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/python-from-rust.html \"Calling Python from Rust - PyO3 user guide\"")] //! [examples subdirectory]: https://github.com/PyO3/pyo3/tree/main/examples //! [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html "Features - The Cargo Book" //! [global interpreter lock]: https://docs.python.org/3/glossary.html#term-global-interpreter-lock //! [hashbrown]: https://docs.rs/hashbrown //! [smallvec]: https://docs.rs/smallvec //! [indexmap]: https://docs.rs/indexmap #![doc = concat!("[manual_builds]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/building-and-distribution.html#manual-builds \"Manual builds - Building and Distribution - PyO3 user guide\"")] //! [num-bigint]: https://docs.rs/num-bigint //! [num-complex]: https://docs.rs/num-complex //! [num-rational]: https://docs.rs/num-rational //! [serde]: https://docs.rs/serde //! [setuptools-rust]: https://github.com/PyO3/setuptools-rust "Setuptools plugin for Rust extensions" //! [the guide]: https://pyo3.rs "PyO3 user guide" #![doc = concat!("[types]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html \"GIL lifetimes, mutability and Python object types\"")] //! [PEP 384]: https://www.python.org/dev/peps/pep-0384 "PEP 384 -- Defining a Stable ABI" //! [Python from Rust]: https://github.com/PyO3/pyo3#using-python-from-rust //! [Rust from Python]: https://github.com/PyO3/pyo3#using-rust-from-python #![doc = concat!("[Features chapter of the guide]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/features.html#features-reference \"Features Reference - PyO3 user guide\"")] //! [`Ungil`]: crate::marker::Ungil pub use crate::class::*; pub use crate::conversion::{AsPyPointer, FromPyObject, IntoPyObject}; #[allow(deprecated)] pub use crate::conversion::{IntoPy, ToPyObject}; pub use crate::err::{DowncastError, DowncastIntoError, PyErr, PyErrArguments, PyResult, ToPyErr}; #[cfg(not(any(PyPy, GraalPy)))] pub use crate::gil::{prepare_freethreaded_python, with_embedded_python_interpreter}; pub use crate::instance::{Borrowed, Bound, BoundObject, Py, PyObject}; pub use crate::marker::Python; pub use crate::pycell::{PyRef, PyRefMut}; pub use crate::pyclass::PyClass; pub use crate::pyclass_init::PyClassInitializer; pub use crate::type_object::{PyTypeCheck, PyTypeInfo}; pub use crate::types::PyAny; pub use crate::version::PythonVersionInfo; pub(crate) mod ffi_ptr_ext; pub(crate) mod py_result_ext; pub(crate) mod sealed; /// Old module which contained some implementation details of the `#[pyproto]` module. /// /// Prefer using the same content from `pyo3::pyclass`, e.g. `use pyo3::pyclass::CompareOp` instead /// of `use pyo3::class::basic::CompareOp`. /// /// For compatibility reasons this has not yet been removed, however will be done so /// once <https://github.com/rust-lang/rust/issues/30827> is resolved. pub mod class { pub use self::gc::{PyTraverseError, PyVisit}; pub use self::methods::*; #[doc(hidden)] pub mod methods { #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type IPowModulo = crate::impl_::pymethods::IPowModulo; #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type PyClassAttributeDef = crate::impl_::pymethods::PyClassAttributeDef; #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type PyGetterDef = crate::impl_::pymethods::PyGetterDef; #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type PyMethodDef = crate::impl_::pymethods::PyMethodDef; #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type PyMethodDefType = crate::impl_::pymethods::PyMethodDefType; #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type PyMethodType = crate::impl_::pymethods::PyMethodType; #[deprecated(since = "0.23.0", note = "PyO3 implementation detail")] pub type PySetterDef = crate::impl_::pymethods::PySetterDef; } /// Old module which contained some implementation details of the `#[pyproto]` module. /// /// Prefer using the same content from `pyo3::pyclass`, e.g. `use pyo3::pyclass::CompareOp` instead /// of `use pyo3::class::basic::CompareOp`. /// /// For compatibility reasons this has not yet been removed, however will be done so /// once <https://github.com/rust-lang/rust/issues/30827> is resolved. pub mod basic { pub use crate::pyclass::CompareOp; } /// Old module which contained some implementation details of the `#[pyproto]` module. /// /// Prefer using the same content from `pyo3::pyclass`, e.g. `use pyo3::pyclass::PyTraverseError` instead /// of `use pyo3::class::gc::PyTraverseError`. /// /// For compatibility reasons this has not yet been removed, however will be done so /// once <https://github.com/rust-lang/rust/issues/30827> is resolved. pub mod gc { pub use crate::pyclass::{PyTraverseError, PyVisit}; } } #[cfg(feature = "macros")] #[doc(hidden)] pub use { indoc, // Re-exported for py_run unindent, // Re-exported for py_run }; #[cfg(all(feature = "macros", feature = "multiple-pymethods"))] #[doc(hidden)] pub use inventory; // Re-exported for `#[pyclass]` and `#[pymethods]` with `multiple-pymethods`. /// Tests and helpers which reside inside PyO3's main library. Declared first so that macros /// are available in unit tests. #[cfg(test)] #[macro_use] mod tests; #[macro_use] mod internal_tricks; mod internal; pub mod buffer; pub mod conversion; mod conversions; #[cfg(feature = "experimental-async")] pub mod coroutine; mod err; pub mod exceptions; pub mod ffi; mod gil; #[doc(hidden)] pub mod impl_; mod instance; pub mod marker; pub mod marshal; #[macro_use] pub mod sync; pub mod panic; pub mod pybacked; pub mod pycell; pub mod pyclass; pub mod pyclass_init; pub mod type_object; pub mod types; mod version; #[allow(unused_imports)] // with no features enabled this module has no public exports pub use crate::conversions::*; #[cfg(feature = "macros")] pub use pyo3_macros::{ pyfunction, pymethods, pymodule, FromPyObject, IntoPyObject, IntoPyObjectRef, }; /// A proc macro used to expose Rust structs and fieldless enums as Python objects. /// /// see: `../guide/pyclass-parameters.md` /// /// For more on creating Python classes, /// see the [class section of the guide][1]. /// #[doc = concat!("[1]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/class.html")] #[cfg(feature = "macros")] pub use pyo3_macros::pyclass; #[cfg(feature = "macros")] #[macro_use] mod macros; #[cfg(feature = "experimental-inspect")] pub mod inspect; // Putting the declaration of prelude at the end seems to help encourage rustc and rustdoc to prefer using // other paths to the same items. (e.g. `pyo3::types::PyAnyMethods` instead of `pyo3::prelude::PyAnyMethods`). pub mod prelude; /// Test readme and user guide #[cfg(doctest)] pub mod doc_test { macro_rules! doctests { ($($path:expr => $mod:ident),* $(,)?) => { $( #[doc = include_str!(concat!("../", $path))] mod $mod{} )* }; } doctests! { "README.md" => readme_md, "guide/src/advanced.md" => guide_advanced_md, "guide/src/async-await.md" => guide_async_await_md, "guide/src/building-and-distribution.md" => guide_building_and_distribution_md, "guide/src/building-and-distribution/multiple-python-versions.md" => guide_bnd_multiple_python_versions_md, "guide/src/class.md" => guide_class_md, "guide/src/class/call.md" => guide_class_call, "guide/src/class/object.md" => guide_class_object, "guide/src/class/numeric.md" => guide_class_numeric, "guide/src/class/protocols.md" => guide_class_protocols_md, "guide/src/conversions.md" => guide_conversions_md, "guide/src/conversions/tables.md" => guide_conversions_tables_md, "guide/src/conversions/traits.md" => guide_conversions_traits_md, "guide/src/debugging.md" => guide_debugging_md, // deliberate choice not to test guide/ecosystem because those pages depend on external // crates such as pyo3_asyncio. "guide/src/exception.md" => guide_exception_md, "guide/src/faq.md" => guide_faq_md, "guide/src/features.md" => guide_features_md, "guide/src/free-threading.md" => guide_free_threading_md, "guide/src/function.md" => guide_function_md, "guide/src/function/error-handling.md" => guide_function_error_handling_md, "guide/src/function/signature.md" => guide_function_signature_md, "guide/src/migration.md" => guide_migration_md, "guide/src/module.md" => guide_module_md, "guide/src/parallelism.md" => guide_parallelism_md, "guide/src/performance.md" => guide_performance_md, "guide/src/python-from-rust.md" => guide_python_from_rust_md, "guide/src/python-from-rust/calling-existing-code.md" => guide_pfr_calling_existing_code_md, "guide/src/python-from-rust/function-calls.md" => guide_pfr_function_calls_md, "guide/src/python-typing-hints.md" => guide_python_typing_hints_md, "guide/src/rust-from-python.md" => guide_rust_from_python_md, "guide/src/trait-bounds.md" => guide_trait_bounds_md, "guide/src/types.md" => guide_types_md, } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/marshal.rs
#![cfg(not(Py_LIMITED_API))] //! Support for the Python `marshal` format. use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::types::{PyAny, PyBytes}; use crate::{ffi, Bound}; use crate::{PyResult, Python}; use std::os::raw::c_int; /// The current version of the marshal binary format. pub const VERSION: i32 = 4; /// Serialize an object to bytes using the Python built-in marshal module. /// /// The built-in marshalling only supports a limited range of objects. /// The exact types supported depend on the version argument. /// The [`VERSION`] constant holds the highest version currently supported. /// /// See the [Python documentation](https://docs.python.org/3/library/marshal.html) for more details. /// /// # Examples /// ``` /// # use pyo3::{marshal, types::PyDict, prelude::PyDictMethods}; /// # pyo3::Python::with_gil(|py| { /// let dict = PyDict::new(py); /// dict.set_item("aap", "noot").unwrap(); /// dict.set_item("mies", "wim").unwrap(); /// dict.set_item("zus", "jet").unwrap(); /// /// let bytes = marshal::dumps(&dict, marshal::VERSION); /// # }); /// ``` pub fn dumps<'py>(object: &Bound<'py, PyAny>, version: i32) -> PyResult<Bound<'py, PyBytes>> { unsafe { ffi::PyMarshal_WriteObjectToString(object.as_ptr(), version as c_int) .assume_owned_or_err(object.py()) .downcast_into_unchecked() } } /// Deprecated form of [`dumps`]. #[deprecated(since = "0.23.0", note = "use `dumps` instead")] pub fn dumps_bound<'py>( py: Python<'py>, object: &impl crate::AsPyPointer, version: i32, ) -> PyResult<Bound<'py, PyBytes>> { dumps( unsafe { object.as_ptr().assume_borrowed(py) }.as_any(), version, ) } /// Deserialize an object from bytes using the Python built-in marshal module. pub fn loads<'py, B>(py: Python<'py>, data: &B) -> PyResult<Bound<'py, PyAny>> where B: AsRef<[u8]> + ?Sized, { let data = data.as_ref(); unsafe { ffi::PyMarshal_ReadObjectFromString(data.as_ptr().cast(), data.len() as isize) .assume_owned_or_err(py) } } /// Deprecated form of [`loads`]. #[deprecated(since = "0.23.0", note = "renamed to `loads`")] pub fn loads_bound<'py>(py: Python<'py>, data: &[u8]) -> PyResult<Bound<'py, PyAny>> { loads(py, data) } #[cfg(test)] mod tests { use super::*; use crate::types::{bytes::PyBytesMethods, dict::PyDictMethods, PyAnyMethods, PyDict}; #[test] fn marshal_roundtrip() { Python::with_gil(|py| { let dict = PyDict::new(py); dict.set_item("aap", "noot").unwrap(); dict.set_item("mies", "wim").unwrap(); dict.set_item("zus", "jet").unwrap(); let pybytes = dumps(&dict, VERSION).expect("marshalling failed"); let deserialized = loads(py, pybytes.as_bytes()).expect("unmarshalling failed"); assert!(dict.eq(&deserialized).unwrap()); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/version.rs
/// Represents the major, minor, and patch (if any) versions of this interpreter. /// /// This struct is usually created with [`Python::version`]. /// /// # Examples /// /// ```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`]: crate::marker::Python::version #[derive(Debug)] pub struct PythonVersionInfo<'a> { /// Python major version (e.g. `3`). pub major: u8, /// Python minor version (e.g. `11`). pub minor: u8, /// Python patch version (e.g. `0`). pub patch: u8, /// Python version suffix, if applicable (e.g. `a0`). pub suffix: Option<&'a str>, } impl<'a> PythonVersionInfo<'a> { /// Parses a hard-coded Python interpreter version string (e.g. 3.9.0a4+). pub(crate) fn from_str(version_number_str: &'a str) -> Result<PythonVersionInfo<'a>, &'a str> { fn split_and_parse_number(version_part: &str) -> (u8, Option<&str>) { match version_part.find(|c: char| !c.is_ascii_digit()) { None => (version_part.parse().unwrap(), None), Some(version_part_suffix_start) => { let (version_part, version_part_suffix) = version_part.split_at(version_part_suffix_start); (version_part.parse().unwrap(), Some(version_part_suffix)) } } } let mut parts = version_number_str.split('.'); let major_str = parts.next().ok_or("Python major version missing")?; let minor_str = parts.next().ok_or("Python minor version missing")?; let patch_str = parts.next(); if parts.next().is_some() { return Err("Python version string has too many parts"); }; let major = major_str .parse() .map_err(|_| "Python major version not an integer")?; let (minor, suffix) = split_and_parse_number(minor_str); if suffix.is_some() { assert!(patch_str.is_none()); return Ok(PythonVersionInfo { major, minor, patch: 0, suffix, }); } let (patch, suffix) = patch_str.map(split_and_parse_number).unwrap_or_default(); Ok(PythonVersionInfo { major, minor, patch, suffix, }) } } impl PartialEq<(u8, u8)> for PythonVersionInfo<'_> { fn eq(&self, other: &(u8, u8)) -> bool { self.major == other.0 && self.minor == other.1 } } impl PartialEq<(u8, u8, u8)> for PythonVersionInfo<'_> { fn eq(&self, other: &(u8, u8, u8)) -> bool { self.major == other.0 && self.minor == other.1 && self.patch == other.2 } } impl PartialOrd<(u8, u8)> for PythonVersionInfo<'_> { fn partial_cmp(&self, other: &(u8, u8)) -> Option<std::cmp::Ordering> { (self.major, self.minor).partial_cmp(other) } } impl PartialOrd<(u8, u8, u8)> for PythonVersionInfo<'_> { fn partial_cmp(&self, other: &(u8, u8, u8)) -> Option<std::cmp::Ordering> { (self.major, self.minor, self.patch).partial_cmp(other) } } #[cfg(test)] mod test { use super::*; use crate::Python; #[test] fn test_python_version_info() { Python::with_gil(|py| { let version = py.version_info(); #[cfg(Py_3_7)] assert!(version >= (3, 7)); #[cfg(Py_3_7)] assert!(version >= (3, 7, 0)); #[cfg(Py_3_8)] assert!(version >= (3, 8)); #[cfg(Py_3_8)] assert!(version >= (3, 8, 0)); #[cfg(Py_3_9)] assert!(version >= (3, 9)); #[cfg(Py_3_9)] assert!(version >= (3, 9, 0)); #[cfg(Py_3_10)] assert!(version >= (3, 10)); #[cfg(Py_3_10)] assert!(version >= (3, 10, 0)); #[cfg(Py_3_11)] assert!(version >= (3, 11)); #[cfg(Py_3_11)] assert!(version >= (3, 11, 0)); }); } #[test] fn test_python_version_info_parse() { assert!(PythonVersionInfo::from_str("3.5.0a1").unwrap() >= (3, 5, 0)); assert!(PythonVersionInfo::from_str("3.5+").unwrap() >= (3, 5, 0)); assert!(PythonVersionInfo::from_str("3.5+").unwrap() == (3, 5, 0)); assert!(PythonVersionInfo::from_str("3.5+").unwrap() != (3, 5, 1)); assert!(PythonVersionInfo::from_str("3.5.2a1+").unwrap() < (3, 5, 3)); assert!(PythonVersionInfo::from_str("3.5.2a1+").unwrap() == (3, 5, 2)); assert!(PythonVersionInfo::from_str("3.5.2a1+").unwrap() == (3, 5)); assert!(PythonVersionInfo::from_str("3.5+").unwrap() == (3, 5)); assert!(PythonVersionInfo::from_str("3.5.2a1+").unwrap() < (3, 6)); assert!(PythonVersionInfo::from_str("3.5.2a1+").unwrap() > (3, 4)); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/type_object.rs
//! Python type object information use crate::ffi_ptr_ext::FfiPtrExt; use crate::types::any::PyAnyMethods; use crate::types::{PyAny, PyType}; use crate::{ffi, Bound, Python}; /// `T: PyLayout<U>` represents that `T` is a concrete representation of `U` in the Python heap. /// E.g., `PyClassObject` is a concrete representation of all `pyclass`es, and `ffi::PyObject` /// is of `PyAny`. /// /// This trait is intended to be used internally. /// /// # Safety /// /// This trait must only be implemented for types which represent valid layouts of Python objects. pub unsafe trait PyLayout<T> {} /// `T: PySizedLayout<U>` represents that `T` is not a instance of /// [`PyVarObject`](https://docs.python.org/3/c-api/structures.html#c.PyVarObject). /// /// In addition, that `T` is a concrete representation of `U`. pub trait PySizedLayout<T>: PyLayout<T> + Sized {} /// Python type information. /// All Python native types (e.g., `PyDict`) and `#[pyclass]` structs implement this trait. /// /// This trait is marked unsafe because: /// - specifying the incorrect layout can lead to memory errors /// - the return value of type_object must always point to the same PyTypeObject instance /// /// It is safely implemented by the `pyclass` macro. /// /// # Safety /// /// Implementations must provide an implementation for `type_object_raw` which infallibly produces a /// non-null pointer to the corresponding Python type object. pub unsafe trait PyTypeInfo: Sized { /// Class name. const NAME: &'static str; /// Module name, if any. const MODULE: Option<&'static str>; /// Returns the PyTypeObject instance for this type. fn type_object_raw(py: Python<'_>) -> *mut ffi::PyTypeObject; /// Returns the safe abstraction over the type object. #[inline] fn type_object(py: Python<'_>) -> Bound<'_, PyType> { // Making the borrowed object `Bound` is necessary for soundness reasons. It's an extreme // edge case, but arbitrary Python code _could_ change the __class__ of an object and cause // the type object to be freed. // // By making `Bound` we assume ownership which is then safe against races. unsafe { Self::type_object_raw(py) .cast::<ffi::PyObject>() .assume_borrowed_unchecked(py) .to_owned() .downcast_into_unchecked() } } /// Deprecated name for [`PyTypeInfo::type_object`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTypeInfo::type_object`")] #[inline] fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType> { Self::type_object(py) } /// Checks if `object` is an instance of this type or a subclass of this type. #[inline] fn is_type_of(object: &Bound<'_, PyAny>) -> bool { unsafe { ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object_raw(object.py())) != 0 } } /// Deprecated name for [`PyTypeInfo::is_type_of`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTypeInfo::is_type_of`")] #[inline] fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool { Self::is_type_of(object) } /// Checks if `object` is an instance of this type. #[inline] fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool { unsafe { ffi::Py_TYPE(object.as_ptr()) == Self::type_object_raw(object.py()) } } /// Deprecated name for [`PyTypeInfo::is_exact_type_of`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTypeInfo::is_exact_type_of`")] #[inline] fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool { Self::is_exact_type_of(object) } } /// Implemented by types which can be used as a concrete Python type inside `Py<T>` smart pointers. pub trait PyTypeCheck { /// Name of self. This is used in error messages, for example. const NAME: &'static str; /// Checks if `object` is an instance of `Self`, which may include a subtype. /// /// This should be equivalent to the Python expression `isinstance(object, Self)`. fn type_check(object: &Bound<'_, PyAny>) -> bool; } impl<T> PyTypeCheck for T where T: PyTypeInfo, { const NAME: &'static str = <T as PyTypeInfo>::NAME; #[inline] fn type_check(object: &Bound<'_, PyAny>) -> bool { T::is_type_of(object) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/internal_tricks.rs
use crate::ffi::{Py_ssize_t, PY_SSIZE_T_MAX}; pub struct PrivateMarker; macro_rules! private_decl { () => { /// This trait is private to implement; this method exists to make it /// impossible to implement outside the crate. fn __private__(&self) -> crate::internal_tricks::PrivateMarker; }; } macro_rules! private_impl { () => { fn __private__(&self) -> crate::internal_tricks::PrivateMarker { crate::internal_tricks::PrivateMarker } }; } macro_rules! pyo3_exception { ($doc: expr, $name: ident, $base: ty) => { #[doc = $doc] #[repr(transparent)] #[allow(non_camel_case_types)] pub struct $name($crate::PyAny); $crate::impl_exception_boilerplate!($name); $crate::create_exception_type_object!(pyo3_runtime, $name, $base, Some($doc)); }; } /// Convert an usize index into a Py_ssize_t index, clamping overflow to /// PY_SSIZE_T_MAX. pub(crate) fn get_ssize_index(index: usize) -> Py_ssize_t { index.min(PY_SSIZE_T_MAX as usize) as Py_ssize_t } // TODO: use ptr::from_ref on MSRV 1.76 #[inline] pub(crate) const fn ptr_from_ref<T>(t: &T) -> *const T { t as *const T } // TODO: use ptr::from_mut on MSRV 1.76 #[inline] pub(crate) fn ptr_from_mut<T>(t: &mut T) -> *mut T { t as *mut T }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/sync.rs
//! Synchronization mechanisms based on the Python GIL. //! //! With the acceptance of [PEP 703] (aka a "freethreaded Python") for Python 3.13, these //! are likely to undergo significant developments in the future. //! //! [PEP 703]: https://peps.python.org/pep-703/ use crate::{ ffi, sealed::Sealed, types::{any::PyAnyMethods, PyAny, PyString}, Bound, Py, PyResult, PyTypeCheck, Python, }; use std::{ cell::UnsafeCell, marker::PhantomData, mem::MaybeUninit, sync::{Once, OnceState}, }; #[cfg(not(Py_GIL_DISABLED))] use crate::PyVisit; /// Value with concurrent access protected by the GIL. /// /// This is a synchronization primitive based on Python's global interpreter lock (GIL). /// It ensures that only one thread at a time can access the inner value via shared references. /// It can be combined with interior mutability to obtain mutable references. /// /// This type is not defined for extensions built against the free-threaded CPython ABI. /// /// # Example /// /// Combining `GILProtected` with `RefCell` enables mutable access to static data: /// /// ``` /// # use pyo3::prelude::*; /// use pyo3::sync::GILProtected; /// use std::cell::RefCell; /// /// static NUMBERS: GILProtected<RefCell<Vec<i32>>> = GILProtected::new(RefCell::new(Vec::new())); /// /// Python::with_gil(|py| { /// NUMBERS.get(py).borrow_mut().push(42); /// }); /// ``` #[cfg(not(Py_GIL_DISABLED))] pub struct GILProtected<T> { value: T, } #[cfg(not(Py_GIL_DISABLED))] impl<T> GILProtected<T> { /// Place the given value under the protection of the GIL. pub const fn new(value: T) -> Self { Self { value } } /// Gain access to the inner value by giving proof of having acquired the GIL. pub fn get<'py>(&'py self, _py: Python<'py>) -> &'py T { &self.value } /// Gain access to the inner value by giving proof that garbage collection is happening. pub fn traverse<'py>(&'py self, _visit: PyVisit<'py>) -> &'py T { &self.value } } #[cfg(not(Py_GIL_DISABLED))] unsafe impl<T> Sync for GILProtected<T> where T: Send {} /// A write-once primitive similar to [`std::sync::OnceLock<T>`]. /// /// Unlike `OnceLock<T>` which blocks threads to achieve thread safety, `GilOnceCell<T>` /// allows calls to [`get_or_init`][GILOnceCell::get_or_init] and /// [`get_or_try_init`][GILOnceCell::get_or_try_init] to race to create an initialized value. /// (It is still guaranteed that only one thread will ever write to the cell.) /// /// On Python versions that run with the Global Interpreter Lock (GIL), this helps to avoid /// deadlocks between initialization and the GIL. For an example of such a deadlock, see #[doc = concat!( "[the FAQ section](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/faq.html#im-experiencing-deadlocks-using-pyo3-with-stdsynconcelock-stdsynclazylock-lazy_static-and-once_cell)" )] /// of the guide. /// /// Note that because the GIL blocks concurrent execution, in practice the means that /// [`get_or_init`][GILOnceCell::get_or_init] and /// [`get_or_try_init`][GILOnceCell::get_or_try_init] may race if the initialization /// function leads to the GIL being released and a thread context switch. This can /// happen when importing or calling any Python code, as long as it releases the /// GIL at some point. On free-threaded Python without any GIL, the race is /// more likely since there is no GIL to prevent races. In the future, PyO3 may change /// the semantics of GILOnceCell to behave more like the GIL build in the future. /// /// # Re-entrant initialization /// /// [`get_or_init`][GILOnceCell::get_or_init] and /// [`get_or_try_init`][GILOnceCell::get_or_try_init] do not protect against infinite recursion /// from reentrant initialization. /// /// # Examples /// /// The following example shows how to use `GILOnceCell` to share a reference to a Python list /// between threads: /// /// ``` /// use pyo3::sync::GILOnceCell; /// use pyo3::prelude::*; /// use pyo3::types::PyList; /// /// static LIST_CELL: GILOnceCell<Py<PyList>> = GILOnceCell::new(); /// /// pub fn get_shared_list(py: Python<'_>) -> &Bound<'_, PyList> { /// LIST_CELL /// .get_or_init(py, || PyList::empty(py).unbind()) /// .bind(py) /// } /// # Python::with_gil(|py| assert_eq!(get_shared_list(py).len(), 0)); /// ``` pub struct GILOnceCell<T> { once: Once, data: UnsafeCell<MaybeUninit<T>>, /// (Copied from std::sync::OnceLock) /// /// `PhantomData` to make sure dropck understands we're dropping T in our Drop impl. /// /// ```compile_error,E0597 /// use pyo3::Python; /// use pyo3::sync::GILOnceCell; /// /// struct A<'a>(#[allow(dead_code)] &'a str); /// /// impl<'a> Drop for A<'a> { /// fn drop(&mut self) {} /// } /// /// let cell = GILOnceCell::new(); /// { /// let s = String::new(); /// let _ = Python::with_gil(|py| cell.set(py,A(&s))); /// } /// ``` _marker: PhantomData<T>, } impl<T> Default for GILOnceCell<T> { fn default() -> Self { Self::new() } } // T: Send is needed for Sync because the thread which drops the GILOnceCell can be different // to the thread which fills it. (e.g. think scoped thread which fills the cell and then exits, // leaving the cell to be dropped by the main thread). unsafe impl<T: Send + Sync> Sync for GILOnceCell<T> {} unsafe impl<T: Send> Send for GILOnceCell<T> {} impl<T> GILOnceCell<T> { /// Create a `GILOnceCell` which does not yet contain a value. pub const fn new() -> Self { Self { once: Once::new(), data: UnsafeCell::new(MaybeUninit::uninit()), _marker: PhantomData, } } /// Get a reference to the contained value, or `None` if the cell has not yet been written. #[inline] pub fn get(&self, _py: Python<'_>) -> Option<&T> { if self.once.is_completed() { // SAFETY: the cell has been written. Some(unsafe { (*self.data.get()).assume_init_ref() }) } else { None } } /// Get a reference to the contained value, initializing it if needed using the provided /// closure. /// /// See the type-level documentation for detail on re-entrancy and concurrent initialization. #[inline] pub fn get_or_init<F>(&self, py: Python<'_>, f: F) -> &T where F: FnOnce() -> T, { if let Some(value) = self.get(py) { return value; } // .unwrap() will never panic because the result is always Ok self.init(py, || Ok::<T, std::convert::Infallible>(f())) .unwrap() } /// Like `get_or_init`, but accepts a fallible initialization function. If it fails, the cell /// is left uninitialized. /// /// See the type-level documentation for detail on re-entrancy and concurrent initialization. #[inline] pub fn get_or_try_init<F, E>(&self, py: Python<'_>, f: F) -> Result<&T, E> where F: FnOnce() -> Result<T, E>, { if let Some(value) = self.get(py) { return Ok(value); } self.init(py, f) } #[cold] fn init<F, E>(&self, py: Python<'_>, f: F) -> Result<&T, E> where F: FnOnce() -> Result<T, E>, { // Note that f() could temporarily release the GIL, so it's possible that another thread // writes to this GILOnceCell before f() finishes. That's fine; we'll just have to discard // the value computed here and accept a bit of wasted computation. // TODO: on the freethreaded build, consider wrapping this pair of operations in a // critical section (requires a critical section API which can use a PyMutex without // an object.) let value = f()?; let _ = self.set(py, value); Ok(self.get(py).unwrap()) } /// Get the contents of the cell mutably. This is only possible if the reference to the cell is /// unique. pub fn get_mut(&mut self) -> Option<&mut T> { if self.once.is_completed() { // SAFETY: the cell has been written. Some(unsafe { (*self.data.get()).assume_init_mut() }) } else { None } } /// Set the value in the cell. /// /// If the cell has already been written, `Err(value)` will be returned containing the new /// value which was not written. pub fn set(&self, _py: Python<'_>, value: T) -> Result<(), T> { let mut value = Some(value); // NB this can block, but since this is only writing a single value and // does not call arbitrary python code, we don't need to worry about // deadlocks with the GIL. self.once.call_once_force(|_| { // SAFETY: no other threads can be writing this value, because we are // inside the `call_once_force` closure. unsafe { // `.take().unwrap()` will never panic (*self.data.get()).write(value.take().unwrap()); } }); match value { // Some other thread wrote to the cell first Some(value) => Err(value), None => Ok(()), } } /// Takes the value out of the cell, moving it back to an uninitialized state. /// /// Has no effect and returns None if the cell has not yet been written. pub fn take(&mut self) -> Option<T> { if self.once.is_completed() { // Reset the cell to its default state so that it won't try to // drop the value again. self.once = Once::new(); // SAFETY: the cell has been written. `self.once` has been reset, // so when `self` is dropped the value won't be read again. Some(unsafe { self.data.get_mut().assume_init_read() }) } else { None } } /// Consumes the cell, returning the wrapped value. /// /// Returns None if the cell has not yet been written. pub fn into_inner(mut self) -> Option<T> { self.take() } } impl<T> GILOnceCell<Py<T>> { /// Creates a new cell that contains a new Python reference to the same contained object. /// /// Returns an uninitialized cell if `self` has not yet been initialized. pub fn clone_ref(&self, py: Python<'_>) -> Self { let cloned = Self { once: Once::new(), data: UnsafeCell::new(MaybeUninit::uninit()), _marker: PhantomData, }; if let Some(value) = self.get(py) { let _ = cloned.set(py, value.clone_ref(py)); } cloned } } impl<T> GILOnceCell<Py<T>> where T: PyTypeCheck, { /// Get a reference to the contained Python type, initializing the cell if needed. /// /// This is a shorthand method for `get_or_init` which imports the type from Python on init. /// /// # Example: Using `GILOnceCell` to store a class in a static variable. /// /// `GILOnceCell` can be used to avoid importing a class multiple times: /// ``` /// # use pyo3::prelude::*; /// # use pyo3::sync::GILOnceCell; /// # use pyo3::types::{PyDict, PyType}; /// # use pyo3::intern; /// # /// #[pyfunction] /// fn create_ordered_dict<'py>(py: Python<'py>, dict: Bound<'py, PyDict>) -> PyResult<Bound<'py, PyAny>> { /// // Even if this function is called multiple times, /// // the `OrderedDict` class will be imported only once. /// static ORDERED_DICT: GILOnceCell<Py<PyType>> = GILOnceCell::new(); /// ORDERED_DICT /// .import(py, "collections", "OrderedDict")? /// .call1((dict,)) /// } /// /// # Python::with_gil(|py| { /// # let dict = PyDict::new(py); /// # dict.set_item(intern!(py, "foo"), 42).unwrap(); /// # let fun = wrap_pyfunction!(create_ordered_dict, py).unwrap(); /// # let ordered_dict = fun.call1((&dict,)).unwrap(); /// # assert!(dict.eq(ordered_dict).unwrap()); /// # }); /// ``` pub fn import<'py>( &self, py: Python<'py>, module_name: &str, attr_name: &str, ) -> PyResult<&Bound<'py, T>> { self.get_or_try_init(py, || { let type_object = py .import(module_name)? .getattr(attr_name)? .downcast_into()?; Ok(type_object.unbind()) }) .map(|ty| ty.bind(py)) } } impl<T> Drop for GILOnceCell<T> { fn drop(&mut self) { if self.once.is_completed() { // SAFETY: the cell has been written. unsafe { MaybeUninit::assume_init_drop(self.data.get_mut()) } } } } /// Interns `text` as a Python string and stores a reference to it in static storage. /// /// A reference to the same Python string is returned on each invocation. /// /// # Example: Using `intern!` to avoid needlessly recreating the same Python string /// /// ``` /// use pyo3::intern; /// # use pyo3::{prelude::*, types::PyDict}; /// /// #[pyfunction] /// fn create_dict(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> { /// let dict = PyDict::new(py); /// // 👇 A new `PyString` is created /// // for every call of this function. /// dict.set_item("foo", 42)?; /// Ok(dict) /// } /// /// #[pyfunction] /// fn create_dict_faster(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> { /// let dict = PyDict::new(py); /// // 👇 A `PyString` is created once and reused /// // for the lifetime of the program. /// dict.set_item(intern!(py, "foo"), 42)?; /// Ok(dict) /// } /// # /// # Python::with_gil(|py| { /// # let fun_slow = wrap_pyfunction!(create_dict, py).unwrap(); /// # let dict = fun_slow.call0().unwrap(); /// # assert!(dict.contains("foo").unwrap()); /// # let fun = wrap_pyfunction!(create_dict_faster, py).unwrap(); /// # let dict = fun.call0().unwrap(); /// # assert!(dict.contains("foo").unwrap()); /// # }); /// ``` #[macro_export] macro_rules! intern { ($py: expr, $text: expr) => {{ static INTERNED: $crate::sync::Interned = $crate::sync::Interned::new($text); INTERNED.get($py) }}; } /// Implementation detail for `intern!` macro. #[doc(hidden)] pub struct Interned(&'static str, GILOnceCell<Py<PyString>>); impl Interned { /// Creates an empty holder for an interned `str`. pub const fn new(value: &'static str) -> Self { Interned(value, GILOnceCell::new()) } /// Gets or creates the interned `str` value. #[inline] pub fn get<'py>(&self, py: Python<'py>) -> &Bound<'py, PyString> { self.1 .get_or_init(py, || PyString::intern(py, self.0).into()) .bind(py) } } /// Executes a closure with a Python critical section held on an object. /// /// Acquires the per-object lock for the object `op` that is held /// until the closure `f` is finished. /// /// This is structurally equivalent to the use of the paired /// Py_BEGIN_CRITICAL_SECTION and Py_END_CRITICAL_SECTION C-API macros. /// /// A no-op on GIL-enabled builds, where the critical section API is exposed as /// a no-op by the Python C API. /// /// Provides weaker locking guarantees than traditional locks, but can in some /// cases be used to provide guarantees similar to the GIL without the risk of /// deadlocks associated with traditional locks. /// /// Many CPython C API functions do not acquire the per-object lock on objects /// passed to Python. You should not expect critical sections applied to /// built-in types to prevent concurrent modification. This API is most useful /// for user-defined types with full control over how the internal state for the /// type is managed. #[cfg_attr(not(Py_GIL_DISABLED), allow(unused_variables))] pub fn with_critical_section<F, R>(object: &Bound<'_, PyAny>, f: F) -> R where F: FnOnce() -> R, { #[cfg(Py_GIL_DISABLED)] { struct Guard(crate::ffi::PyCriticalSection); impl Drop for Guard { fn drop(&mut self) { unsafe { crate::ffi::PyCriticalSection_End(&mut self.0); } } } let mut guard = Guard(unsafe { std::mem::zeroed() }); unsafe { crate::ffi::PyCriticalSection_Begin(&mut guard.0, object.as_ptr()) }; f() } #[cfg(not(Py_GIL_DISABLED))] { f() } } #[cfg(rustc_has_once_lock)] mod once_lock_ext_sealed { pub trait Sealed {} impl<T> Sealed for std::sync::OnceLock<T> {} } /// Helper trait for `Once` to help avoid deadlocking when using a `Once` when attached to a /// Python thread. pub trait OnceExt: Sealed { /// Similar to [`call_once`][Once::call_once], but releases the Python GIL temporarily /// if blocking on another thread currently calling this `Once`. fn call_once_py_attached(&self, py: Python<'_>, f: impl FnOnce()); /// Similar to [`call_once_force`][Once::call_once_force], but releases the Python GIL /// temporarily if blocking on another thread currently calling this `Once`. fn call_once_force_py_attached(&self, py: Python<'_>, f: impl FnOnce(&OnceState)); } // Extension trait for [`std::sync::OnceLock`] which helps avoid deadlocks between the Python /// interpreter and initialization with the `OnceLock`. #[cfg(rustc_has_once_lock)] pub trait OnceLockExt<T>: once_lock_ext_sealed::Sealed { /// Initializes this `OnceLock` with the given closure if it has not been initialized yet. /// /// If this function would block, this function detaches from the Python interpreter and /// reattaches before calling `f`. This avoids deadlocks between the Python interpreter and /// the `OnceLock` in cases where `f` can call arbitrary Python code, as calling arbitrary /// Python code can lead to `f` itself blocking on the Python interpreter. /// /// By detaching from the Python interpreter before blocking, this ensures that if `f` blocks /// then the Python interpreter cannot be blocked by `f` itself. fn get_or_init_py_attached<F>(&self, py: Python<'_>, f: F) -> &T where F: FnOnce() -> T; } struct Guard(*mut crate::ffi::PyThreadState); impl Drop for Guard { fn drop(&mut self) { unsafe { ffi::PyEval_RestoreThread(self.0) }; } } impl OnceExt for Once { fn call_once_py_attached(&self, py: Python<'_>, f: impl FnOnce()) { if self.is_completed() { return; } init_once_py_attached(self, py, f) } fn call_once_force_py_attached(&self, py: Python<'_>, f: impl FnOnce(&OnceState)) { if self.is_completed() { return; } init_once_force_py_attached(self, py, f); } } #[cfg(rustc_has_once_lock)] impl<T> OnceLockExt<T> for std::sync::OnceLock<T> { fn get_or_init_py_attached<F>(&self, py: Python<'_>, f: F) -> &T where F: FnOnce() -> T, { // this trait is guarded by a rustc version config // so clippy's MSRV check is wrong #[allow(clippy::incompatible_msrv)] // Use self.get() first to create a fast path when initialized self.get() .unwrap_or_else(|| init_once_lock_py_attached(self, py, f)) } } #[cold] fn init_once_py_attached<F, T>(once: &Once, _py: Python<'_>, f: F) where F: FnOnce() -> T, { // Safety: we are currently attached to the GIL, and we expect to block. We will save // the current thread state and restore it as soon as we are done blocking. let ts_guard = Guard(unsafe { ffi::PyEval_SaveThread() }); once.call_once(move || { drop(ts_guard); f(); }); } #[cold] fn init_once_force_py_attached<F, T>(once: &Once, _py: Python<'_>, f: F) where F: FnOnce(&OnceState) -> T, { // Safety: we are currently attached to the GIL, and we expect to block. We will save // the current thread state and restore it as soon as we are done blocking. let ts_guard = Guard(unsafe { ffi::PyEval_SaveThread() }); once.call_once_force(move |state| { drop(ts_guard); f(state); }); } #[cfg(rustc_has_once_lock)] #[cold] fn init_once_lock_py_attached<'a, F, T>( lock: &'a std::sync::OnceLock<T>, _py: Python<'_>, f: F, ) -> &'a T where F: FnOnce() -> T, { // SAFETY: we are currently attached to a Python thread let ts_guard = Guard(unsafe { ffi::PyEval_SaveThread() }); // this trait is guarded by a rustc version config // so clippy's MSRV check is wrong #[allow(clippy::incompatible_msrv)] // By having detached here, we guarantee that `.get_or_init` cannot deadlock with // the Python interpreter let value = lock.get_or_init(move || { drop(ts_guard); f() }); value } #[cfg(test)] mod tests { use super::*; use crate::types::{PyDict, PyDictMethods}; #[test] fn test_intern() { Python::with_gil(|py| { let foo1 = "foo"; let foo2 = intern!(py, "foo"); let foo3 = intern!(py, stringify!(foo)); let dict = PyDict::new(py); dict.set_item(foo1, 42_usize).unwrap(); assert!(dict.contains(foo2).unwrap()); assert_eq!( dict.get_item(foo3) .unwrap() .unwrap() .extract::<usize>() .unwrap(), 42 ); }); } #[test] fn test_once_cell() { Python::with_gil(|py| { let mut cell = GILOnceCell::new(); assert!(cell.get(py).is_none()); assert_eq!(cell.get_or_try_init(py, || Err(5)), Err(5)); assert!(cell.get(py).is_none()); assert_eq!(cell.get_or_try_init(py, || Ok::<_, ()>(2)), Ok(&2)); assert_eq!(cell.get(py), Some(&2)); assert_eq!(cell.get_or_try_init(py, || Err(5)), Ok(&2)); assert_eq!(cell.take(), Some(2)); assert_eq!(cell.into_inner(), None); let cell_py = GILOnceCell::new(); assert!(cell_py.clone_ref(py).get(py).is_none()); cell_py.get_or_init(py, || py.None()); assert!(cell_py.clone_ref(py).get(py).unwrap().is_none(py)); }) } #[test] fn test_once_cell_drop() { #[derive(Debug)] struct RecordDrop<'a>(&'a mut bool); impl Drop for RecordDrop<'_> { fn drop(&mut self) { *self.0 = true; } } Python::with_gil(|py| { let mut dropped = false; let cell = GILOnceCell::new(); cell.set(py, RecordDrop(&mut dropped)).unwrap(); let drop_container = cell.get(py).unwrap(); assert!(!*drop_container.0); drop(cell); assert!(dropped); }); } #[cfg(feature = "macros")] #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled #[test] fn test_critical_section() { use std::sync::{ atomic::{AtomicBool, Ordering}, Barrier, }; let barrier = Barrier::new(2); #[crate::pyclass(crate = "crate")] struct BoolWrapper(AtomicBool); let bool_wrapper = Python::with_gil(|py| -> Py<BoolWrapper> { Py::new(py, BoolWrapper(AtomicBool::new(false))).unwrap() }); std::thread::scope(|s| { s.spawn(|| { Python::with_gil(|py| { let b = bool_wrapper.bind(py); with_critical_section(b, || { barrier.wait(); std::thread::sleep(std::time::Duration::from_millis(10)); b.borrow().0.store(true, Ordering::Release); }) }); }); s.spawn(|| { barrier.wait(); Python::with_gil(|py| { let b = bool_wrapper.bind(py); // this blocks until the other thread's critical section finishes with_critical_section(b, || { assert!(b.borrow().0.load(Ordering::Acquire)); }); }); }); }); } #[test] #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled fn test_once_ext() { // adapted from the example in the docs for Once::try_once_force let init = Once::new(); std::thread::scope(|s| { // poison the once let handle = s.spawn(|| { Python::with_gil(|py| { init.call_once_py_attached(py, || panic!()); }) }); assert!(handle.join().is_err()); // poisoning propagates let handle = s.spawn(|| { Python::with_gil(|py| { init.call_once_py_attached(py, || {}); }); }); assert!(handle.join().is_err()); // call_once_force will still run and reset the poisoned state Python::with_gil(|py| { init.call_once_force_py_attached(py, |state| { assert!(state.is_poisoned()); }); // once any success happens, we stop propagating the poison init.call_once_py_attached(py, || {}); }); }); } #[cfg(rustc_has_once_lock)] #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled #[test] fn test_once_lock_ext() { let cell = std::sync::OnceLock::new(); std::thread::scope(|s| { assert!(cell.get().is_none()); s.spawn(|| { Python::with_gil(|py| { assert_eq!(*cell.get_or_init_py_attached(py, || 12345), 12345); }); }); }); assert_eq!(cell.get(), Some(&12345)); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/gil.rs
//! Interaction with Python's global interpreter lock #[cfg(pyo3_disable_reference_pool)] use crate::impl_::panic::PanicTrap; use crate::{ffi, Python}; #[cfg(not(pyo3_disable_reference_pool))] use once_cell::sync::Lazy; use std::cell::Cell; use std::{mem, ptr::NonNull, sync}; static START: sync::Once = sync::Once::new(); std::thread_local! { /// This is an internal counter in pyo3 monitoring whether this thread has the GIL. /// /// It will be incremented whenever a GILGuard or GILPool is created, and decremented whenever /// they are dropped. /// /// As a result, if this thread has the GIL, GIL_COUNT is greater than zero. /// /// Additionally, we sometimes need to prevent safe access to the GIL, /// e.g. when implementing `__traverse__`, which is represented by a negative value. static GIL_COUNT: Cell<isize> = const { Cell::new(0) }; } const GIL_LOCKED_DURING_TRAVERSE: isize = -1; /// Checks whether the GIL is acquired. /// /// Note: This uses pyo3's internal count rather than PyGILState_Check for two reasons: /// 1) for performance /// 2) PyGILState_Check always returns 1 if the sub-interpreter APIs have ever been called, /// which could lead to incorrect conclusions that the GIL is held. #[inline(always)] fn gil_is_acquired() -> bool { GIL_COUNT.try_with(|c| c.get() > 0).unwrap_or(false) } /// Prepares the use of Python in a free-threaded context. /// /// If the Python interpreter is not already initialized, this function will initialize it with /// signal handling disabled (Python will not raise the `KeyboardInterrupt` exception). Python /// signal handling depends on the notion of a 'main thread', which must be the thread that /// initializes the Python interpreter. /// /// If the Python interpreter is already initialized, this function has no effect. /// /// This function is unavailable under PyPy because 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). /// /// # Examples /// ```rust /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// pyo3::prepare_freethreaded_python(); /// Python::with_gil(|py| py.run(pyo3::ffi::c_str!("print('Hello World')"), None, None)) /// # } /// ``` #[cfg(not(any(PyPy, GraalPy)))] pub fn prepare_freethreaded_python() { // Protect against race conditions when Python is not yet initialized and multiple threads // concurrently call 'prepare_freethreaded_python()'. Note that we do not protect against // concurrent initialization of the Python runtime by other users of the Python C API. START.call_once_force(|_| unsafe { // Use call_once_force because if initialization panics, it's okay to try again. if ffi::Py_IsInitialized() == 0 { ffi::Py_InitializeEx(0); // Release the GIL. ffi::PyEval_SaveThread(); } }); } /// Executes the provided closure with an embedded Python interpreter. /// /// This function initializes the Python interpreter, executes the provided closure, and then /// finalizes the Python interpreter. /// /// After execution all Python resources are cleaned up, and no further Python APIs can be called. /// Because many Python modules implemented in C do not support multiple Python interpreters in a /// single process, it is not safe to call this function more than once. (Many such modules will not /// initialize correctly on the second run.) /// /// # Panics /// - If the Python interpreter is already initialized before calling this function. /// /// # Safety /// - This function should only ever be called once per process (usually as part of the `main` /// function). It is also not thread-safe. /// - No Python APIs can be used after this function has finished executing. /// - The return value of the closure must not contain any Python value, _including_ `PyResult`. /// /// # Examples /// /// ```rust /// unsafe { /// pyo3::with_embedded_python_interpreter(|py| { /// if let Err(e) = py.run(pyo3::ffi::c_str!("print('Hello World')"), None, None) { /// // We must make sure to not return a `PyErr`! /// e.print(py); /// } /// }); /// } /// ``` #[cfg(not(any(PyPy, GraalPy)))] pub unsafe fn with_embedded_python_interpreter<F, R>(f: F) -> R where F: for<'p> FnOnce(Python<'p>) -> R, { assert_eq!( ffi::Py_IsInitialized(), 0, "called `with_embedded_python_interpreter` but a Python interpreter is already running." ); ffi::Py_InitializeEx(0); let result = { let guard = GILGuard::assume(); let py = guard.python(); // Import the threading module - this ensures that it will associate this thread as the "main" // thread, which is important to avoid an `AssertionError` at finalization. py.import("threading").unwrap(); // Execute the closure. f(py) }; // Finalize the Python interpreter. ffi::Py_Finalize(); result } /// RAII type that represents the Global Interpreter Lock acquisition. pub(crate) enum GILGuard { /// Indicates the GIL was already held with this GILGuard was acquired. Assumed, /// Indicates that we actually acquired the GIL when this GILGuard was acquired Ensured { gstate: ffi::PyGILState_STATE }, } impl GILGuard { /// PyO3 internal API for acquiring the GIL. The public API is Python::with_gil. /// /// If the GIL was already acquired via PyO3, this returns /// `GILGuard::Assumed`. Otherwise, the GIL will be acquired and /// `GILGuard::Ensured` will be returned. pub(crate) fn acquire() -> Self { if gil_is_acquired() { // SAFETY: We just checked that the GIL is already acquired. return unsafe { Self::assume() }; } // Maybe auto-initialize the GIL: // - If auto-initialize feature set and supported, try to initialize the interpreter. // - If the auto-initialize feature is set but unsupported, emit hard errors only when the // extension-module feature is not activated - extension modules don't care about // auto-initialize so this avoids breaking existing builds. // - Otherwise, just check the GIL is initialized. cfg_if::cfg_if! { if #[cfg(all(feature = "auto-initialize", not(any(PyPy, GraalPy))))] { prepare_freethreaded_python(); } else { // This is a "hack" to make running `cargo test` for PyO3 convenient (i.e. no need // to specify `--features auto-initialize` manually. Tests within the crate itself // all depend on the auto-initialize feature for conciseness but Cargo does not // provide a mechanism to specify required features for tests. #[cfg(not(any(PyPy, GraalPy)))] if option_env!("CARGO_PRIMARY_PACKAGE").is_some() { prepare_freethreaded_python(); } START.call_once_force(|_| unsafe { // Use call_once_force because if there is a panic because the interpreter is // not initialized, it's fine for the user to initialize the interpreter and // retry. assert_ne!( ffi::Py_IsInitialized(), 0, "The Python interpreter is not initialized and the `auto-initialize` \ feature is not enabled.\n\n\ Consider calling `pyo3::prepare_freethreaded_python()` before attempting \ to use Python APIs." ); }); } } // SAFETY: We have ensured the Python interpreter is initialized. unsafe { Self::acquire_unchecked() } } /// Acquires the `GILGuard` without performing any state checking. /// /// This can be called in "unsafe" contexts where the normal interpreter state /// checking performed by `GILGuard::acquire` may fail. This includes calling /// as part of multi-phase interpreter initialization. pub(crate) unsafe fn acquire_unchecked() -> Self { if gil_is_acquired() { return Self::assume(); } let gstate = ffi::PyGILState_Ensure(); // acquire GIL increment_gil_count(); #[cfg(not(pyo3_disable_reference_pool))] if let Some(pool) = Lazy::get(&POOL) { pool.update_counts(Python::assume_gil_acquired()); } GILGuard::Ensured { gstate } } /// Acquires the `GILGuard` while assuming that the GIL is already held. pub(crate) unsafe fn assume() -> Self { increment_gil_count(); let guard = GILGuard::Assumed; #[cfg(not(pyo3_disable_reference_pool))] if let Some(pool) = Lazy::get(&POOL) { pool.update_counts(guard.python()); } guard } /// Gets the Python token associated with this [`GILGuard`]. #[inline] pub fn python(&self) -> Python<'_> { unsafe { Python::assume_gil_acquired() } } } /// The Drop implementation for `GILGuard` will release the GIL. impl Drop for GILGuard { fn drop(&mut self) { match self { GILGuard::Assumed => {} GILGuard::Ensured { gstate } => unsafe { // Drop the objects in the pool before attempting to release the thread state ffi::PyGILState_Release(*gstate); }, } decrement_gil_count(); } } // Vector of PyObject type PyObjVec = Vec<NonNull<ffi::PyObject>>; #[cfg(not(pyo3_disable_reference_pool))] /// Thread-safe storage for objects which were dec_ref while the GIL was not held. struct ReferencePool { pending_decrefs: sync::Mutex<PyObjVec>, } #[cfg(not(pyo3_disable_reference_pool))] impl ReferencePool { const fn new() -> Self { Self { pending_decrefs: sync::Mutex::new(Vec::new()), } } fn register_decref(&self, obj: NonNull<ffi::PyObject>) { self.pending_decrefs.lock().unwrap().push(obj); } fn update_counts(&self, _py: Python<'_>) { let mut pending_decrefs = self.pending_decrefs.lock().unwrap(); if pending_decrefs.is_empty() { return; } let decrefs = mem::take(&mut *pending_decrefs); drop(pending_decrefs); for ptr in decrefs { unsafe { ffi::Py_DECREF(ptr.as_ptr()) }; } } } #[cfg(not(pyo3_disable_reference_pool))] unsafe impl Send for ReferencePool {} #[cfg(not(pyo3_disable_reference_pool))] unsafe impl Sync for ReferencePool {} #[cfg(not(pyo3_disable_reference_pool))] static POOL: Lazy<ReferencePool> = Lazy::new(ReferencePool::new); /// A guard which can be used to temporarily release the GIL and restore on `Drop`. pub(crate) struct SuspendGIL { count: isize, tstate: *mut ffi::PyThreadState, } impl SuspendGIL { pub(crate) unsafe fn new() -> Self { let count = GIL_COUNT.with(|c| c.replace(0)); let tstate = ffi::PyEval_SaveThread(); Self { count, tstate } } } impl Drop for SuspendGIL { fn drop(&mut self) { GIL_COUNT.with(|c| c.set(self.count)); unsafe { ffi::PyEval_RestoreThread(self.tstate); // Update counts of PyObjects / Py that were cloned or dropped while the GIL was released. #[cfg(not(pyo3_disable_reference_pool))] if let Some(pool) = Lazy::get(&POOL) { pool.update_counts(Python::assume_gil_acquired()); } } } } /// Used to lock safe access to the GIL pub(crate) struct LockGIL { count: isize, } impl LockGIL { /// Lock access to the GIL while an implementation of `__traverse__` is running pub fn during_traverse() -> Self { Self::new(GIL_LOCKED_DURING_TRAVERSE) } fn new(reason: isize) -> Self { let count = GIL_COUNT.with(|c| c.replace(reason)); Self { count } } #[cold] fn bail(current: isize) { match current { GIL_LOCKED_DURING_TRAVERSE => panic!( "Access to the GIL is prohibited while a __traverse__ implmentation is running." ), _ => panic!("Access to the GIL is currently prohibited."), } } } impl Drop for LockGIL { fn drop(&mut self) { GIL_COUNT.with(|c| c.set(self.count)); } } /// Increments the reference count of a Python object if the GIL is held. If /// the GIL is not held, this function will panic. /// /// # Safety /// The object must be an owned Python reference. #[cfg(feature = "py-clone")] #[track_caller] pub unsafe fn register_incref(obj: NonNull<ffi::PyObject>) { if gil_is_acquired() { ffi::Py_INCREF(obj.as_ptr()) } else { panic!("Cannot clone pointer into Python heap without the GIL being held."); } } /// Registers a Python object pointer inside the release pool, to have its reference count decreased /// the next time the GIL is acquired in pyo3. /// /// If the GIL is held, the reference count will be decreased immediately instead of being queued /// for later. /// /// # Safety /// The object must be an owned Python reference. #[track_caller] pub unsafe fn register_decref(obj: NonNull<ffi::PyObject>) { if gil_is_acquired() { ffi::Py_DECREF(obj.as_ptr()) } else { #[cfg(not(pyo3_disable_reference_pool))] POOL.register_decref(obj); #[cfg(all( pyo3_disable_reference_pool, not(pyo3_leak_on_drop_without_reference_pool) ))] { let _trap = PanicTrap::new("Aborting the process to avoid panic-from-drop."); panic!("Cannot drop pointer into Python heap without the GIL being held."); } } } /// Increments pyo3's internal GIL count - to be called whenever GILPool or GILGuard is created. #[inline(always)] fn increment_gil_count() { // Ignores the error in case this function called from `atexit`. let _ = GIL_COUNT.try_with(|c| { let current = c.get(); if current < 0 { LockGIL::bail(current); } c.set(current + 1); }); } /// Decrements pyo3's internal GIL count - to be called whenever GILPool or GILGuard is dropped. #[inline(always)] fn decrement_gil_count() { // Ignores the error in case this function called from `atexit`. let _ = GIL_COUNT.try_with(|c| { let current = c.get(); debug_assert!( current > 0, "Negative GIL count detected. Please report this error to the PyO3 repo as a bug." ); c.set(current - 1); }); } #[cfg(test)] mod tests { use super::GIL_COUNT; #[cfg(not(pyo3_disable_reference_pool))] use super::{gil_is_acquired, POOL}; use crate::{ffi, PyObject, Python}; use crate::{gil::GILGuard, types::any::PyAnyMethods}; use std::ptr::NonNull; fn get_object(py: Python<'_>) -> PyObject { py.eval(ffi::c_str!("object()"), None, None) .unwrap() .unbind() } #[cfg(not(pyo3_disable_reference_pool))] fn pool_dec_refs_does_not_contain(obj: &PyObject) -> bool { !POOL .pending_decrefs .lock() .unwrap() .contains(&unsafe { NonNull::new_unchecked(obj.as_ptr()) }) } // with no GIL, threads can empty the POOL at any time, so this // function does not test anything meaningful #[cfg(not(any(pyo3_disable_reference_pool, Py_GIL_DISABLED)))] fn pool_dec_refs_contains(obj: &PyObject) -> bool { POOL.pending_decrefs .lock() .unwrap() .contains(&unsafe { NonNull::new_unchecked(obj.as_ptr()) }) } #[test] fn test_pyobject_drop_with_gil_decreases_refcnt() { Python::with_gil(|py| { let obj = get_object(py); // Create a reference to drop with the GIL. let reference = obj.clone_ref(py); assert_eq!(obj.get_refcnt(py), 2); #[cfg(not(pyo3_disable_reference_pool))] assert!(pool_dec_refs_does_not_contain(&obj)); // With the GIL held, reference count will be decreased immediately. drop(reference); assert_eq!(obj.get_refcnt(py), 1); #[cfg(not(any(pyo3_disable_reference_pool)))] assert!(pool_dec_refs_does_not_contain(&obj)); }); } #[test] #[cfg(all(not(pyo3_disable_reference_pool), not(target_arch = "wasm32")))] // We are building wasm Python with pthreads disabled fn test_pyobject_drop_without_gil_doesnt_decrease_refcnt() { let obj = Python::with_gil(|py| { let obj = get_object(py); // Create a reference to drop without the GIL. let reference = obj.clone_ref(py); assert_eq!(obj.get_refcnt(py), 2); assert!(pool_dec_refs_does_not_contain(&obj)); // Drop reference in a separate thread which doesn't have the GIL. std::thread::spawn(move || drop(reference)).join().unwrap(); // The reference count should not have changed (the GIL has always // been held by this thread), it is remembered to release later. assert_eq!(obj.get_refcnt(py), 2); #[cfg(not(Py_GIL_DISABLED))] assert!(pool_dec_refs_contains(&obj)); obj }); // Next time the GIL is acquired, the reference is released #[allow(unused)] Python::with_gil(|py| { // with no GIL, another thread could still be processing // DECREFs after releasing the lock on the POOL, so the // refcnt could still be 2 when this assert happens #[cfg(not(Py_GIL_DISABLED))] assert_eq!(obj.get_refcnt(py), 1); assert!(pool_dec_refs_does_not_contain(&obj)); }); } #[test] #[allow(deprecated)] fn test_gil_counts() { // Check with_gil and GILGuard both increase counts correctly let get_gil_count = || GIL_COUNT.with(|c| c.get()); assert_eq!(get_gil_count(), 0); Python::with_gil(|_| { assert_eq!(get_gil_count(), 1); let pool = unsafe { GILGuard::assume() }; assert_eq!(get_gil_count(), 2); let pool2 = unsafe { GILGuard::assume() }; assert_eq!(get_gil_count(), 3); drop(pool); assert_eq!(get_gil_count(), 2); Python::with_gil(|_| { // nested with_gil updates gil count assert_eq!(get_gil_count(), 3); }); assert_eq!(get_gil_count(), 2); drop(pool2); assert_eq!(get_gil_count(), 1); }); assert_eq!(get_gil_count(), 0); } #[test] fn test_allow_threads() { assert!(!gil_is_acquired()); Python::with_gil(|py| { assert!(gil_is_acquired()); py.allow_threads(move || { assert!(!gil_is_acquired()); Python::with_gil(|_| assert!(gil_is_acquired())); assert!(!gil_is_acquired()); }); assert!(gil_is_acquired()); }); assert!(!gil_is_acquired()); } #[cfg(feature = "py-clone")] #[test] #[should_panic] fn test_allow_threads_updates_refcounts() { Python::with_gil(|py| { // Make a simple object with 1 reference let obj = get_object(py); assert!(obj.get_refcnt(py) == 1); // Clone the object without the GIL which should panic py.allow_threads(|| obj.clone()); }); } #[test] fn dropping_gil_does_not_invalidate_references() { // Acquiring GIL for the second time should be safe - see #864 Python::with_gil(|py| { let obj = Python::with_gil(|_| py.eval(ffi::c_str!("object()"), None, None).unwrap()); // After gil2 drops, obj should still have a reference count of one assert_eq!(obj.get_refcnt(), 1); }) } #[cfg(feature = "py-clone")] #[test] fn test_clone_with_gil() { Python::with_gil(|py| { let obj = get_object(py); let count = obj.get_refcnt(py); // Cloning with the GIL should increase reference count immediately #[allow(clippy::redundant_clone)] let c = obj.clone(); assert_eq!(count + 1, c.get_refcnt(py)); }) } #[test] #[cfg(not(pyo3_disable_reference_pool))] fn test_update_counts_does_not_deadlock() { // update_counts can run arbitrary Python code during Py_DECREF. // if the locking is implemented incorrectly, it will deadlock. use crate::ffi; use crate::gil::GILGuard; Python::with_gil(|py| { let obj = get_object(py); unsafe extern "C" fn capsule_drop(capsule: *mut ffi::PyObject) { // This line will implicitly call update_counts // -> and so cause deadlock if update_counts is not handling recursion correctly. let pool = GILGuard::assume(); // Rebuild obj so that it can be dropped PyObject::from_owned_ptr( pool.python(), ffi::PyCapsule_GetPointer(capsule, std::ptr::null()) as _, ); } let ptr = obj.into_ptr(); let capsule = unsafe { ffi::PyCapsule_New(ptr as _, std::ptr::null(), Some(capsule_drop)) }; POOL.register_decref(NonNull::new(capsule).unwrap()); // Updating the counts will call decref on the capsule, which calls capsule_drop POOL.update_counts(py); }) } #[test] #[cfg(not(pyo3_disable_reference_pool))] fn test_gil_guard_update_counts() { use crate::gil::GILGuard; Python::with_gil(|py| { let obj = get_object(py); // For GILGuard::acquire POOL.register_decref(NonNull::new(obj.clone_ref(py).into_ptr()).unwrap()); #[cfg(not(Py_GIL_DISABLED))] assert!(pool_dec_refs_contains(&obj)); let _guard = GILGuard::acquire(); assert!(pool_dec_refs_does_not_contain(&obj)); // For GILGuard::assume POOL.register_decref(NonNull::new(obj.clone_ref(py).into_ptr()).unwrap()); #[cfg(not(Py_GIL_DISABLED))] assert!(pool_dec_refs_contains(&obj)); let _guard2 = unsafe { GILGuard::assume() }; assert!(pool_dec_refs_does_not_contain(&obj)); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/instance.rs
use crate::conversion::IntoPyObject; use crate::err::{self, PyErr, PyResult}; use crate::impl_::pycell::PyClassObject; use crate::internal_tricks::ptr_from_ref; use crate::pycell::{PyBorrowError, PyBorrowMutError}; use crate::pyclass::boolean_struct::{False, True}; use crate::types::{any::PyAnyMethods, string::PyStringMethods, typeobject::PyTypeMethods}; use crate::types::{DerefToPyAny, PyDict, PyString, PyTuple}; use crate::{ ffi, AsPyPointer, DowncastError, FromPyObject, PyAny, PyClass, PyClassInitializer, PyRef, PyRefMut, PyTypeInfo, Python, }; use crate::{gil, PyTypeCheck}; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; use std::marker::PhantomData; use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr::NonNull; /// Owned or borrowed gil-bound Python smart pointer /// /// This is implemented for [`Bound`] and [`Borrowed`]. pub trait BoundObject<'py, T>: bound_object_sealed::Sealed { /// Type erased version of `Self` type Any: BoundObject<'py, PyAny>; /// Borrow this smart pointer. fn as_borrowed(&self) -> Borrowed<'_, 'py, T>; /// Turns this smart pointer into an owned [`Bound<'py, T>`] fn into_bound(self) -> Bound<'py, T>; /// Upcast the target type of this smart pointer fn into_any(self) -> Self::Any; /// Turn this smart pointer into a strong reference pointer fn into_ptr(self) -> *mut ffi::PyObject; /// Turn this smart pointer into a borrowed reference pointer fn as_ptr(&self) -> *mut ffi::PyObject; /// Turn this smart pointer into an owned [`Py<T>`] fn unbind(self) -> Py<T>; } mod bound_object_sealed { /// # Safety /// /// Type must be layout-compatible with `*mut ffi::PyObject`. pub unsafe trait Sealed {} // SAFETY: `Bound` is layout-compatible with `*mut ffi::PyObject`. unsafe impl<T> Sealed for super::Bound<'_, T> {} // SAFETY: `Borrowed` is layout-compatible with `*mut ffi::PyObject`. unsafe impl<T> Sealed for super::Borrowed<'_, '_, T> {} } /// A GIL-attached equivalent to [`Py<T>`]. /// /// This type can be thought of as equivalent to the tuple `(Py<T>, Python<'py>)`. By having the `'py` /// lifetime of the [`Python<'py>`] token, this ties the lifetime of the [`Bound<'py, T>`] smart pointer /// to the lifetime of the GIL and allows PyO3 to call Python APIs at maximum efficiency. /// /// To access the object in situations where the GIL is not held, convert it to [`Py<T>`] /// using [`.unbind()`][Bound::unbind]. This includes situations where the GIL is temporarily /// released, such as [`Python::allow_threads`](crate::Python::allow_threads)'s closure. /// /// See #[doc = concat!("[the guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html#boundpy-t)")] /// for more detail. #[repr(transparent)] pub struct Bound<'py, T>(Python<'py>, ManuallyDrop<Py<T>>); impl<'py, T> Bound<'py, T> where T: PyClass, { /// Creates a new instance `Bound<T>` of a `#[pyclass]` on the Python heap. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pyclass] /// struct Foo {/* fields omitted */} /// /// # fn main() -> PyResult<()> { /// let foo: Py<Foo> = Python::with_gil(|py| -> PyResult<_> { /// let foo: Bound<'_, Foo> = Bound::new(py, Foo {})?; /// Ok(foo.into()) /// })?; /// # Python::with_gil(move |_py| drop(foo)); /// # Ok(()) /// # } /// ``` pub fn new( py: Python<'py>, value: impl Into<PyClassInitializer<T>>, ) -> PyResult<Bound<'py, T>> { value.into().create_class_object(py) } } impl<'py> Bound<'py, PyAny> { /// Constructs a new `Bound<'py, PyAny>` from a pointer. Panics if `ptr` is null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object /// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership #[inline] #[track_caller] pub unsafe fn from_owned_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self { Self(py, ManuallyDrop::new(Py::from_owned_ptr(py, ptr))) } /// Constructs a new `Bound<'py, PyAny>` from a pointer. Returns `None` if `ptr` is null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null /// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership #[inline] pub unsafe fn from_owned_ptr_or_opt(py: Python<'py>, ptr: *mut ffi::PyObject) -> Option<Self> { Py::from_owned_ptr_or_opt(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj))) } /// Constructs a new `Bound<'py, PyAny>` from a pointer. Returns an `Err` by calling `PyErr::fetch` /// if `ptr` is null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null /// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership #[inline] pub unsafe fn from_owned_ptr_or_err( py: Python<'py>, ptr: *mut ffi::PyObject, ) -> PyResult<Self> { Py::from_owned_ptr_or_err(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj))) } /// Constructs a new `Bound<'py, PyAny>` from a pointer without checking for null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object /// - `ptr` must be a strong/owned reference pub(crate) unsafe fn from_owned_ptr_unchecked( py: Python<'py>, ptr: *mut ffi::PyObject, ) -> Self { Self(py, ManuallyDrop::new(Py::from_owned_ptr_unchecked(ptr))) } /// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference. /// Panics if `ptr` is null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object #[inline] #[track_caller] pub unsafe fn from_borrowed_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self { Self(py, ManuallyDrop::new(Py::from_borrowed_ptr(py, ptr))) } /// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference. /// Returns `None` if `ptr` is null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null #[inline] pub unsafe fn from_borrowed_ptr_or_opt( py: Python<'py>, ptr: *mut ffi::PyObject, ) -> Option<Self> { Py::from_borrowed_ptr_or_opt(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj))) } /// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference. /// Returns an `Err` by calling `PyErr::fetch` if `ptr` is null. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null #[inline] pub unsafe fn from_borrowed_ptr_or_err( py: Python<'py>, ptr: *mut ffi::PyObject, ) -> PyResult<Self> { Py::from_borrowed_ptr_or_err(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj))) } /// This slightly strange method is used to obtain `&Bound<PyAny>` from a pointer in macro code /// where we need to constrain the lifetime `'a` safely. /// /// Note that `'py` is required to outlive `'a` implicitly by the nature of the fact that /// `&'a Bound<'py>` means that `Bound<'py>` exists for at least the lifetime `'a`. /// /// # Safety /// - `ptr` must be a valid pointer to a Python object for the lifetime `'a`. The `ptr` can /// be either a borrowed reference or an owned reference, it does not matter, as this is /// just `&Bound` there will never be any ownership transfer. #[inline] pub(crate) unsafe fn ref_from_ptr<'a>( _py: Python<'py>, ptr: &'a *mut ffi::PyObject, ) -> &'a Self { &*ptr_from_ref(ptr).cast::<Bound<'py, PyAny>>() } /// Variant of the above which returns `None` for null pointers. /// /// # Safety /// - `ptr` must be a valid pointer to a Python object for the lifetime `'a, or null. #[inline] pub(crate) unsafe fn ref_from_ptr_or_opt<'a>( _py: Python<'py>, ptr: &'a *mut ffi::PyObject, ) -> &'a Option<Self> { &*ptr_from_ref(ptr).cast::<Option<Bound<'py, PyAny>>>() } } impl<'py, T> Bound<'py, T> where T: PyClass, { /// Immutably borrows the value `T`. /// /// This borrow lasts while the returned [`PyRef`] exists. /// Multiple immutable borrows can be taken out at the same time. /// /// For frozen classes, the simpler [`get`][Self::get] is available. /// /// # Examples /// /// ```rust /// # use pyo3::prelude::*; /// # /// #[pyclass] /// struct Foo { /// inner: u8, /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?; /// let inner: &u8 = &foo.borrow().inner; /// /// assert_eq!(*inner, 73); /// Ok(()) /// })?; /// # Ok(()) /// # } /// ``` /// /// # Panics /// /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use /// [`try_borrow`](#method.try_borrow). #[inline] #[track_caller] pub fn borrow(&self) -> PyRef<'py, T> { PyRef::borrow(self) } /// Mutably borrows the value `T`. /// /// This borrow lasts while the returned [`PyRefMut`] exists. /// /// # Examples /// /// ``` /// # use pyo3::prelude::*; /// # /// #[pyclass] /// struct Foo { /// inner: u8, /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?; /// foo.borrow_mut().inner = 35; /// /// assert_eq!(foo.borrow().inner, 35); /// Ok(()) /// })?; /// # Ok(()) /// # } /// ``` /// /// # Panics /// Panics if the value is currently borrowed. For a non-panicking variant, use /// [`try_borrow_mut`](#method.try_borrow_mut). #[inline] #[track_caller] pub fn borrow_mut(&self) -> PyRefMut<'py, T> where T: PyClass<Frozen = False>, { PyRefMut::borrow(self) } /// Attempts to immutably borrow the value `T`, returning an error if the value is currently mutably borrowed. /// /// The borrow lasts while the returned [`PyRef`] exists. /// /// This is the non-panicking variant of [`borrow`](#method.borrow). /// /// For frozen classes, the simpler [`get`][Self::get] is available. #[inline] pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError> { PyRef::try_borrow(self) } /// Attempts to mutably borrow the value `T`, returning an error if the value is currently borrowed. /// /// The borrow lasts while the returned [`PyRefMut`] exists. /// /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). #[inline] pub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError> where T: PyClass<Frozen = False>, { PyRefMut::try_borrow(self) } /// Provide an immutable borrow of the value `T` without acquiring the GIL. /// /// This is available if the class is [`frozen`][macro@crate::pyclass] and [`Sync`]. /// /// # Examples /// /// ``` /// use std::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] /// struct FrozenCounter { /// value: AtomicUsize, /// } /// /// Python::with_gil(|py| { /// let counter = FrozenCounter { value: AtomicUsize::new(0) }; /// /// let py_counter = Bound::new(py, counter).unwrap(); /// /// py_counter.get().value.fetch_add(1, Ordering::Relaxed); /// }); /// ``` #[inline] pub fn get(&self) -> &T where T: PyClass<Frozen = True> + Sync, { self.1.get() } /// Upcast this `Bound<PyClass>` to its base type by reference. /// /// If this type defined an explicit base class in its `pyclass` declaration /// (e.g. `#[pyclass(extends = BaseType)]`), the returned type will be /// `&Bound<BaseType>`. If an explicit base class was _not_ declared, the /// return value will be `&Bound<PyAny>` (making this method equivalent /// to [`as_any`]). /// /// This method is particularly useful for calling methods defined in an /// extension trait that has been implemented for `Bound<BaseType>`. /// /// See also the [`into_super`] method to upcast by value, and the /// [`PyRef::as_super`]/[`PyRefMut::as_super`] methods for upcasting a pyclass /// that has already been [`borrow`]ed. /// /// # Example: Calling a method defined on the `Bound` base type /// /// ```rust /// # fn main() { /// use pyo3::prelude::*; /// /// #[pyclass(subclass)] /// struct BaseClass; /// /// trait MyClassMethods<'py> { /// fn pyrepr(&self) -> PyResult<String>; /// } /// impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> { /// fn pyrepr(&self) -> PyResult<String> { /// self.call_method0("__repr__")?.extract() /// } /// } /// /// #[pyclass(extends = BaseClass)] /// struct SubClass; /// /// Python::with_gil(|py| { /// let obj = Bound::new(py, (SubClass, BaseClass)).unwrap(); /// assert!(obj.as_super().pyrepr().is_ok()); /// }) /// # } /// ``` /// /// [`as_any`]: Bound::as_any /// [`into_super`]: Bound::into_super /// [`borrow`]: Bound::borrow #[inline] pub fn as_super(&self) -> &Bound<'py, T::BaseType> { // a pyclass can always be safely "downcast" to its base type unsafe { self.as_any().downcast_unchecked() } } /// Upcast this `Bound<PyClass>` to its base type by value. /// /// If this type defined an explicit base class in its `pyclass` declaration /// (e.g. `#[pyclass(extends = BaseType)]`), the returned type will be /// `Bound<BaseType>`. If an explicit base class was _not_ declared, the /// return value will be `Bound<PyAny>` (making this method equivalent /// to [`into_any`]). /// /// This method is particularly useful for calling methods defined in an /// extension trait that has been implemented for `Bound<BaseType>`. /// /// See also the [`as_super`] method to upcast by reference, and the /// [`PyRef::into_super`]/[`PyRefMut::into_super`] methods for upcasting a pyclass /// that has already been [`borrow`]ed. /// /// # Example: Calling a method defined on the `Bound` base type /// /// ```rust /// # fn main() { /// use pyo3::prelude::*; /// /// #[pyclass(subclass)] /// struct BaseClass; /// /// trait MyClassMethods<'py> { /// fn pyrepr(self) -> PyResult<String>; /// } /// impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> { /// fn pyrepr(self) -> PyResult<String> { /// self.call_method0("__repr__")?.extract() /// } /// } /// /// #[pyclass(extends = BaseClass)] /// struct SubClass; /// /// Python::with_gil(|py| { /// let obj = Bound::new(py, (SubClass, BaseClass)).unwrap(); /// assert!(obj.into_super().pyrepr().is_ok()); /// }) /// # } /// ``` /// /// [`into_any`]: Bound::into_any /// [`as_super`]: Bound::as_super /// [`borrow`]: Bound::borrow #[inline] pub fn into_super(self) -> Bound<'py, T::BaseType> { // a pyclass can always be safely "downcast" to its base type unsafe { self.into_any().downcast_into_unchecked() } } #[inline] pub(crate) fn get_class_object(&self) -> &PyClassObject<T> { self.1.get_class_object() } } impl<T> std::fmt::Debug for Bound<'_, T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { let any = self.as_any(); python_format(any, any.repr(), f) } } impl<T> std::fmt::Display for Bound<'_, T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { let any = self.as_any(); python_format(any, any.str(), f) } } fn python_format( any: &Bound<'_, PyAny>, format_result: PyResult<Bound<'_, PyString>>, f: &mut std::fmt::Formatter<'_>, ) -> Result<(), std::fmt::Error> { match format_result { Result::Ok(s) => return f.write_str(&s.to_string_lossy()), Result::Err(err) => err.write_unraisable(any.py(), Some(any)), } match any.get_type().name() { Result::Ok(name) => std::write!(f, "<unprintable {} object>", name), Result::Err(_err) => f.write_str("<unprintable object>"), } } // The trait bound is needed to avoid running into the auto-deref recursion // limit (error[E0055]), because `Bound<PyAny>` would deref into itself. See: // https://github.com/rust-lang/rust/issues/19509 impl<'py, T> Deref for Bound<'py, T> where T: DerefToPyAny, { type Target = Bound<'py, PyAny>; #[inline] fn deref(&self) -> &Bound<'py, PyAny> { self.as_any() } } impl<'py, T> AsRef<Bound<'py, PyAny>> for Bound<'py, T> { #[inline] fn as_ref(&self) -> &Bound<'py, PyAny> { self.as_any() } } impl<T> Clone for Bound<'_, T> { #[inline] fn clone(&self) -> Self { Self(self.0, ManuallyDrop::new(self.1.clone_ref(self.0))) } } impl<T> Drop for Bound<'_, T> { #[inline] fn drop(&mut self) { unsafe { ffi::Py_DECREF(self.as_ptr()) } } } impl<'py, T> Bound<'py, T> { /// Returns the GIL token associated with this object. #[inline] pub fn py(&self) -> Python<'py> { self.0 } /// Returns the raw FFI pointer represented by self. /// /// # Safety /// /// Callers are responsible for ensuring that the pointer does not outlive self. /// /// The reference is borrowed; callers should not decrease the reference count /// when they are finished with the pointer. #[inline] pub fn as_ptr(&self) -> *mut ffi::PyObject { self.1.as_ptr() } /// Returns an owned raw FFI pointer represented by self. /// /// # Safety /// /// The reference is owned; when finished the caller should either transfer ownership /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)). #[inline] pub fn into_ptr(self) -> *mut ffi::PyObject { ManuallyDrop::new(self).as_ptr() } /// Helper to cast to `Bound<'py, PyAny>`. #[inline] pub fn as_any(&self) -> &Bound<'py, PyAny> { // Safety: all Bound<T> have the same memory layout, and all Bound<T> are valid // Bound<PyAny>, so pointer casting is valid. unsafe { &*ptr_from_ref(self).cast::<Bound<'py, PyAny>>() } } /// Helper to cast to `Bound<'py, PyAny>`, transferring ownership. #[inline] pub fn into_any(self) -> Bound<'py, PyAny> { // Safety: all Bound<T> are valid Bound<PyAny> Bound(self.0, ManuallyDrop::new(self.unbind().into_any())) } /// Casts this `Bound<T>` to a `Borrowed<T>` smart pointer. #[inline] pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T> { Borrowed( unsafe { NonNull::new_unchecked(self.as_ptr()) }, PhantomData, self.py(), ) } /// Removes the connection for this `Bound<T>` from the GIL, allowing /// it to cross thread boundaries. #[inline] pub fn unbind(self) -> Py<T> { // Safety: the type T is known to be correct and the ownership of the // pointer is transferred to the new Py<T> instance. let non_null = (ManuallyDrop::new(self).1).0; unsafe { Py::from_non_null(non_null) } } /// Removes the connection for this `Bound<T>` from the GIL, allowing /// it to cross thread boundaries, without transferring ownership. #[inline] pub fn as_unbound(&self) -> &Py<T> { &self.1 } } unsafe impl<T> AsPyPointer for Bound<'_, T> { #[inline] fn as_ptr(&self) -> *mut ffi::PyObject { self.1.as_ptr() } } impl<'py, T> BoundObject<'py, T> for Bound<'py, T> { type Any = Bound<'py, PyAny>; fn as_borrowed(&self) -> Borrowed<'_, 'py, T> { Bound::as_borrowed(self) } fn into_bound(self) -> Bound<'py, T> { self } fn into_any(self) -> Self::Any { self.into_any() } fn into_ptr(self) -> *mut ffi::PyObject { self.into_ptr() } fn as_ptr(&self) -> *mut ffi::PyObject { self.as_ptr() } fn unbind(self) -> Py<T> { self.unbind() } } /// A borrowed equivalent to `Bound`. /// /// The advantage of this over `&Bound` is that it avoids the need to have a pointer-to-pointer, as Bound /// is already a pointer to an `ffi::PyObject``. /// /// Similarly, this type is `Copy` and `Clone`, like a shared reference (`&T`). #[repr(transparent)] pub struct Borrowed<'a, 'py, T>(NonNull<ffi::PyObject>, PhantomData<&'a Py<T>>, Python<'py>); impl<'a, 'py, T> Borrowed<'a, 'py, T> { /// Creates a new owned [`Bound<T>`] from this borrowed reference by /// increasing the reference count. /// /// # Example /// ``` /// use pyo3::{prelude::*, types::PyTuple}; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let tuple = PyTuple::new(py, [1, 2, 3])?; /// /// // borrows from `tuple`, so can only be /// // used while `tuple` stays alive /// let borrowed = tuple.get_borrowed_item(0)?; /// /// // creates a new owned reference, which /// // can be used indendently of `tuple` /// let bound = borrowed.to_owned(); /// drop(tuple); /// /// assert_eq!(bound.extract::<i32>().unwrap(), 1); /// Ok(()) /// }) /// # } pub fn to_owned(self) -> Bound<'py, T> { (*self).clone() } /// Returns the raw FFI pointer represented by self. /// /// # Safety /// /// Callers are responsible for ensuring that the pointer does not outlive self. /// /// The reference is borrowed; callers should not decrease the reference count /// when they are finished with the pointer. #[inline] pub fn as_ptr(self) -> *mut ffi::PyObject { self.0.as_ptr() } pub(crate) fn to_any(self) -> Borrowed<'a, 'py, PyAny> { Borrowed(self.0, PhantomData, self.2) } } impl<'a, 'py> Borrowed<'a, 'py, PyAny> { /// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Panics if `ptr` is null. /// /// Prefer to use [`Bound::from_borrowed_ptr`], as that avoids the major safety risk /// of needing to precisely define the lifetime `'a` for which the borrow is valid. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] #[track_caller] pub unsafe fn from_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self { Self( NonNull::new(ptr).unwrap_or_else(|| crate::err::panic_after_error(py)), PhantomData, py, ) } /// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Returns `None` if `ptr` is null. /// /// Prefer to use [`Bound::from_borrowed_ptr_or_opt`], as that avoids the major safety risk /// of needing to precisely define the lifetime `'a` for which the borrow is valid. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] pub unsafe fn from_ptr_or_opt(py: Python<'py>, ptr: *mut ffi::PyObject) -> Option<Self> { NonNull::new(ptr).map(|ptr| Self(ptr, PhantomData, py)) } /// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Returns an `Err` by calling `PyErr::fetch` /// if `ptr` is null. /// /// Prefer to use [`Bound::from_borrowed_ptr_or_err`], as that avoids the major safety risk /// of needing to precisely define the lifetime `'a` for which the borrow is valid. /// /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] pub unsafe fn from_ptr_or_err(py: Python<'py>, ptr: *mut ffi::PyObject) -> PyResult<Self> { NonNull::new(ptr).map_or_else( || Err(PyErr::fetch(py)), |ptr| Ok(Self(ptr, PhantomData, py)), ) } /// # Safety /// This is similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it's the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] pub(crate) unsafe fn from_ptr_unchecked(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self { Self(NonNull::new_unchecked(ptr), PhantomData, py) } #[inline] pub(crate) fn downcast<T>(self) -> Result<Borrowed<'a, 'py, T>, DowncastError<'a, 'py>> where T: PyTypeCheck, { if T::type_check(&self) { // Safety: type_check is responsible for ensuring that the type is correct Ok(unsafe { self.downcast_unchecked() }) } else { Err(DowncastError::new_from_borrowed(self, T::NAME)) } } /// Converts this `PyAny` to a concrete Python type without checking validity. /// /// # Safety /// Callers must ensure that the type is valid or risk type confusion. #[inline] pub(crate) unsafe fn downcast_unchecked<T>(self) -> Borrowed<'a, 'py, T> { Borrowed(self.0, PhantomData, self.2) } } impl<'a, 'py, T> From<&'a Bound<'py, T>> for Borrowed<'a, 'py, T> { /// Create borrow on a Bound #[inline] fn from(instance: &'a Bound<'py, T>) -> Self { instance.as_borrowed() } } impl<T> std::fmt::Debug for Borrowed<'_, '_, T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Bound::fmt(self, f) } } impl<'py, T> Deref for Borrowed<'_, 'py, T> { type Target = Bound<'py, T>; #[inline] fn deref(&self) -> &Bound<'py, T> { // safety: Bound has the same layout as NonNull<ffi::PyObject> unsafe { &*ptr_from_ref(&self.0).cast() } } } impl<T> Clone for Borrowed<'_, '_, T> { #[inline] fn clone(&self) -> Self { *self } } impl<T> Copy for Borrowed<'_, '_, T> {} #[allow(deprecated)] impl<T> ToPyObject for Borrowed<'_, '_, T> { /// Converts `Py` instance -> PyObject. #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { (*self).into_py(py) } } #[allow(deprecated)] impl<T> IntoPy<PyObject> for Borrowed<'_, '_, T> { /// Converts `Py` instance -> PyObject. #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.to_owned().into_py(py) } } impl<'a, 'py, T> BoundObject<'py, T> for Borrowed<'a, 'py, T> { type Any = Borrowed<'a, 'py, PyAny>; fn as_borrowed(&self) -> Borrowed<'a, 'py, T> { *self } fn into_bound(self) -> Bound<'py, T> { (*self).to_owned() } fn into_any(self) -> Self::Any { self.to_any() } fn into_ptr(self) -> *mut ffi::PyObject { (*self).to_owned().into_ptr() } fn as_ptr(&self) -> *mut ffi::PyObject { (*self).as_ptr() } fn unbind(self) -> Py<T> { (*self).to_owned().unbind() } } /// A GIL-independent reference to an object allocated on the Python heap. /// /// This type does not auto-dereference to the inner object because you must prove you hold the GIL to access it. /// Instead, call one of its methods to access the inner object: /// - [`Py::bind`] or [`Py::into_bound`], to borrow a GIL-bound reference to the contained object. /// - [`Py::borrow`], [`Py::try_borrow`], [`Py::borrow_mut`], or [`Py::try_borrow_mut`], /// /// to get a (mutable) reference to a contained pyclass, using a scheme similar to std's [`RefCell`]. /// See the #[doc = concat!("[guide entry](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/class.html#bound-and-interior-mutability)")] /// for more information. /// - You can call methods directly on `Py` with [`Py::call_bound`], [`Py::call_method_bound`] and friends. /// /// These require passing in the [`Python<'py>`](crate::Python) token but are otherwise similar to the corresponding /// methods on [`PyAny`]. /// /// # Example: Storing Python objects in `#[pyclass]` structs /// /// Usually `Bound<'py, T>` is recommended for interacting with Python objects as its lifetime `'py` /// is an association to the GIL and that enables many operations to be done as efficiently as possible. /// /// However, `#[pyclass]` structs cannot carry a lifetime, so `Py<T>` is the only way to store /// a Python object in a `#[pyclass]` struct. /// /// For example, this won't compile: /// /// ```compile_fail /// # use pyo3::prelude::*; /// # use pyo3::types::PyDict; /// # /// #[pyclass] /// struct Foo<'py> { /// inner: Bound<'py, PyDict>, /// } /// /// impl Foo { /// fn new() -> Foo { /// let foo = Python::with_gil(|py| { /// // `py` will only last for this scope. /// /// // `Bound<'py, PyDict>` inherits the GIL lifetime from `py` and /// // so won't be able to outlive this closure. /// let dict: Bound<'_, PyDict> = PyDict::new(py); /// /// // because `Foo` contains `dict` its lifetime /// // is now also tied to `py`. /// Foo { inner: dict } /// }); /// // Foo is no longer valid. /// // Returning it from this function is a 💥 compiler error 💥 /// foo /// } /// } /// ``` /// /// [`Py`]`<T>` can be used to get around this by converting `dict` into a GIL-independent reference: /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// /// #[pyclass] /// struct Foo { /// inner: Py<PyDict>, /// } /// /// #[pymethods] /// impl Foo { /// #[new] /// fn __new__() -> Foo { /// Python::with_gil(|py| { /// let dict: Py<PyDict> = PyDict::new(py).unbind(); /// Foo { inner: dict } /// }) /// } /// } /// # /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| { /// # let m = pyo3::types::PyModule::new(py, "test")?; /// # m.add_class::<Foo>()?; /// # /// # let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?; /// # let dict = &foo.borrow().inner; /// # let dict: &Bound<'_, PyDict> = dict.bind(py); /// # /// # Ok(()) /// # }) /// # } /// ``` /// /// This can also be done with other pyclasses: /// ```rust /// use pyo3::prelude::*; /// /// #[pyclass] /// struct Bar {/* ... */} /// /// #[pyclass] /// struct Foo { /// inner: Py<Bar>, /// } /// /// #[pymethods] /// impl Foo { /// #[new] /// fn __new__() -> PyResult<Foo> { /// Python::with_gil(|py| { /// let bar: Py<Bar> = Py::new(py, Bar {})?; /// Ok(Foo { inner: bar }) /// }) /// } /// } /// # /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| { /// # let m = pyo3::types::PyModule::new(py, "test")?; /// # m.add_class::<Foo>()?; /// # /// # let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?; /// # let bar = &foo.borrow().inner; /// # let bar: &Bar = &*bar.borrow(py); /// # /// # Ok(()) /// # }) /// # } /// ``` /// /// # Example: Shared ownership of Python objects /// /// `Py<T>` can be used to share ownership of a Python object, similar to std's [`Rc`]`<T>`. /// As with [`Rc`]`<T>`, cloning it increases its reference count rather than duplicating /// the underlying object. /// /// This can be done using either [`Py::clone_ref`] or [`Py`]`<T>`'s [`Clone`] trait implementation. /// [`Py::clone_ref`] will be faster if you happen to be already holding the GIL. /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// /// # fn main() { /// Python::with_gil(|py| { /// let first: Py<PyDict> = PyDict::new(py).unbind(); /// /// // All of these are valid syntax /// let second = Py::clone_ref(&first, py); /// let third = first.clone_ref(py); /// #[cfg(feature = "py-clone")] /// let fourth = Py::clone(&first); /// #[cfg(feature = "py-clone")] /// let fifth = first.clone(); /// /// // Disposing of our original `Py<PyDict>` just decrements the reference count. /// drop(first); /// /// // They all point to the same object /// assert!(second.is(&third)); /// #[cfg(feature = "py-clone")] /// assert!(fourth.is(&fifth)); /// #[cfg(feature = "py-clone")] /// assert!(second.is(&fourth)); /// }); /// # } /// ``` /// /// # Preventing reference cycles /// /// It is easy to accidentally create reference cycles using [`Py`]`<T>`. /// The Python interpreter can break these reference cycles within pyclasses if they /// [integrate with the garbage collector][gc]. If your pyclass contains other Python /// objects you should implement it to avoid leaking memory. /// /// # A note on Python reference counts /// /// Dropping a [`Py`]`<T>` will eventually decrease Python's reference count /// of the pointed-to variable, allowing Python's garbage collector to free /// the associated memory, but this may not happen immediately. This is /// because a [`Py`]`<T>` can be dropped at any time, but the Python reference /// count can only be modified when the GIL is held. /// /// If a [`Py`]`<T>` is dropped while its thread happens to be holding the /// GIL then the Python reference count will be decreased immediately. /// Otherwise, the reference count will be decreased the next time the GIL is /// reacquired. /// /// If you happen to be already holding the GIL, [`Py::drop_ref`] will decrease /// the Python reference count immediately and will execute slightly faster than /// relying on implicit [`Drop`]s. /// /// # A note on `Send` and `Sync` /// /// Accessing this object is threadsafe, since any access to its API requires a [`Python<'py>`](crate::Python) token. /// As you can only get this by acquiring the GIL, `Py<...>` implements [`Send`] and [`Sync`]. /// /// [`Rc`]: std::rc::Rc /// [`RefCell`]: std::cell::RefCell /// [gc]: https://pyo3.rs/main/class/protocols.html#garbage-collector-integration #[repr(transparent)] pub struct Py<T>(NonNull<ffi::PyObject>, PhantomData<T>); // The inner value is only accessed through ways that require proving the gil is held #[cfg(feature = "nightly")] unsafe impl<T> crate::marker::Ungil for Py<T> {} unsafe impl<T> Send for Py<T> {} unsafe impl<T> Sync for Py<T> {} impl<T> Py<T> where T: PyClass, { /// Creates a new instance `Py<T>` of a `#[pyclass]` on the Python heap. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pyclass] /// struct Foo {/* fields omitted */} /// /// # fn main() -> PyResult<()> { /// let foo = Python::with_gil(|py| -> PyResult<_> { /// let foo: Py<Foo> = Py::new(py, Foo {})?; /// Ok(foo) /// })?; /// # Python::with_gil(move |_py| drop(foo)); /// # Ok(()) /// # } /// ``` pub fn new(py: Python<'_>, value: impl Into<PyClassInitializer<T>>) -> PyResult<Py<T>> { Bound::new(py, value).map(Bound::unbind) } } impl<T> Py<T> { /// Returns the raw FFI pointer represented by self. /// /// # Safety /// /// Callers are responsible for ensuring that the pointer does not outlive self. /// /// The reference is borrowed; callers should not decrease the reference count /// when they are finished with the pointer. #[inline] pub fn as_ptr(&self) -> *mut ffi::PyObject { self.0.as_ptr() } /// Returns an owned raw FFI pointer represented by self. /// /// # Safety /// /// The reference is owned; when finished the caller should either transfer ownership /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)). #[inline] pub fn into_ptr(self) -> *mut ffi::PyObject { ManuallyDrop::new(self).0.as_ptr() } /// Helper to cast to `Py<PyAny>`. #[inline] pub fn as_any(&self) -> &Py<PyAny> { // Safety: all Py<T> have the same memory layout, and all Py<T> are valid // Py<PyAny>, so pointer casting is valid. unsafe { &*ptr_from_ref(self).cast::<Py<PyAny>>() } } /// Helper to cast to `Py<PyAny>`, transferring ownership. #[inline] pub fn into_any(self) -> Py<PyAny> { // Safety: all Py<T> are valid Py<PyAny> unsafe { Py::from_non_null(ManuallyDrop::new(self).0) } } } impl<T> Py<T> where T: PyClass, { /// Immutably borrows the value `T`. /// /// This borrow lasts while the returned [`PyRef`] exists. /// Multiple immutable borrows can be taken out at the same time. /// /// For frozen classes, the simpler [`get`][Self::get] is available. /// /// Equivalent to `self.bind(py).borrow()` - see [`Bound::borrow`]. /// /// # Examples /// /// ```rust /// # use pyo3::prelude::*; /// # /// #[pyclass] /// struct Foo { /// inner: u8, /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?; /// let inner: &u8 = &foo.borrow(py).inner; /// /// assert_eq!(*inner, 73); /// Ok(()) /// })?; /// # Ok(()) /// # } /// ``` /// /// # Panics /// /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use /// [`try_borrow`](#method.try_borrow). #[inline] #[track_caller] pub fn borrow<'py>(&'py self, py: Python<'py>) -> PyRef<'py, T> { self.bind(py).borrow() } /// Mutably borrows the value `T`. /// /// This borrow lasts while the returned [`PyRefMut`] exists. /// /// Equivalent to `self.bind(py).borrow_mut()` - see [`Bound::borrow_mut`]. /// /// # Examples /// /// ``` /// # use pyo3::prelude::*; /// # /// #[pyclass] /// struct Foo { /// inner: u8, /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?; /// foo.borrow_mut(py).inner = 35; /// /// assert_eq!(foo.borrow(py).inner, 35); /// Ok(()) /// })?; /// # Ok(()) /// # } /// ``` /// /// # Panics /// Panics if the value is currently borrowed. For a non-panicking variant, use /// [`try_borrow_mut`](#method.try_borrow_mut). #[inline] #[track_caller] pub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T> where T: PyClass<Frozen = False>, { self.bind(py).borrow_mut() } /// Attempts to immutably borrow the value `T`, returning an error if the value is currently mutably borrowed. /// /// The borrow lasts while the returned [`PyRef`] exists. /// /// This is the non-panicking variant of [`borrow`](#method.borrow). /// /// For frozen classes, the simpler [`get`][Self::get] is available. /// /// Equivalent to `self.bind(py).try_borrow()` - see [`Bound::try_borrow`]. #[inline] pub fn try_borrow<'py>(&'py self, py: Python<'py>) -> Result<PyRef<'py, T>, PyBorrowError> { self.bind(py).try_borrow() } /// Attempts to mutably borrow the value `T`, returning an error if the value is currently borrowed. /// /// The borrow lasts while the returned [`PyRefMut`] exists. /// /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). /// /// Equivalent to `self.bind(py).try_borrow_mut()` - see [`Bound::try_borrow_mut`]. #[inline] pub fn try_borrow_mut<'py>( &'py self, py: Python<'py>, ) -> Result<PyRefMut<'py, T>, PyBorrowMutError> where T: PyClass<Frozen = False>, { self.bind(py).try_borrow_mut() } /// Provide an immutable borrow of the value `T` without acquiring the GIL. /// /// This is available if the class is [`frozen`][macro@crate::pyclass] and [`Sync`]. /// /// # Examples /// /// ``` /// use std::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] /// struct FrozenCounter { /// value: AtomicUsize, /// } /// /// let cell = Python::with_gil(|py| { /// let counter = FrozenCounter { value: AtomicUsize::new(0) }; /// /// Py::new(py, counter).unwrap() /// }); /// /// cell.get().value.fetch_add(1, Ordering::Relaxed); /// # Python::with_gil(move |_py| drop(cell)); /// ``` #[inline] pub fn get(&self) -> &T where T: PyClass<Frozen = True> + Sync, { // Safety: The class itself is frozen and `Sync` unsafe { &*self.get_class_object().get_ptr() } } /// Get a view on the underlying `PyClass` contents. #[inline] pub(crate) fn get_class_object(&self) -> &PyClassObject<T> { let class_object = self.as_ptr().cast::<PyClassObject<T>>(); // Safety: Bound<T: PyClass> is known to contain an object which is laid out in memory as a // PyClassObject<T>. unsafe { &*class_object } } } impl<T> Py<T> { /// Attaches this `Py` to the given Python context, allowing access to further Python APIs. #[inline] pub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T> { // Safety: `Bound` has the same layout as `Py` unsafe { &*ptr_from_ref(self).cast() } } /// Same as `bind` but takes ownership of `self`. #[inline] pub fn into_bound(self, py: Python<'_>) -> Bound<'_, T> { Bound(py, ManuallyDrop::new(self)) } /// Same as `bind` but produces a `Borrowed<T>` instead of a `Bound<T>`. #[inline] pub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T> { Borrowed(self.0, PhantomData, py) } /// Returns whether `self` and `other` point to the same object. To compare /// the equality of two objects (the `==` operator), use [`eq`](PyAnyMethods::eq). /// /// This is equivalent to the Python expression `self is other`. #[inline] pub fn is<U: AsPyPointer>(&self, o: &U) -> bool { self.as_ptr() == o.as_ptr() } /// Gets the reference count of the `ffi::PyObject` pointer. #[inline] pub fn get_refcnt(&self, _py: Python<'_>) -> isize { unsafe { ffi::Py_REFCNT(self.0.as_ptr()) } } /// Makes a clone of `self`. /// /// This creates another pointer to the same object, increasing its reference count. /// /// You should prefer using this method over [`Clone`] if you happen to be holding the GIL already. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// /// # fn main() { /// Python::with_gil(|py| { /// let first: Py<PyDict> = PyDict::new(py).unbind(); /// let second = Py::clone_ref(&first, py); /// /// // Both point to the same object /// assert!(first.is(&second)); /// }); /// # } /// ``` #[inline] pub fn clone_ref(&self, _py: Python<'_>) -> Py<T> { unsafe { ffi::Py_INCREF(self.as_ptr()); Self::from_non_null(self.0) } } /// Drops `self` and immediately decreases its reference count. /// /// This method is a micro-optimisation over [`Drop`] if you happen to be holding the GIL /// already. /// /// Note that if you are using [`Bound`], you do not need to use [`Self::drop_ref`] since /// [`Bound`] guarantees that the GIL is held. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// /// # fn main() { /// Python::with_gil(|py| { /// let object: Py<PyDict> = PyDict::new(py).unbind(); /// /// // some usage of object /// /// object.drop_ref(py); /// }); /// # } /// ``` #[inline] pub fn drop_ref(self, py: Python<'_>) { let _ = self.into_bound(py); } /// Returns whether the object is considered to be None. /// /// This is equivalent to the Python expression `self is None`. pub fn is_none(&self, _py: Python<'_>) -> bool { unsafe { ffi::Py_None() == self.as_ptr() } } /// Returns whether the object is considered to be true. /// /// This applies truth value testing equivalent to the Python expression `bool(self)`. pub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool> { let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) }; err::error_on_minusone(py, v)?; Ok(v != 0) } /// Extracts some type from the Python object. /// /// This is a wrapper function around `FromPyObject::extract()`. pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> PyResult<D> where D: crate::conversion::FromPyObjectBound<'a, 'py>, // TODO it might be possible to relax this bound in future, to allow // e.g. `.extract::<&str>(py)` where `py` is short-lived. 'py: 'a, { self.bind(py).as_any().extract() } /// Retrieves an attribute value. /// /// This is equivalent to the Python expression `self.attr_name`. /// /// If calling this method becomes performance-critical, the [`intern!`](crate::intern) macro /// can be used to intern `attr_name`, thereby avoiding repeated temporary allocations of /// Python strings. /// /// # Example: `intern!`ing the attribute name /// /// ``` /// # use pyo3::{prelude::*, intern}; /// # /// #[pyfunction] /// fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<PyObject> { /// sys.getattr(py, intern!(py, "version")) /// } /// # /// # Python::with_gil(|py| { /// # let sys = py.import("sys").unwrap().unbind(); /// # version(sys, py).unwrap(); /// # }); /// ``` pub fn getattr<'py, N>(&self, py: Python<'py>, attr_name: N) -> PyResult<PyObject> where N: IntoPyObject<'py, Target = PyString>, { self.bind(py).as_any().getattr(attr_name).map(Bound::unbind) } /// Sets an attribute value. /// /// This is equivalent to the Python expression `self.attr_name = value`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern) /// macro can be used to intern `attr_name`. /// /// # Example: `intern!`ing the attribute name /// /// ``` /// # use pyo3::{intern, pyfunction, types::PyModule, IntoPyObject, PyObject, Python, PyResult}; /// # /// #[pyfunction] /// fn set_answer(ob: PyObject, py: Python<'_>) -> PyResult<()> { /// ob.setattr(py, intern!(py, "answer"), 42) /// } /// # /// # Python::with_gil(|py| { /// # let ob = PyModule::new(py, "empty").unwrap().into_pyobject(py).unwrap().into_any().unbind(); /// # set_answer(ob, py).unwrap(); /// # }); /// ``` pub fn setattr<'py, N, V>(&self, py: Python<'py>, attr_name: N, value: V) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>, V: IntoPyObject<'py>, { self.bind(py).as_any().setattr(attr_name, value) } /// Calls the object. /// /// This is equivalent to the Python expression `self(*args, **kwargs)`. pub fn call<'py, A>( &self, py: Python<'py>, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<PyObject> where A: IntoPyObject<'py, Target = PyTuple>, { self.bind(py) .as_any() .call( // FIXME(icxolu): remove explicit args conversion args.into_pyobject(py).map_err(Into::into)?.into_bound(), kwargs, ) .map(Bound::unbind) } /// Deprecated name for [`Py::call`]. #[deprecated(since = "0.23.0", note = "renamed to `Py::call`")] #[allow(deprecated)] #[inline] pub fn call_bound( &self, py: Python<'_>, args: impl IntoPy<Py<PyTuple>>, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<PyObject> { self.call(py, args.into_py(py), kwargs) } /// Calls the object with only positional arguments. /// /// This is equivalent to the Python expression `self(*args)`. pub fn call1<'py, N>(&self, py: Python<'py>, args: N) -> PyResult<PyObject> where N: IntoPyObject<'py, Target = PyTuple>, { self.bind(py) .as_any() // FIXME(icxolu): remove explicit args conversion .call1(args.into_pyobject(py).map_err(Into::into)?.into_bound()) .map(Bound::unbind) } /// Calls the object without arguments. /// /// This is equivalent to the Python expression `self()`. pub fn call0(&self, py: Python<'_>) -> PyResult<PyObject> { self.bind(py).as_any().call0().map(Bound::unbind) } /// Calls a method on the object. /// /// This is equivalent to the Python expression `self.name(*args, **kwargs)`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern) /// macro can be used to intern `name`. pub fn call_method<'py, N, A>( &self, py: Python<'py>, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<PyObject> where N: IntoPyObject<'py, Target = PyString>, A: IntoPyObject<'py, Target = PyTuple>, { self.bind(py) .as_any() .call_method( name, // FIXME(icxolu): remove explicit args conversion args.into_pyobject(py).map_err(Into::into)?.into_bound(), kwargs, ) .map(Bound::unbind) } /// Deprecated name for [`Py::call_method`]. #[deprecated(since = "0.23.0", note = "renamed to `Py::call_method`")] #[allow(deprecated)] #[inline] pub fn call_method_bound<N, A>( &self, py: Python<'_>, name: N, args: A, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<PyObject> where N: IntoPy<Py<PyString>>, A: IntoPy<Py<PyTuple>>, { self.call_method(py, name.into_py(py), args.into_py(py), kwargs) } /// Calls a method on the object with only positional arguments. /// /// This is equivalent to the Python expression `self.name(*args)`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern) /// macro can be used to intern `name`. pub fn call_method1<'py, N, A>(&self, py: Python<'py>, name: N, args: A) -> PyResult<PyObject> where N: IntoPyObject<'py, Target = PyString>, A: IntoPyObject<'py, Target = PyTuple>, { self.bind(py) .as_any() .call_method1( name, // FIXME(icxolu): remove explicit args conversion args.into_pyobject(py).map_err(Into::into)?.into_bound(), ) .map(Bound::unbind) } /// Calls a method on the object with no arguments. /// /// This is equivalent to the Python expression `self.name()`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern) /// macro can be used to intern `name`. pub fn call_method0<'py, N>(&self, py: Python<'py>, name: N) -> PyResult<PyObject> where N: IntoPyObject<'py, Target = PyString>, { self.bind(py).as_any().call_method0(name).map(Bound::unbind) } /// Create a `Py<T>` instance by taking ownership of the given FFI pointer. /// /// # Safety /// `ptr` must be a pointer to a Python object of type T. /// /// Callers must own the object referred to by `ptr`, as this function /// implicitly takes ownership of that object. /// /// # Panics /// Panics if `ptr` is null. #[inline] #[track_caller] pub unsafe fn from_owned_ptr(py: Python<'_>, ptr: *mut ffi::PyObject) -> Py<T> { match NonNull::new(ptr) { Some(nonnull_ptr) => Py(nonnull_ptr, PhantomData), None => crate::err::panic_after_error(py), } } /// Create a `Py<T>` instance by taking ownership of the given FFI pointer. /// /// If `ptr` is null then the current Python exception is fetched as a [`PyErr`]. /// /// # Safety /// If non-null, `ptr` must be a pointer to a Python object of type T. #[inline] pub unsafe fn from_owned_ptr_or_err( py: Python<'_>, ptr: *mut ffi::PyObject, ) -> PyResult<Py<T>> { match NonNull::new(ptr) { Some(nonnull_ptr) => Ok(Py(nonnull_ptr, PhantomData)), None => Err(PyErr::fetch(py)), } } /// Create a `Py<T>` instance by taking ownership of the given FFI pointer. /// /// If `ptr` is null then `None` is returned. /// /// # Safety /// If non-null, `ptr` must be a pointer to a Python object of type T. #[inline] pub unsafe fn from_owned_ptr_or_opt(_py: Python<'_>, ptr: *mut ffi::PyObject) -> Option<Self> { NonNull::new(ptr).map(|nonnull_ptr| Py(nonnull_ptr, PhantomData)) } /// Constructs a new `Py<T>` instance by taking ownership of the given FFI pointer. /// /// # Safety /// /// - `ptr` must be a non-null pointer to a Python object or type `T`. pub(crate) unsafe fn from_owned_ptr_unchecked(ptr: *mut ffi::PyObject) -> Self { Py(NonNull::new_unchecked(ptr), PhantomData) } /// Create a `Py<T>` instance by creating a new reference from the given FFI pointer. /// /// # Safety /// `ptr` must be a pointer to a Python object of type T. /// /// # Panics /// Panics if `ptr` is null. #[inline] #[track_caller] pub unsafe fn from_borrowed_ptr(py: Python<'_>, ptr: *mut ffi::PyObject) -> Py<T> { match Self::from_borrowed_ptr_or_opt(py, ptr) { Some(slf) => slf, None => crate::err::panic_after_error(py), } } /// Create a `Py<T>` instance by creating a new reference from the given FFI pointer. /// /// If `ptr` is null then the current Python exception is fetched as a `PyErr`. /// /// # Safety /// `ptr` must be a pointer to a Python object of type T. #[inline] pub unsafe fn from_borrowed_ptr_or_err( py: Python<'_>, ptr: *mut ffi::PyObject, ) -> PyResult<Self> { Self::from_borrowed_ptr_or_opt(py, ptr).ok_or_else(|| PyErr::fetch(py)) } /// Create a `Py<T>` instance by creating a new reference from the given FFI pointer. /// /// If `ptr` is null then `None` is returned. /// /// # Safety /// `ptr` must be a pointer to a Python object of type T. #[inline] pub unsafe fn from_borrowed_ptr_or_opt( _py: Python<'_>, ptr: *mut ffi::PyObject, ) -> Option<Self> { NonNull::new(ptr).map(|nonnull_ptr| { ffi::Py_INCREF(ptr); Py(nonnull_ptr, PhantomData) }) } /// For internal conversions. /// /// # Safety /// `ptr` must point to a Python object of type T. unsafe fn from_non_null(ptr: NonNull<ffi::PyObject>) -> Self { Self(ptr, PhantomData) } } #[allow(deprecated)] impl<T> ToPyObject for Py<T> { /// Converts `Py` instance -> PyObject. #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { self.clone_ref(py).into_any() } } #[allow(deprecated)] impl<T> IntoPy<PyObject> for Py<T> { /// Converts a `Py` instance to `PyObject`. /// Consumes `self` without calling `Py_DECREF()`. #[inline] fn into_py(self, _py: Python<'_>) -> PyObject { self.into_any() } } #[allow(deprecated)] impl<T> IntoPy<PyObject> for &'_ Py<T> { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } #[allow(deprecated)] impl<T> ToPyObject for Bound<'_, T> { /// Converts `&Bound` instance -> PyObject, increasing the reference count. #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { self.clone().into_py(py) } } #[allow(deprecated)] impl<T> IntoPy<PyObject> for Bound<'_, T> { /// Converts a `Bound` instance to `PyObject`. #[inline] fn into_py(self, _py: Python<'_>) -> PyObject { self.into_any().unbind() } } #[allow(deprecated)] impl<T> IntoPy<PyObject> for &Bound<'_, T> { /// Converts `&Bound` instance -> PyObject, increasing the reference count. #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } unsafe impl<T> crate::AsPyPointer for Py<T> { /// Gets the underlying FFI pointer, returns a borrowed pointer. #[inline] fn as_ptr(&self) -> *mut ffi::PyObject { self.0.as_ptr() } } impl<T> std::convert::From<Py<T>> for PyObject where T: AsRef<PyAny>, { #[inline] fn from(other: Py<T>) -> Self { other.into_any() } } impl<T> std::convert::From<Bound<'_, T>> for PyObject where T: AsRef<PyAny>, { #[inline] fn from(other: Bound<'_, T>) -> Self { other.into_any().unbind() } } impl<T> std::convert::From<Bound<'_, T>> for Py<T> { #[inline] fn from(other: Bound<'_, T>) -> Self { other.unbind() } } impl<'a, T> std::convert::From<PyRef<'a, T>> for Py<T> where T: PyClass, { fn from(pyref: PyRef<'a, T>) -> Self { unsafe { Py::from_borrowed_ptr(pyref.py(), pyref.as_ptr()) } } } impl<'a, T> std::convert::From<PyRefMut<'a, T>> for Py<T> where T: PyClass<Frozen = False>, { fn from(pyref: PyRefMut<'a, T>) -> Self { unsafe { Py::from_borrowed_ptr(pyref.py(), pyref.as_ptr()) } } } /// If the GIL is held this increments `self`'s reference count. /// Otherwise, it will panic. /// /// Only available if the `py-clone` feature is enabled. #[cfg(feature = "py-clone")] impl<T> Clone for Py<T> { #[track_caller] fn clone(&self) -> Self { unsafe { gil::register_incref(self.0); } Self(self.0, PhantomData) } } /// Dropping a `Py` instance decrements the reference count /// on the object by one if the GIL is held. /// /// Otherwise and by default, this registers the underlying pointer to have its reference count /// decremented the next time PyO3 acquires the GIL. /// /// However, if the `pyo3_disable_reference_pool` conditional compilation flag /// is enabled, it will abort the process. impl<T> Drop for Py<T> { #[track_caller] fn drop(&mut self) { unsafe { gil::register_decref(self.0); } } } impl<T> FromPyObject<'_> for Py<T> where T: PyTypeCheck, { /// Extracts `Self` from the source `PyObject`. fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> { ob.extract::<Bound<'_, T>>().map(Bound::unbind) } } impl<'py, T> FromPyObject<'py> for Bound<'py, T> where T: PyTypeCheck, { /// Extracts `Self` from the source `PyObject`. fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> { ob.downcast().cloned().map_err(Into::into) } } impl<T> std::fmt::Display for Py<T> where T: PyTypeInfo, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Python::with_gil(|py| std::fmt::Display::fmt(self.bind(py), f)) } } impl<T> std::fmt::Debug for Py<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("Py").field(&self.0.as_ptr()).finish() } } /// A commonly-used alias for `Py<PyAny>`. /// /// This is an owned reference a Python object without any type information. This value can also be /// safely sent between threads. /// /// See the documentation for [`Py`](struct.Py.html). pub type PyObject = Py<PyAny>; impl PyObject { /// Downcast this `PyObject` to a concrete Python type or pyclass. /// /// Note that you can often avoid downcasting yourself by just specifying /// the desired type in function or method signatures. /// However, manual downcasting is sometimes necessary. /// /// For extracting a Rust-only type, see [`Py::extract`](struct.Py.html#method.extract). /// /// # Example: Downcasting to a specific Python object /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::{PyDict, PyList}; /// /// Python::with_gil(|py| { /// let any: PyObject = PyDict::new(py).into(); /// /// assert!(any.downcast_bound::<PyDict>(py).is_ok()); /// assert!(any.downcast_bound::<PyList>(py).is_err()); /// }); /// ``` /// /// # Example: Getting a reference to a pyclass /// /// This is useful if you want to mutate a `PyObject` that /// might actually be a pyclass. /// /// ```rust /// # fn main() -> Result<(), pyo3::PyErr> { /// use pyo3::prelude::*; /// /// #[pyclass] /// struct Class { /// i: i32, /// } /// /// Python::with_gil(|py| { /// let class: PyObject = Py::new(py, Class { i: 0 })?.into_any(); /// /// let class_bound = class.downcast_bound::<Class>(py)?; /// /// class_bound.borrow_mut().i += 1; /// /// // Alternatively you can get a `PyRefMut` directly /// let class_ref: PyRefMut<'_, Class> = class.extract(py)?; /// assert_eq!(class_ref.i, 1); /// Ok(()) /// }) /// # } /// ``` #[inline] pub fn downcast_bound<'py, T>( &self, py: Python<'py>, ) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> where T: PyTypeCheck, { self.bind(py).downcast() } /// Casts the PyObject to a concrete Python object type without checking validity. /// /// # Safety /// /// Callers must ensure that the type is valid or risk type confusion. #[inline] pub unsafe fn downcast_bound_unchecked<'py, T>(&self, py: Python<'py>) -> &Bound<'py, T> { self.bind(py).downcast_unchecked() } } #[cfg(test)] mod tests { use super::{Bound, IntoPyObject, Py, PyObject}; use crate::tests::common::generate_unique_module_name; use crate::types::{dict::IntoPyDict, PyAnyMethods, PyCapsule, PyDict, PyString}; use crate::{ffi, Borrowed, PyAny, PyResult, Python}; use pyo3_ffi::c_str; use std::ffi::CStr; #[test] fn test_call() { Python::with_gil(|py| { let obj = py.get_type::<PyDict>().into_pyobject(py).unwrap(); let assert_repr = |obj: Bound<'_, PyAny>, expected: &str| { assert_eq!(obj.repr().unwrap(), expected); }; assert_repr(obj.call0().unwrap(), "{}"); assert_repr(obj.call1(()).unwrap(), "{}"); assert_repr(obj.call((), None).unwrap(), "{}"); assert_repr(obj.call1(((('x', 1),),)).unwrap(), "{'x': 1}"); assert_repr( obj.call((), Some(&[('x', 1)].into_py_dict(py).unwrap())) .unwrap(), "{'x': 1}", ); }) } #[test] fn test_call_for_non_existing_method() { Python::with_gil(|py| { let obj: PyObject = PyDict::new(py).into(); assert!(obj.call_method0(py, "asdf").is_err()); assert!(obj .call_method(py, "nonexistent_method", (1,), None) .is_err()); assert!(obj.call_method0(py, "nonexistent_method").is_err()); assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err()); }); } #[test] fn py_from_dict() { let dict: Py<PyDict> = Python::with_gil(|py| { let native = PyDict::new(py); Py::from(native) }); Python::with_gil(move |py| { assert_eq!(dict.get_refcnt(py), 1); }); } #[test] fn pyobject_from_py() { Python::with_gil(|py| { let dict: Py<PyDict> = PyDict::new(py).unbind(); let cnt = dict.get_refcnt(py); let p: PyObject = dict.into(); assert_eq!(p.get_refcnt(py), cnt); }); } #[test] fn attr() -> PyResult<()> { use crate::types::PyModule; Python::with_gil(|py| { const CODE: &CStr = c_str!( r#" class A: pass a = A() "# ); let module = PyModule::from_code(py, CODE, c_str!(""), &generate_unique_module_name(""))?; let instance: Py<PyAny> = module.getattr("a")?.into(); instance.getattr(py, "foo").unwrap_err(); instance.setattr(py, "foo", "bar")?; assert!(instance .getattr(py, "foo")? .bind(py) .eq(PyString::new(py, "bar"))?); instance.getattr(py, "foo")?; Ok(()) }) } #[test] fn pystring_attr() -> PyResult<()> { use crate::types::PyModule; Python::with_gil(|py| { const CODE: &CStr = c_str!( r#" class A: pass a = A() "# ); let module = PyModule::from_code(py, CODE, c_str!(""), &generate_unique_module_name(""))?; let instance: Py<PyAny> = module.getattr("a")?.into(); let foo = crate::intern!(py, "foo"); let bar = crate::intern!(py, "bar"); instance.getattr(py, foo).unwrap_err(); instance.setattr(py, foo, bar)?; assert!(instance.getattr(py, foo)?.bind(py).eq(bar)?); Ok(()) }) } #[test] fn invalid_attr() -> PyResult<()> { Python::with_gil(|py| { let instance: Py<PyAny> = py.eval(ffi::c_str!("object()"), None, None)?.into(); instance.getattr(py, "foo").unwrap_err(); // Cannot assign arbitrary attributes to `object` instance.setattr(py, "foo", "bar").unwrap_err(); Ok(()) }) } #[test] fn test_py2_from_py_object() { Python::with_gil(|py| { let instance = py.eval(ffi::c_str!("object()"), None, None).unwrap(); let ptr = instance.as_ptr(); let instance: Bound<'_, PyAny> = instance.extract().unwrap(); assert_eq!(instance.as_ptr(), ptr); }) } #[test] fn test_py2_into_py_object() { Python::with_gil(|py| { let instance = py.eval(ffi::c_str!("object()"), None, None).unwrap(); let ptr = instance.as_ptr(); let instance: PyObject = instance.clone().unbind(); assert_eq!(instance.as_ptr(), ptr); }) } #[test] fn test_debug_fmt() { Python::with_gil(|py| { let obj = "hello world".into_pyobject(py).unwrap(); assert_eq!(format!("{:?}", obj), "'hello world'"); }); } #[test] fn test_display_fmt() { Python::with_gil(|py| { let obj = "hello world".into_pyobject(py).unwrap(); assert_eq!(format!("{}", obj), "hello world"); }); } #[test] fn test_bound_as_any() { Python::with_gil(|py| { let obj = PyString::new(py, "hello world"); let any = obj.as_any(); assert_eq!(any.as_ptr(), obj.as_ptr()); }); } #[test] fn test_bound_into_any() { Python::with_gil(|py| { let obj = PyString::new(py, "hello world"); let any = obj.clone().into_any(); assert_eq!(any.as_ptr(), obj.as_ptr()); }); } #[test] fn test_bound_py_conversions() { Python::with_gil(|py| { let obj: Bound<'_, PyString> = PyString::new(py, "hello world"); let obj_unbound: &Py<PyString> = obj.as_unbound(); let _: &Bound<'_, PyString> = obj_unbound.bind(py); let obj_unbound: Py<PyString> = obj.unbind(); let obj: Bound<'_, PyString> = obj_unbound.into_bound(py); assert_eq!(obj, "hello world"); }); } #[test] fn bound_from_borrowed_ptr_constructors() { // More detailed tests of the underlying semantics in pycell.rs Python::with_gil(|py| { fn check_drop<'py>( py: Python<'py>, method: impl FnOnce(*mut ffi::PyObject) -> Bound<'py, PyAny>, ) { let mut dropped = false; let capsule = PyCapsule::new_with_destructor( py, (&mut dropped) as *mut _ as usize, None, |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) }, ) .unwrap(); let bound = method(capsule.as_ptr()); assert!(!dropped); // creating the bound should have increased the refcount drop(capsule); assert!(!dropped); // dropping the bound should now also decrease the refcount and free the object drop(bound); assert!(dropped); } check_drop(py, |ptr| unsafe { Bound::from_borrowed_ptr(py, ptr) }); check_drop(py, |ptr| unsafe { Bound::from_borrowed_ptr_or_opt(py, ptr).unwrap() }); check_drop(py, |ptr| unsafe { Bound::from_borrowed_ptr_or_err(py, ptr).unwrap() }); }) } #[test] fn borrowed_ptr_constructors() { // More detailed tests of the underlying semantics in pycell.rs Python::with_gil(|py| { fn check_drop<'py>( py: Python<'py>, method: impl FnOnce(&*mut ffi::PyObject) -> Borrowed<'_, 'py, PyAny>, ) { let mut dropped = false; let capsule = PyCapsule::new_with_destructor( py, (&mut dropped) as *mut _ as usize, None, |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) }, ) .unwrap(); let ptr = &capsule.as_ptr(); let _borrowed = method(ptr); assert!(!dropped); // creating the borrow should not have increased the refcount drop(capsule); assert!(dropped); } check_drop(py, |&ptr| unsafe { Borrowed::from_ptr(py, ptr) }); check_drop(py, |&ptr| unsafe { Borrowed::from_ptr_or_opt(py, ptr).unwrap() }); check_drop(py, |&ptr| unsafe { Borrowed::from_ptr_or_err(py, ptr).unwrap() }); }) } #[test] fn explicit_drop_ref() { Python::with_gil(|py| { let object: Py<PyDict> = PyDict::new(py).unbind(); let object2 = object.clone_ref(py); assert_eq!(object.as_ptr(), object2.as_ptr()); assert_eq!(object.get_refcnt(py), 2); object.drop_ref(py); assert_eq!(object2.get_refcnt(py), 1); object2.drop_ref(py); }); } #[cfg(feature = "macros")] mod using_macros { use super::*; #[crate::pyclass(crate = "crate")] struct SomeClass(i32); #[test] fn py_borrow_methods() { // More detailed tests of the underlying semantics in pycell.rs Python::with_gil(|py| { let instance = Py::new(py, SomeClass(0)).unwrap(); assert_eq!(instance.borrow(py).0, 0); assert_eq!(instance.try_borrow(py).unwrap().0, 0); assert_eq!(instance.borrow_mut(py).0, 0); assert_eq!(instance.try_borrow_mut(py).unwrap().0, 0); instance.borrow_mut(py).0 = 123; assert_eq!(instance.borrow(py).0, 123); assert_eq!(instance.try_borrow(py).unwrap().0, 123); assert_eq!(instance.borrow_mut(py).0, 123); assert_eq!(instance.try_borrow_mut(py).unwrap().0, 123); }) } #[test] fn bound_borrow_methods() { // More detailed tests of the underlying semantics in pycell.rs Python::with_gil(|py| { let instance = Bound::new(py, SomeClass(0)).unwrap(); assert_eq!(instance.borrow().0, 0); assert_eq!(instance.try_borrow().unwrap().0, 0); assert_eq!(instance.borrow_mut().0, 0); assert_eq!(instance.try_borrow_mut().unwrap().0, 0); instance.borrow_mut().0 = 123; assert_eq!(instance.borrow().0, 123); assert_eq!(instance.try_borrow().unwrap().0, 123); assert_eq!(instance.borrow_mut().0, 123); assert_eq!(instance.try_borrow_mut().unwrap().0, 123); }) } #[crate::pyclass(frozen, crate = "crate")] struct FrozenClass(i32); #[test] fn test_frozen_get() { Python::with_gil(|py| { for i in 0..10 { let instance = Py::new(py, FrozenClass(i)).unwrap(); assert_eq!(instance.get().0, i); assert_eq!(instance.bind(py).get().0, i); } }) } #[crate::pyclass(crate = "crate", subclass)] struct BaseClass; trait MyClassMethods<'py>: Sized { fn pyrepr_by_ref(&self) -> PyResult<String>; fn pyrepr_by_val(self) -> PyResult<String> { self.pyrepr_by_ref() } } impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> { fn pyrepr_by_ref(&self) -> PyResult<String> { self.call_method0("__repr__")?.extract() } } #[crate::pyclass(crate = "crate", extends = BaseClass)] struct SubClass; #[test] fn test_as_super() { Python::with_gil(|py| { let obj = Bound::new(py, (SubClass, BaseClass)).unwrap(); let _: &Bound<'_, BaseClass> = obj.as_super(); let _: &Bound<'_, PyAny> = obj.as_super().as_super(); assert!(obj.as_super().pyrepr_by_ref().is_ok()); }) } #[test] fn test_into_super() { Python::with_gil(|py| { let obj = Bound::new(py, (SubClass, BaseClass)).unwrap(); let _: Bound<'_, BaseClass> = obj.clone().into_super(); let _: Bound<'_, PyAny> = obj.clone().into_super().into_super(); assert!(obj.into_super().pyrepr_by_val().is_ok()); }) } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3
lc_public_repos/langsmith-sdk/vendor/pyo3/src/coroutine.rs
//! Python coroutine implementation, used notably when wrapping `async fn` //! with `#[pyfunction]`/`#[pymethods]`. use std::{ future::Future, panic, pin::Pin, sync::Arc, task::{Context, Poll, Waker}, }; use pyo3_macros::{pyclass, pymethods}; use crate::{ coroutine::{cancel::ThrowCallback, waker::AsyncioWaker}, exceptions::{PyAttributeError, PyRuntimeError, PyStopIteration}, panic::PanicException, types::{string::PyStringMethods, PyIterator, PyString}, Bound, BoundObject, IntoPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python, }; pub(crate) mod cancel; mod waker; pub use cancel::CancelHandle; const COROUTINE_REUSED_ERROR: &str = "cannot reuse already awaited coroutine"; /// Python coroutine wrapping a [`Future`]. #[pyclass(crate = "crate")] pub struct Coroutine { name: Option<Py<PyString>>, qualname_prefix: Option<&'static str>, throw_callback: Option<ThrowCallback>, future: Option<Pin<Box<dyn Future<Output = PyResult<PyObject>> + Send>>>, waker: Option<Arc<AsyncioWaker>>, } // Safety: `Coroutine` is allowed to be `Sync` even though the future is not, // because the future is polled with `&mut self` receiver unsafe impl Sync for Coroutine {} impl Coroutine { /// Wrap a future into a Python coroutine. /// /// Coroutine `send` polls the wrapped future, ignoring the value passed /// (should always be `None` anyway). /// /// `Coroutine `throw` drop the wrapped future and reraise the exception passed pub(crate) fn new<'py, F, T, E>( name: Option<Bound<'py, PyString>>, qualname_prefix: Option<&'static str>, throw_callback: Option<ThrowCallback>, future: F, ) -> Self where F: Future<Output = Result<T, E>> + Send + 'static, T: IntoPyObject<'py>, E: Into<PyErr>, { let wrap = async move { let obj = future.await.map_err(Into::into)?; // SAFETY: GIL is acquired when future is polled (see `Coroutine::poll`) obj.into_pyobject(unsafe { Python::assume_gil_acquired() }) .map(BoundObject::into_any) .map(BoundObject::unbind) .map_err(Into::into) }; Self { name: name.map(Bound::unbind), qualname_prefix, throw_callback, future: Some(Box::pin(wrap)), waker: None, } } fn poll(&mut self, py: Python<'_>, throw: Option<PyObject>) -> PyResult<PyObject> { // raise if the coroutine has already been run to completion let future_rs = match self.future { Some(ref mut fut) => fut, None => return Err(PyRuntimeError::new_err(COROUTINE_REUSED_ERROR)), }; // reraise thrown exception it match (throw, &self.throw_callback) { (Some(exc), Some(cb)) => cb.throw(exc), (Some(exc), None) => { self.close(); return Err(PyErr::from_value(exc.into_bound(py))); } (None, _) => {} } // create a new waker, or try to reset it in place if let Some(waker) = self.waker.as_mut().and_then(Arc::get_mut) { waker.reset(); } else { self.waker = Some(Arc::new(AsyncioWaker::new())); } let waker = Waker::from(self.waker.clone().unwrap()); // poll the Rust future and forward its results if ready // polling is UnwindSafe because the future is dropped in case of panic let poll = || future_rs.as_mut().poll(&mut Context::from_waker(&waker)); match panic::catch_unwind(panic::AssertUnwindSafe(poll)) { Ok(Poll::Ready(res)) => { self.close(); return Err(PyStopIteration::new_err((res?,))); } Err(err) => { self.close(); return Err(PanicException::from_panic_payload(err)); } _ => {} } // otherwise, initialize the waker `asyncio.Future` if let Some(future) = self.waker.as_ref().unwrap().initialize_future(py)? { // `asyncio.Future` must be awaited; fortunately, it implements `__iter__ = __await__` // and will yield itself if its result has not been set in polling above if let Some(future) = PyIterator::from_object(future).unwrap().next() { // future has not been leaked into Python for now, and Rust code can only call // `set_result(None)` in `Wake` implementation, so it's safe to unwrap return Ok(future.unwrap().into()); } } // if waker has been waken during future polling, this is roughly equivalent to // `await asyncio.sleep(0)`, so just yield `None`. Ok(py.None()) } } #[pymethods(crate = "crate")] impl Coroutine { #[getter] fn __name__(&self, py: Python<'_>) -> PyResult<Py<PyString>> { match &self.name { Some(name) => Ok(name.clone_ref(py)), None => Err(PyAttributeError::new_err("__name__")), } } #[getter] fn __qualname__(&self, py: Python<'_>) -> PyResult<Py<PyString>> { match (&self.name, &self.qualname_prefix) { (Some(name), Some(prefix)) => format!("{}.{}", prefix, name.bind(py).to_cow()?) .as_str() .into_pyobject(py) .map(BoundObject::unbind) .map_err(Into::into), (Some(name), None) => Ok(name.clone_ref(py)), (None, _) => Err(PyAttributeError::new_err("__qualname__")), } } fn send(&mut self, py: Python<'_>, _value: &Bound<'_, PyAny>) -> PyResult<PyObject> { self.poll(py, None) } fn throw(&mut self, py: Python<'_>, exc: PyObject) -> PyResult<PyObject> { self.poll(py, Some(exc)) } fn close(&mut self) { // the Rust future is dropped, and the field set to `None` // to indicate the coroutine has been run to completion drop(self.future.take()); } fn __await__(self_: Py<Self>) -> Py<Self> { self_ } fn __next__(&mut self, py: Python<'_>) -> PyResult<PyObject> { self.poll(py, None) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/complex.rs
#[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] use crate::py_result_ext::PyResultExt; use crate::{ffi, types::any::PyAnyMethods, Bound, PyAny, Python}; use std::os::raw::c_double; /// Represents a Python [`complex`](https://docs.python.org/3/library/functions.html#complex) object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyComplex>`][crate::Py] or [`Bound<'py, PyComplex>`][Bound]. /// /// For APIs available on `complex` objects, see the [`PyComplexMethods`] trait which is implemented for /// [`Bound<'py, PyComplex>`][Bound]. /// /// Note that `PyComplex` supports only basic operations. For advanced operations /// consider using [num-complex](https://docs.rs/num-complex)'s [`Complex`] type instead. /// This optional dependency can be activated with the `num-complex` feature flag. /// /// [`Complex`]: https://docs.rs/num-complex/latest/num_complex/struct.Complex.html #[repr(transparent)] pub struct PyComplex(PyAny); pyobject_subclassable_native_type!(PyComplex, ffi::PyComplexObject); pyobject_native_type!( PyComplex, ffi::PyComplexObject, pyobject_native_static_type_object!(ffi::PyComplex_Type), #checkfunction=ffi::PyComplex_Check ); impl PyComplex { /// Creates a new `PyComplex` from the given real and imaginary values. pub fn from_doubles(py: Python<'_>, real: c_double, imag: c_double) -> Bound<'_, PyComplex> { use crate::ffi_ptr_ext::FfiPtrExt; unsafe { ffi::PyComplex_FromDoubles(real, imag) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyComplex::from_doubles`]. #[deprecated(since = "0.23.0", note = "renamed to `PyComplex::from_doubles`")] #[inline] pub fn from_doubles_bound( py: Python<'_>, real: c_double, imag: c_double, ) -> Bound<'_, PyComplex> { Self::from_doubles(py, real, imag) } } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] mod not_limited_impls { use crate::Borrowed; use super::*; use std::ops::{Add, Div, Mul, Neg, Sub}; macro_rules! bin_ops { ($trait:ident, $fn:ident, $op:tt) => { impl<'py> $trait for Borrowed<'_, 'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn $fn(self, other: Self) -> Self::Output { PyAnyMethods::$fn(self.as_any(), other) .downcast_into().expect( concat!("Complex method ", stringify!($fn), " failed.") ) } } impl<'py> $trait for &Bound<'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn $fn(self, other: &Bound<'py, PyComplex>) -> Bound<'py, PyComplex> { self.as_borrowed() $op other.as_borrowed() } } impl<'py> $trait<Bound<'py, PyComplex>> for &Bound<'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn $fn(self, other: Bound<'py, PyComplex>) -> Bound<'py, PyComplex> { self.as_borrowed() $op other.as_borrowed() } } impl<'py> $trait for Bound<'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn $fn(self, other: Bound<'py, PyComplex>) -> Bound<'py, PyComplex> { self.as_borrowed() $op other.as_borrowed() } } impl<'py> $trait<&Self> for Bound<'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn $fn(self, other: &Bound<'py, PyComplex>) -> Bound<'py, PyComplex> { self.as_borrowed() $op other.as_borrowed() } } }; } bin_ops!(Add, add, +); bin_ops!(Sub, sub, -); bin_ops!(Mul, mul, *); bin_ops!(Div, div, /); impl<'py> Neg for Borrowed<'_, 'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn neg(self) -> Self::Output { PyAnyMethods::neg(self.as_any()) .downcast_into() .expect("Complex method __neg__ failed.") } } impl<'py> Neg for &Bound<'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn neg(self) -> Bound<'py, PyComplex> { -self.as_borrowed() } } impl<'py> Neg for Bound<'py, PyComplex> { type Output = Bound<'py, PyComplex>; fn neg(self) -> Bound<'py, PyComplex> { -self.as_borrowed() } } #[cfg(test)] mod tests { use super::PyComplex; use crate::{types::complex::PyComplexMethods, Python}; use assert_approx_eq::assert_approx_eq; #[test] fn test_add() { Python::with_gil(|py| { let l = PyComplex::from_doubles(py, 3.0, 1.2); let r = PyComplex::from_doubles(py, 1.0, 2.6); let res = l + r; assert_approx_eq!(res.real(), 4.0); assert_approx_eq!(res.imag(), 3.8); }); } #[test] fn test_sub() { Python::with_gil(|py| { let l = PyComplex::from_doubles(py, 3.0, 1.2); let r = PyComplex::from_doubles(py, 1.0, 2.6); let res = l - r; assert_approx_eq!(res.real(), 2.0); assert_approx_eq!(res.imag(), -1.4); }); } #[test] fn test_mul() { Python::with_gil(|py| { let l = PyComplex::from_doubles(py, 3.0, 1.2); let r = PyComplex::from_doubles(py, 1.0, 2.6); let res = l * r; assert_approx_eq!(res.real(), -0.12); assert_approx_eq!(res.imag(), 9.0); }); } #[test] fn test_div() { Python::with_gil(|py| { let l = PyComplex::from_doubles(py, 3.0, 1.2); let r = PyComplex::from_doubles(py, 1.0, 2.6); let res = l / r; assert_approx_eq!(res.real(), 0.788_659_793_814_432_9); assert_approx_eq!(res.imag(), -0.850_515_463_917_525_7); }); } #[test] fn test_neg() { Python::with_gil(|py| { let val = PyComplex::from_doubles(py, 3.0, 1.2); let res = -val; assert_approx_eq!(res.real(), -3.0); assert_approx_eq!(res.imag(), -1.2); }); } #[test] fn test_abs() { Python::with_gil(|py| { let val = PyComplex::from_doubles(py, 3.0, 1.2); assert_approx_eq!(val.abs(), 3.231_098_884_280_702_2); }); } #[test] fn test_pow() { Python::with_gil(|py| { let l = PyComplex::from_doubles(py, 3.0, 1.2); let r = PyComplex::from_doubles(py, 1.2, 2.6); let val = l.pow(&r); assert_approx_eq!(val.real(), -1.419_309_997_016_603_7); assert_approx_eq!(val.imag(), -0.541_297_466_033_544_6); }); } } } /// Implementation of functionality for [`PyComplex`]. /// /// These methods are defined for the `Bound<'py, PyComplex>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyComplex")] pub trait PyComplexMethods<'py>: crate::sealed::Sealed { /// Returns the real part of the complex number. fn real(&self) -> c_double; /// Returns the imaginary part of the complex number. fn imag(&self) -> c_double; /// Returns `|self|`. #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] fn abs(&self) -> c_double; /// Returns `self` raised to the power of `other`. #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] fn pow(&self, other: &Bound<'py, PyComplex>) -> Bound<'py, PyComplex>; } impl<'py> PyComplexMethods<'py> for Bound<'py, PyComplex> { fn real(&self) -> c_double { unsafe { ffi::PyComplex_RealAsDouble(self.as_ptr()) } } fn imag(&self) -> c_double { unsafe { ffi::PyComplex_ImagAsDouble(self.as_ptr()) } } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] fn abs(&self) -> c_double { PyAnyMethods::abs(self.as_any()) .downcast_into() .expect("Complex method __abs__ failed.") .extract() .expect("Failed to extract to c double.") } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] fn pow(&self, other: &Bound<'py, PyComplex>) -> Bound<'py, PyComplex> { Python::with_gil(|py| { PyAnyMethods::pow(self.as_any(), other, py.None()) .downcast_into() .expect("Complex method __pow__ failed.") }) } } #[cfg(test)] mod tests { use super::PyComplex; use crate::{types::complex::PyComplexMethods, Python}; use assert_approx_eq::assert_approx_eq; #[test] fn test_from_double() { use assert_approx_eq::assert_approx_eq; Python::with_gil(|py| { let complex = PyComplex::from_doubles(py, 3.0, 1.2); assert_approx_eq!(complex.real(), 3.0); assert_approx_eq!(complex.imag(), 1.2); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/list.rs
use std::iter::FusedIterator; use crate::err::{self, PyResult}; use crate::ffi::{self, Py_ssize_t}; use crate::ffi_ptr_ext::FfiPtrExt; use crate::internal_tricks::get_ssize_index; use crate::types::{PySequence, PyTuple}; use crate::{Borrowed, Bound, BoundObject, IntoPyObject, PyAny, PyErr, PyObject, Python}; use crate::types::any::PyAnyMethods; use crate::types::sequence::PySequenceMethods; /// Represents a Python `list`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyList>`][crate::Py] or [`Bound<'py, PyList>`][Bound]. /// /// For APIs available on `list` objects, see the [`PyListMethods`] trait which is implemented for /// [`Bound<'py, PyDict>`][Bound]. #[repr(transparent)] pub struct PyList(PyAny); pyobject_native_type_core!(PyList, pyobject_native_static_type_object!(ffi::PyList_Type), #checkfunction=ffi::PyList_Check); #[inline] #[track_caller] pub(crate) fn new_from_iter( py: Python<'_>, elements: impl ExactSizeIterator<Item = PyObject>, ) -> Bound<'_, PyList> { try_new_from_iter(py, elements.map(|e| e.into_bound(py)).map(Ok)).unwrap() } #[inline] #[track_caller] pub(crate) fn try_new_from_iter<'py>( py: Python<'py>, mut elements: impl ExactSizeIterator<Item = PyResult<Bound<'py, PyAny>>>, ) -> PyResult<Bound<'py, PyList>> { unsafe { // PyList_New checks for overflow but has a bad error message, so we check ourselves let len: Py_ssize_t = elements .len() .try_into() .expect("out of range integral type conversion attempted on `elements.len()`"); let ptr = ffi::PyList_New(len); // We create the `Bound` pointer here for two reasons: // - panics if the ptr is null // - its Drop cleans up the list if user code or the asserts panic. let list = ptr.assume_owned(py).downcast_into_unchecked(); let count = (&mut elements) .take(len as usize) .try_fold(0, |count, item| { #[cfg(not(Py_LIMITED_API))] ffi::PyList_SET_ITEM(ptr, count, item?.into_ptr()); #[cfg(Py_LIMITED_API)] ffi::PyList_SetItem(ptr, count, item?.into_ptr()); Ok::<_, PyErr>(count + 1) })?; assert!(elements.next().is_none(), "Attempted to create PyList but `elements` was larger than reported by its `ExactSizeIterator` implementation."); assert_eq!(len, count, "Attempted to create PyList but `elements` was smaller than reported by its `ExactSizeIterator` implementation."); Ok(list) } } impl PyList { /// Constructs a new list with the given elements. /// /// If you want to create a [`PyList`] with elements of different or unknown types, or from an /// iterable that doesn't implement [`ExactSizeIterator`], use [`PyListMethods::append`]. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyList; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let elements: Vec<i32> = vec![0, 1, 2, 3, 4, 5]; /// let list = PyList::new(py, elements)?; /// assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5]"); /// # Ok(()) /// }) /// # } /// ``` /// /// # Panics /// /// This function will panic if `element`'s [`ExactSizeIterator`] implementation is incorrect. /// All standard library structures implement this trait correctly, if they do, so calling this /// function with (for example) [`Vec`]`<T>` or `&[T]` will always succeed. #[track_caller] pub fn new<'py, T, U>( py: Python<'py>, elements: impl IntoIterator<Item = T, IntoIter = U>, ) -> PyResult<Bound<'py, PyList>> where T: IntoPyObject<'py>, U: ExactSizeIterator<Item = T>, { let iter = elements.into_iter().map(|e| { e.into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::into_bound) .map_err(Into::into) }); try_new_from_iter(py, iter) } /// Deprecated name for [`PyList::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyList::new`")] #[allow(deprecated)] #[inline] #[track_caller] pub fn new_bound<T, U>( py: Python<'_>, elements: impl IntoIterator<Item = T, IntoIter = U>, ) -> Bound<'_, PyList> where T: crate::ToPyObject, U: ExactSizeIterator<Item = T>, { Self::new(py, elements.into_iter().map(|e| e.to_object(py))).unwrap() } /// Constructs a new empty list. pub fn empty(py: Python<'_>) -> Bound<'_, PyList> { unsafe { ffi::PyList_New(0) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyList::empty`]. #[deprecated(since = "0.23.0", note = "renamed to `PyList::empty`")] #[inline] pub fn empty_bound(py: Python<'_>) -> Bound<'_, PyList> { Self::empty(py) } } /// Implementation of functionality for [`PyList`]. /// /// These methods are defined for the `Bound<'py, PyList>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyList")] pub trait PyListMethods<'py>: crate::sealed::Sealed { /// Returns the length of the list. fn len(&self) -> usize; /// Checks if the list is empty. fn is_empty(&self) -> bool; /// Returns `self` cast as a `PySequence`. fn as_sequence(&self) -> &Bound<'py, PySequence>; /// Returns `self` cast as a `PySequence`. fn into_sequence(self) -> Bound<'py, PySequence>; /// Gets the list item at the specified index. /// # Example /// ``` /// use pyo3::{prelude::*, types::PyList}; /// Python::with_gil(|py| { /// let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); /// let obj = list.get_item(0); /// assert_eq!(obj.unwrap().extract::<i32>().unwrap(), 2); /// }); /// ``` fn get_item(&self, index: usize) -> PyResult<Bound<'py, PyAny>>; /// Gets the list item at the specified index. Undefined behavior on bad index. Use with caution. /// /// # Safety /// /// Caller must verify that the index is within the bounds of the list. #[cfg(not(any(Py_LIMITED_API, Py_GIL_DISABLED)))] unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny>; /// Takes the slice `self[low:high]` and returns it as a new list. /// /// Indices must be nonnegative, and out-of-range indices are clipped to /// `self.len()`. fn get_slice(&self, low: usize, high: usize) -> Bound<'py, PyList>; /// Sets the item at the specified index. /// /// Raises `IndexError` if the index is out of range. fn set_item<I>(&self, index: usize, item: I) -> PyResult<()> where I: IntoPyObject<'py>; /// Deletes the `index`th element of self. /// /// This is equivalent to the Python statement `del self[i]`. fn del_item(&self, index: usize) -> PyResult<()>; /// Assigns the sequence `seq` to the slice of `self` from `low` to `high`. /// /// This is equivalent to the Python statement `self[low:high] = v`. fn set_slice(&self, low: usize, high: usize, seq: &Bound<'_, PyAny>) -> PyResult<()>; /// Deletes the slice from `low` to `high` from `self`. /// /// This is equivalent to the Python statement `del self[low:high]`. fn del_slice(&self, low: usize, high: usize) -> PyResult<()>; /// Appends an item to the list. fn append<I>(&self, item: I) -> PyResult<()> where I: IntoPyObject<'py>; /// Inserts an item at the specified index. /// /// If `index >= self.len()`, inserts at the end. fn insert<I>(&self, index: usize, item: I) -> PyResult<()> where I: IntoPyObject<'py>; /// Determines if self contains `value`. /// /// This is equivalent to the Python expression `value in self`. fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>; /// Returns the first index `i` for which `self[i] == value`. /// /// This is equivalent to the Python expression `self.index(value)`. fn index<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>; /// Returns an iterator over this list's items. fn iter(&self) -> BoundListIterator<'py>; /// Sorts the list in-place. Equivalent to the Python expression `l.sort()`. fn sort(&self) -> PyResult<()>; /// Reverses the list in-place. Equivalent to the Python expression `l.reverse()`. fn reverse(&self) -> PyResult<()>; /// Return a new tuple containing the contents of the list; equivalent to the Python expression `tuple(list)`. /// /// This method is equivalent to `self.as_sequence().to_tuple()` and faster than `PyTuple::new(py, this_list)`. fn to_tuple(&self) -> Bound<'py, PyTuple>; } impl<'py> PyListMethods<'py> for Bound<'py, PyList> { /// Returns the length of the list. fn len(&self) -> usize { unsafe { #[cfg(not(Py_LIMITED_API))] let size = ffi::PyList_GET_SIZE(self.as_ptr()); #[cfg(Py_LIMITED_API)] let size = ffi::PyList_Size(self.as_ptr()); // non-negative Py_ssize_t should always fit into Rust usize size as usize } } /// Checks if the list is empty. fn is_empty(&self) -> bool { self.len() == 0 } /// Returns `self` cast as a `PySequence`. fn as_sequence(&self) -> &Bound<'py, PySequence> { unsafe { self.downcast_unchecked() } } /// Returns `self` cast as a `PySequence`. fn into_sequence(self) -> Bound<'py, PySequence> { unsafe { self.into_any().downcast_into_unchecked() } } /// Gets the list item at the specified index. /// # Example /// ``` /// use pyo3::{prelude::*, types::PyList}; /// Python::with_gil(|py| { /// let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); /// let obj = list.get_item(0); /// assert_eq!(obj.unwrap().extract::<i32>().unwrap(), 2); /// }); /// ``` fn get_item(&self, index: usize) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::compat::PyList_GetItemRef(self.as_ptr(), index as Py_ssize_t) .assume_owned_or_err(self.py()) } } /// Gets the list item at the specified index. Undefined behavior on bad index. Use with caution. /// /// # Safety /// /// Caller must verify that the index is within the bounds of the list. #[cfg(not(any(Py_LIMITED_API, Py_GIL_DISABLED)))] unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny> { // PyList_GET_ITEM return borrowed ptr; must make owned for safety (see #890). ffi::PyList_GET_ITEM(self.as_ptr(), index as Py_ssize_t) .assume_borrowed(self.py()) .to_owned() } /// Takes the slice `self[low:high]` and returns it as a new list. /// /// Indices must be nonnegative, and out-of-range indices are clipped to /// `self.len()`. fn get_slice(&self, low: usize, high: usize) -> Bound<'py, PyList> { unsafe { ffi::PyList_GetSlice(self.as_ptr(), get_ssize_index(low), get_ssize_index(high)) .assume_owned(self.py()) .downcast_into_unchecked() } } /// Sets the item at the specified index. /// /// Raises `IndexError` if the index is out of range. fn set_item<I>(&self, index: usize, item: I) -> PyResult<()> where I: IntoPyObject<'py>, { fn inner(list: &Bound<'_, PyList>, index: usize, item: Bound<'_, PyAny>) -> PyResult<()> { err::error_on_minusone(list.py(), unsafe { ffi::PyList_SetItem(list.as_ptr(), get_ssize_index(index), item.into_ptr()) }) } let py = self.py(); inner( self, index, item.into_pyobject(py) .map_err(Into::into)? .into_any() .into_bound(), ) } /// Deletes the `index`th element of self. /// /// This is equivalent to the Python statement `del self[i]`. #[inline] fn del_item(&self, index: usize) -> PyResult<()> { self.as_sequence().del_item(index) } /// Assigns the sequence `seq` to the slice of `self` from `low` to `high`. /// /// This is equivalent to the Python statement `self[low:high] = v`. #[inline] fn set_slice(&self, low: usize, high: usize, seq: &Bound<'_, PyAny>) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PyList_SetSlice( self.as_ptr(), get_ssize_index(low), get_ssize_index(high), seq.as_ptr(), ) }) } /// Deletes the slice from `low` to `high` from `self`. /// /// This is equivalent to the Python statement `del self[low:high]`. #[inline] fn del_slice(&self, low: usize, high: usize) -> PyResult<()> { self.as_sequence().del_slice(low, high) } /// Appends an item to the list. fn append<I>(&self, item: I) -> PyResult<()> where I: IntoPyObject<'py>, { fn inner(list: &Bound<'_, PyList>, item: Borrowed<'_, '_, PyAny>) -> PyResult<()> { err::error_on_minusone(list.py(), unsafe { ffi::PyList_Append(list.as_ptr(), item.as_ptr()) }) } let py = self.py(); inner( self, item.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } /// Inserts an item at the specified index. /// /// If `index >= self.len()`, inserts at the end. fn insert<I>(&self, index: usize, item: I) -> PyResult<()> where I: IntoPyObject<'py>, { fn inner( list: &Bound<'_, PyList>, index: usize, item: Borrowed<'_, '_, PyAny>, ) -> PyResult<()> { err::error_on_minusone(list.py(), unsafe { ffi::PyList_Insert(list.as_ptr(), get_ssize_index(index), item.as_ptr()) }) } let py = self.py(); inner( self, index, item.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } /// Determines if self contains `value`. /// /// This is equivalent to the Python expression `value in self`. #[inline] fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>, { self.as_sequence().contains(value) } /// Returns the first index `i` for which `self[i] == value`. /// /// This is equivalent to the Python expression `self.index(value)`. #[inline] fn index<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>, { self.as_sequence().index(value) } /// Returns an iterator over this list's items. fn iter(&self) -> BoundListIterator<'py> { BoundListIterator::new(self.clone()) } /// Sorts the list in-place. Equivalent to the Python expression `l.sort()`. fn sort(&self) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PyList_Sort(self.as_ptr()) }) } /// Reverses the list in-place. Equivalent to the Python expression `l.reverse()`. fn reverse(&self) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PyList_Reverse(self.as_ptr()) }) } /// Return a new tuple containing the contents of the list; equivalent to the Python expression `tuple(list)`. /// /// This method is equivalent to `self.as_sequence().to_tuple()` and faster than `PyTuple::new(py, this_list)`. fn to_tuple(&self) -> Bound<'py, PyTuple> { unsafe { ffi::PyList_AsTuple(self.as_ptr()) .assume_owned(self.py()) .downcast_into_unchecked() } } } /// Used by `PyList::iter()`. pub struct BoundListIterator<'py> { list: Bound<'py, PyList>, index: usize, length: usize, } impl<'py> BoundListIterator<'py> { fn new(list: Bound<'py, PyList>) -> Self { let length: usize = list.len(); BoundListIterator { list, index: 0, length, } } unsafe fn get_item(&self, index: usize) -> Bound<'py, PyAny> { #[cfg(any(Py_LIMITED_API, PyPy, Py_GIL_DISABLED))] let item = self.list.get_item(index).expect("list.get failed"); #[cfg(not(any(Py_LIMITED_API, PyPy, Py_GIL_DISABLED)))] let item = self.list.get_item_unchecked(index); item } } impl<'py> Iterator for BoundListIterator<'py> { type Item = Bound<'py, PyAny>; #[inline] fn next(&mut self) -> Option<Self::Item> { let length = self.length.min(self.list.len()); if self.index < length { let item = unsafe { self.get_item(self.index) }; self.index += 1; Some(item) } else { None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } } impl DoubleEndedIterator for BoundListIterator<'_> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { let length = self.length.min(self.list.len()); if self.index < length { let item = unsafe { self.get_item(length - 1) }; self.length = length - 1; Some(item) } else { None } } } impl ExactSizeIterator for BoundListIterator<'_> { fn len(&self) -> usize { self.length.saturating_sub(self.index) } } impl FusedIterator for BoundListIterator<'_> {} impl<'py> IntoIterator for Bound<'py, PyList> { type Item = Bound<'py, PyAny>; type IntoIter = BoundListIterator<'py>; fn into_iter(self) -> Self::IntoIter { BoundListIterator::new(self) } } impl<'py> IntoIterator for &Bound<'py, PyList> { type Item = Bound<'py, PyAny>; type IntoIter = BoundListIterator<'py>; fn into_iter(self) -> Self::IntoIter { self.iter() } } #[cfg(test)] mod tests { use crate::types::any::PyAnyMethods; use crate::types::list::PyListMethods; use crate::types::sequence::PySequenceMethods; use crate::types::{PyList, PyTuple}; use crate::{ffi, IntoPyObject, Python}; #[test] fn test_new() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_len() { Python::with_gil(|py| { let list = PyList::new(py, [1, 2, 3, 4]).unwrap(); assert_eq!(4, list.len()); }); } #[test] fn test_get_item() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_get_slice() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); let slice = list.get_slice(1, 3); assert_eq!(2, slice.len()); let slice = list.get_slice(1, 7); assert_eq!(3, slice.len()); }); } #[test] fn test_set_item() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); let val = 42i32.into_pyobject(py).unwrap(); let val2 = 42i32.into_pyobject(py).unwrap(); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); list.set_item(0, val).unwrap(); assert_eq!(42, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.set_item(10, val2).is_err()); }); } #[test] fn test_set_item_refcnt() { Python::with_gil(|py| { let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap(); let cnt; { let v = vec![2]; let ob = v.into_pyobject(py).unwrap(); let list = ob.downcast::<PyList>().unwrap(); cnt = obj.get_refcnt(); list.set_item(0, &obj).unwrap(); } assert_eq!(cnt, obj.get_refcnt()); }); } #[test] fn test_insert() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); let val = 42i32.into_pyobject(py).unwrap(); let val2 = 43i32.into_pyobject(py).unwrap(); assert_eq!(4, list.len()); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); list.insert(0, val).unwrap(); list.insert(1000, val2).unwrap(); assert_eq!(6, list.len()); assert_eq!(42, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(2, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(43, list.get_item(5).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_insert_refcnt() { Python::with_gil(|py| { let cnt; let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap(); { let list = PyList::empty(py); cnt = obj.get_refcnt(); list.insert(0, &obj).unwrap(); } assert_eq!(cnt, obj.get_refcnt()); }); } #[test] fn test_append() { Python::with_gil(|py| { let list = PyList::new(py, [2]).unwrap(); list.append(3).unwrap(); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_append_refcnt() { Python::with_gil(|py| { let cnt; let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap(); { let list = PyList::empty(py); cnt = obj.get_refcnt(); list.append(&obj).unwrap(); } assert_eq!(cnt, obj.get_refcnt()); }); } #[test] fn test_iter() { Python::with_gil(|py| { let v = vec![2, 3, 5, 7]; let list = PyList::new(py, &v).unwrap(); let mut idx = 0; for el in list { assert_eq!(v[idx], el.extract::<i32>().unwrap()); idx += 1; } assert_eq!(idx, v.len()); }); } #[test] fn test_iter_size_hint() { Python::with_gil(|py| { let v = vec![2, 3, 5, 7]; let ob = (&v).into_pyobject(py).unwrap(); let list = ob.downcast::<PyList>().unwrap(); let mut iter = list.iter(); assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); iter.next(); assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); // Exhaust iterator. for _ in &mut iter {} assert_eq!(iter.size_hint(), (0, Some(0))); }); } #[test] fn test_iter_rev() { Python::with_gil(|py| { let v = vec![2, 3, 5, 7]; let ob = v.into_pyobject(py).unwrap(); let list = ob.downcast::<PyList>().unwrap(); let mut iter = list.iter().rev(); assert_eq!(iter.size_hint(), (4, Some(4))); assert_eq!(iter.next().unwrap().extract::<i32>().unwrap(), 7); assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(iter.next().unwrap().extract::<i32>().unwrap(), 5); assert_eq!(iter.size_hint(), (2, Some(2))); assert_eq!(iter.next().unwrap().extract::<i32>().unwrap(), 3); assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(iter.next().unwrap().extract::<i32>().unwrap(), 2); assert_eq!(iter.size_hint(), (0, Some(0))); assert!(iter.next().is_none()); assert!(iter.next().is_none()); }); } #[test] fn test_into_iter() { Python::with_gil(|py| { let list = PyList::new(py, [1, 2, 3, 4]).unwrap(); for (i, item) in list.iter().enumerate() { assert_eq!((i + 1) as i32, item.extract::<i32>().unwrap()); } }); } #[test] fn test_into_iter_bound() { use crate::types::any::PyAnyMethods; Python::with_gil(|py| { let list = PyList::new(py, [1, 2, 3, 4]).unwrap(); let mut items = vec![]; for item in &list { items.push(item.extract::<i32>().unwrap()); } assert_eq!(items, vec![1, 2, 3, 4]); }); } #[test] fn test_as_sequence() { Python::with_gil(|py| { let list = PyList::new(py, [1, 2, 3, 4]).unwrap(); assert_eq!(list.as_sequence().len().unwrap(), 4); assert_eq!( list.as_sequence() .get_item(1) .unwrap() .extract::<i32>() .unwrap(), 2 ); }); } #[test] fn test_into_sequence() { Python::with_gil(|py| { let list = PyList::new(py, [1, 2, 3, 4]).unwrap(); let sequence = list.into_sequence(); assert_eq!(sequence.len().unwrap(), 4); assert_eq!(sequence.get_item(1).unwrap().extract::<i32>().unwrap(), 2); }); } #[test] fn test_extract() { Python::with_gil(|py| { let v = vec![2, 3, 5, 7]; let list = PyList::new(py, &v).unwrap(); let v2 = list.as_ref().extract::<Vec<i32>>().unwrap(); assert_eq!(v, v2); }); } #[test] fn test_sort() { Python::with_gil(|py| { let v = vec![7, 3, 2, 5]; let list = PyList::new(py, &v).unwrap(); assert_eq!(7, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(2, list.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(5, list.get_item(3).unwrap().extract::<i32>().unwrap()); list.sort().unwrap(); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_reverse() { Python::with_gil(|py| { let v = vec![2, 3, 5, 7]; let list = PyList::new(py, &v).unwrap(); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(5, list.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(7, list.get_item(3).unwrap().extract::<i32>().unwrap()); list.reverse().unwrap(); assert_eq!(7, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(5, list.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(3, list.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(2, list.get_item(3).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_array_into_pyobject() { Python::with_gil(|py| { let array = [1, 2].into_pyobject(py).unwrap(); let list = array.downcast::<PyList>().unwrap(); assert_eq!(1, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(2, list.get_item(1).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_list_get_item_invalid_index() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); let obj = list.get_item(5); assert!(obj.is_err()); assert_eq!( obj.unwrap_err().to_string(), "IndexError: list index out of range" ); }); } #[test] fn test_list_get_item_sanity() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); let obj = list.get_item(0); assert_eq!(obj.unwrap().extract::<i32>().unwrap(), 2); }); } #[cfg(not(any(Py_LIMITED_API, PyPy, Py_GIL_DISABLED)))] #[test] fn test_list_get_item_unchecked_sanity() { Python::with_gil(|py| { let list = PyList::new(py, [2, 3, 5, 7]).unwrap(); let obj = unsafe { list.get_item_unchecked(0) }; assert_eq!(obj.extract::<i32>().unwrap(), 2); }); } #[test] fn test_list_del_item() { Python::with_gil(|py| { let list = PyList::new(py, [1, 1, 2, 3, 5, 8]).unwrap(); assert!(list.del_item(10).is_err()); assert_eq!(1, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.del_item(0).is_ok()); assert_eq!(1, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.del_item(0).is_ok()); assert_eq!(2, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.del_item(0).is_ok()); assert_eq!(3, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.del_item(0).is_ok()); assert_eq!(5, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.del_item(0).is_ok()); assert_eq!(8, list.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(list.del_item(0).is_ok()); assert_eq!(0, list.len()); assert!(list.del_item(0).is_err()); }); } #[test] fn test_list_set_slice() { Python::with_gil(|py| { let list = PyList::new(py, [1, 1, 2, 3, 5, 8]).unwrap(); let ins = PyList::new(py, [7, 4]).unwrap(); list.set_slice(1, 4, &ins).unwrap(); assert_eq!([1, 7, 4, 5, 8], list.extract::<[i32; 5]>().unwrap()); list.set_slice(3, 100, &PyList::empty(py)).unwrap(); assert_eq!([1, 7, 4], list.extract::<[i32; 3]>().unwrap()); }); } #[test] fn test_list_del_slice() { Python::with_gil(|py| { let list = PyList::new(py, [1, 1, 2, 3, 5, 8]).unwrap(); list.del_slice(1, 4).unwrap(); assert_eq!([1, 5, 8], list.extract::<[i32; 3]>().unwrap()); list.del_slice(1, 100).unwrap(); assert_eq!([1], list.extract::<[i32; 1]>().unwrap()); }); } #[test] fn test_list_contains() { Python::with_gil(|py| { let list = PyList::new(py, [1, 1, 2, 3, 5, 8]).unwrap(); assert_eq!(6, list.len()); let bad_needle = 7i32.into_pyobject(py).unwrap(); assert!(!list.contains(&bad_needle).unwrap()); let good_needle = 8i32.into_pyobject(py).unwrap(); assert!(list.contains(&good_needle).unwrap()); let type_coerced_needle = 8f32.into_pyobject(py).unwrap(); assert!(list.contains(&type_coerced_needle).unwrap()); }); } #[test] fn test_list_index() { Python::with_gil(|py| { let list = PyList::new(py, [1, 1, 2, 3, 5, 8]).unwrap(); assert_eq!(0, list.index(1i32).unwrap()); assert_eq!(2, list.index(2i32).unwrap()); assert_eq!(3, list.index(3i32).unwrap()); assert_eq!(4, list.index(5i32).unwrap()); assert_eq!(5, list.index(8i32).unwrap()); assert!(list.index(42i32).is_err()); }); } use std::ops::Range; // An iterator that lies about its `ExactSizeIterator` implementation. // See https://github.com/PyO3/pyo3/issues/2118 struct FaultyIter(Range<usize>, usize); impl Iterator for FaultyIter { type Item = usize; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } impl ExactSizeIterator for FaultyIter { fn len(&self) -> usize { self.1 } } #[test] #[should_panic( expected = "Attempted to create PyList but `elements` was larger than reported by its `ExactSizeIterator` implementation." )] fn too_long_iterator() { Python::with_gil(|py| { let iter = FaultyIter(0..usize::MAX, 73); let _list = PyList::new(py, iter).unwrap(); }) } #[test] #[should_panic( expected = "Attempted to create PyList but `elements` was smaller than reported by its `ExactSizeIterator` implementation." )] fn too_short_iterator() { Python::with_gil(|py| { let iter = FaultyIter(0..35, 73); let _list = PyList::new(py, iter).unwrap(); }) } #[test] #[should_panic( expected = "out of range integral type conversion attempted on `elements.len()`" )] fn overflowing_size() { Python::with_gil(|py| { let iter = FaultyIter(0..0, usize::MAX); let _list = PyList::new(py, iter).unwrap(); }) } #[test] fn bad_intopyobject_doesnt_cause_leaks() { use crate::types::PyInt; use std::convert::Infallible; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; static NEEDS_DESTRUCTING_COUNT: AtomicUsize = AtomicUsize::new(0); struct Bad(usize); impl Drop for Bad { fn drop(&mut self) { NEEDS_DESTRUCTING_COUNT.fetch_sub(1, SeqCst); } } impl<'py> IntoPyObject<'py> for Bad { type Target = PyInt; type Output = crate::Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { // This panic should not lead to a memory leak assert_ne!(self.0, 42); self.0.into_pyobject(py) } } struct FaultyIter(Range<usize>, usize); impl Iterator for FaultyIter { type Item = Bad; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|i| { NEEDS_DESTRUCTING_COUNT.fetch_add(1, SeqCst); Bad(i) }) } } impl ExactSizeIterator for FaultyIter { fn len(&self) -> usize { self.1 } } Python::with_gil(|py| { std::panic::catch_unwind(|| { let iter = FaultyIter(0..50, 50); let _list = PyList::new(py, iter).unwrap(); }) .unwrap_err(); }); assert_eq!( NEEDS_DESTRUCTING_COUNT.load(SeqCst), 0, "Some destructors did not run" ); } #[test] fn test_list_to_tuple() { Python::with_gil(|py| { let list = PyList::new(py, vec![1, 2, 3]).unwrap(); let tuple = list.to_tuple(); let tuple_expected = PyTuple::new(py, vec![1, 2, 3]).unwrap(); assert!(tuple.eq(tuple_expected).unwrap()); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/sequence.rs
use crate::err::{self, DowncastError, PyErr, PyResult}; use crate::exceptions::PyTypeError; use crate::ffi_ptr_ext::FfiPtrExt; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; use crate::instance::Bound; use crate::internal_tricks::get_ssize_index; use crate::py_result_ext::PyResultExt; use crate::sync::GILOnceCell; use crate::type_object::PyTypeInfo; use crate::types::{any::PyAnyMethods, PyAny, PyList, PyString, PyTuple, PyType}; use crate::{ffi, Borrowed, BoundObject, FromPyObject, IntoPyObject, Py, PyTypeCheck, Python}; /// Represents a reference to a Python object supporting the sequence protocol. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PySequence>`][crate::Py] or [`Bound<'py, PySequence>`][Bound]. /// /// For APIs available on sequence objects, see the [`PySequenceMethods`] trait which is implemented for /// [`Bound<'py, PySequence>`][Bound]. #[repr(transparent)] pub struct PySequence(PyAny); pyobject_native_type_named!(PySequence); impl PySequence { /// Register a pyclass as a subclass of `collections.abc.Sequence` (from the Python standard /// library). This is equivalent to `collections.abc.Sequence.register(T)` in Python. /// This registration is required for a pyclass to be downcastable from `PyAny` to `PySequence`. pub fn register<T: PyTypeInfo>(py: Python<'_>) -> PyResult<()> { let ty = T::type_object(py); get_sequence_abc(py)?.call_method1("register", (ty,))?; Ok(()) } } /// Implementation of functionality for [`PySequence`]. /// /// These methods are defined for the `Bound<'py, PySequence>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PySequence")] pub trait PySequenceMethods<'py>: crate::sealed::Sealed { /// Returns the number of objects in sequence. /// /// This is equivalent to the Python expression `len(self)`. fn len(&self) -> PyResult<usize>; /// Returns whether the sequence is empty. fn is_empty(&self) -> PyResult<bool>; /// Returns the concatenation of `self` and `other`. /// /// This is equivalent to the Python expression `self + other`. fn concat(&self, other: &Bound<'_, PySequence>) -> PyResult<Bound<'py, PySequence>>; /// Returns the result of repeating a sequence object `count` times. /// /// This is equivalent to the Python expression `self * count`. fn repeat(&self, count: usize) -> PyResult<Bound<'py, PySequence>>; /// Concatenates `self` and `other`, in place if possible. /// /// This is equivalent to the Python expression `self.__iadd__(other)`. /// /// The Python statement `self += other` is syntactic sugar for `self = /// self.__iadd__(other)`. `__iadd__` should modify and return `self` if /// possible, but create and return a new object if not. fn in_place_concat(&self, other: &Bound<'_, PySequence>) -> PyResult<Bound<'py, PySequence>>; /// Repeats the sequence object `count` times and updates `self`, if possible. /// /// This is equivalent to the Python expression `self.__imul__(other)`. /// /// The Python statement `self *= other` is syntactic sugar for `self = /// self.__imul__(other)`. `__imul__` should modify and return `self` if /// possible, but create and return a new object if not. fn in_place_repeat(&self, count: usize) -> PyResult<Bound<'py, PySequence>>; /// Returns the `index`th element of the Sequence. /// /// This is equivalent to the Python expression `self[index]` without support of negative indices. fn get_item(&self, index: usize) -> PyResult<Bound<'py, PyAny>>; /// Returns the slice of sequence object between `begin` and `end`. /// /// This is equivalent to the Python expression `self[begin:end]`. fn get_slice(&self, begin: usize, end: usize) -> PyResult<Bound<'py, PySequence>>; /// Assigns object `item` to the `i`th element of self. /// /// This is equivalent to the Python statement `self[i] = v`. fn set_item<I>(&self, i: usize, item: I) -> PyResult<()> where I: IntoPyObject<'py>; /// Deletes the `i`th element of self. /// /// This is equivalent to the Python statement `del self[i]`. fn del_item(&self, i: usize) -> PyResult<()>; /// Assigns the sequence `v` to the slice of `self` from `i1` to `i2`. /// /// This is equivalent to the Python statement `self[i1:i2] = v`. fn set_slice(&self, i1: usize, i2: usize, v: &Bound<'_, PyAny>) -> PyResult<()>; /// Deletes the slice from `i1` to `i2` from `self`. /// /// This is equivalent to the Python statement `del self[i1:i2]`. fn del_slice(&self, i1: usize, i2: usize) -> PyResult<()>; /// Returns the number of occurrences of `value` in self, that is, return the /// number of keys for which `self[key] == value`. #[cfg(not(PyPy))] fn count<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>; /// Determines if self contains `value`. /// /// This is equivalent to the Python expression `value in self`. fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>; /// Returns the first index `i` for which `self[i] == value`. /// /// This is equivalent to the Python expression `self.index(value)`. fn index<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>; /// Returns a fresh list based on the Sequence. fn to_list(&self) -> PyResult<Bound<'py, PyList>>; /// Returns a fresh tuple based on the Sequence. fn to_tuple(&self) -> PyResult<Bound<'py, PyTuple>>; } impl<'py> PySequenceMethods<'py> for Bound<'py, PySequence> { #[inline] fn len(&self) -> PyResult<usize> { let v = unsafe { ffi::PySequence_Size(self.as_ptr()) }; crate::err::error_on_minusone(self.py(), v)?; Ok(v as usize) } #[inline] fn is_empty(&self) -> PyResult<bool> { self.len().map(|l| l == 0) } #[inline] fn concat(&self, other: &Bound<'_, PySequence>) -> PyResult<Bound<'py, PySequence>> { unsafe { ffi::PySequence_Concat(self.as_ptr(), other.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn repeat(&self, count: usize) -> PyResult<Bound<'py, PySequence>> { unsafe { ffi::PySequence_Repeat(self.as_ptr(), get_ssize_index(count)) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn in_place_concat(&self, other: &Bound<'_, PySequence>) -> PyResult<Bound<'py, PySequence>> { unsafe { ffi::PySequence_InPlaceConcat(self.as_ptr(), other.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn in_place_repeat(&self, count: usize) -> PyResult<Bound<'py, PySequence>> { unsafe { ffi::PySequence_InPlaceRepeat(self.as_ptr(), get_ssize_index(count)) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn get_item(&self, index: usize) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PySequence_GetItem(self.as_ptr(), get_ssize_index(index)) .assume_owned_or_err(self.py()) } } #[inline] fn get_slice(&self, begin: usize, end: usize) -> PyResult<Bound<'py, PySequence>> { unsafe { ffi::PySequence_GetSlice(self.as_ptr(), get_ssize_index(begin), get_ssize_index(end)) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn set_item<I>(&self, i: usize, item: I) -> PyResult<()> where I: IntoPyObject<'py>, { fn inner( seq: &Bound<'_, PySequence>, i: usize, item: Borrowed<'_, '_, PyAny>, ) -> PyResult<()> { err::error_on_minusone(seq.py(), unsafe { ffi::PySequence_SetItem(seq.as_ptr(), get_ssize_index(i), item.as_ptr()) }) } let py = self.py(); inner( self, i, item.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } #[inline] fn del_item(&self, i: usize) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PySequence_DelItem(self.as_ptr(), get_ssize_index(i)) }) } #[inline] fn set_slice(&self, i1: usize, i2: usize, v: &Bound<'_, PyAny>) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PySequence_SetSlice( self.as_ptr(), get_ssize_index(i1), get_ssize_index(i2), v.as_ptr(), ) }) } #[inline] fn del_slice(&self, i1: usize, i2: usize) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PySequence_DelSlice(self.as_ptr(), get_ssize_index(i1), get_ssize_index(i2)) }) } #[inline] #[cfg(not(PyPy))] fn count<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>, { fn inner(seq: &Bound<'_, PySequence>, value: Borrowed<'_, '_, PyAny>) -> PyResult<usize> { let r = unsafe { ffi::PySequence_Count(seq.as_ptr(), value.as_ptr()) }; crate::err::error_on_minusone(seq.py(), r)?; Ok(r as usize) } let py = self.py(); inner( self, value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } #[inline] fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>, { fn inner(seq: &Bound<'_, PySequence>, value: Borrowed<'_, '_, PyAny>) -> PyResult<bool> { let r = unsafe { ffi::PySequence_Contains(seq.as_ptr(), value.as_ptr()) }; match r { 0 => Ok(false), 1 => Ok(true), _ => Err(PyErr::fetch(seq.py())), } } let py = self.py(); inner( self, value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } #[inline] fn index<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>, { fn inner(seq: &Bound<'_, PySequence>, value: Borrowed<'_, '_, PyAny>) -> PyResult<usize> { let r = unsafe { ffi::PySequence_Index(seq.as_ptr(), value.as_ptr()) }; crate::err::error_on_minusone(seq.py(), r)?; Ok(r as usize) } let py = self.py(); inner( self, value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } #[inline] fn to_list(&self) -> PyResult<Bound<'py, PyList>> { unsafe { ffi::PySequence_List(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn to_tuple(&self) -> PyResult<Bound<'py, PyTuple>> { unsafe { ffi::PySequence_Tuple(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } } impl<'py, T> FromPyObject<'py> for Vec<T> where T: 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 `Vec`")); } extract_sequence(obj) } #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { TypeInfo::sequence_of(T::type_input()) } } fn extract_sequence<'py, T>(obj: &Bound<'py, PyAny>) -> PyResult<Vec<T>> 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 mut v = Vec::with_capacity(seq.len().unwrap_or(0)); for item in seq.try_iter()? { v.push(item?.extract::<T>()?); } Ok(v) } fn get_sequence_abc(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> { static SEQUENCE_ABC: GILOnceCell<Py<PyType>> = GILOnceCell::new(); SEQUENCE_ABC.import(py, "collections.abc", "Sequence") } impl PyTypeCheck for PySequence { const NAME: &'static str = "Sequence"; #[inline] fn type_check(object: &Bound<'_, PyAny>) -> bool { // Using `is_instance` for `collections.abc.Sequence` is slow, so provide // optimized cases for list and tuples as common well-known sequences PyList::is_type_of(object) || PyTuple::is_type_of(object) || get_sequence_abc(object.py()) .and_then(|abc| object.is_instance(abc)) .unwrap_or_else(|err| { err.write_unraisable(object.py(), Some(object)); false }) } } #[cfg(test)] mod tests { use crate::types::{PyAnyMethods, PyList, PySequence, PySequenceMethods, PyTuple}; use crate::{ffi, IntoPyObject, PyObject, Python}; fn get_object() -> PyObject { // Convenience function for getting a single unique object Python::with_gil(|py| { let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap(); obj.into_pyobject(py).unwrap().unbind() }) } #[test] fn test_numbers_are_not_sequences() { Python::with_gil(|py| { let v = 42i32; assert!(v .into_pyobject(py) .unwrap() .downcast::<PySequence>() .is_err()); }); } #[test] fn test_strings_are_sequences() { Python::with_gil(|py| { let v = "London Calling"; assert!(v .into_pyobject(py) .unwrap() .downcast::<PySequence>() .is_ok()); }); } #[test] fn test_strings_cannot_be_extracted_to_vec() { Python::with_gil(|py| { let v = "London Calling"; let ob = v.into_pyobject(py).unwrap(); assert!(ob.extract::<Vec<String>>().is_err()); assert!(ob.extract::<Vec<char>>().is_err()); }); } #[test] fn test_seq_empty() { Python::with_gil(|py| { let v: Vec<i32> = vec![]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!(0, seq.len().unwrap()); let needle = 7i32.into_pyobject(py).unwrap(); assert!(!seq.contains(&needle).unwrap()); }); } #[test] fn test_seq_is_empty() { Python::with_gil(|py| { let list = vec![1].into_pyobject(py).unwrap(); let seq = list.downcast::<PySequence>().unwrap(); assert!(!seq.is_empty().unwrap()); let vec: Vec<u32> = Vec::new(); let empty_list = vec.into_pyobject(py).unwrap(); let empty_seq = empty_list.downcast::<PySequence>().unwrap(); assert!(empty_seq.is_empty().unwrap()); }); } #[test] fn test_seq_contains() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!(6, seq.len().unwrap()); let bad_needle = 7i32.into_pyobject(py).unwrap(); assert!(!seq.contains(&bad_needle).unwrap()); let good_needle = 8i32.into_pyobject(py).unwrap(); assert!(seq.contains(&good_needle).unwrap()); let type_coerced_needle = 8f32.into_pyobject(py).unwrap(); assert!(seq.contains(&type_coerced_needle).unwrap()); }); } #[test] fn test_seq_get_item() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert_eq!(1, seq.get_item(1).unwrap().extract::<i32>().unwrap()); assert_eq!(2, seq.get_item(2).unwrap().extract::<i32>().unwrap()); assert_eq!(3, seq.get_item(3).unwrap().extract::<i32>().unwrap()); assert_eq!(5, seq.get_item(4).unwrap().extract::<i32>().unwrap()); assert_eq!(8, seq.get_item(5).unwrap().extract::<i32>().unwrap()); assert!(seq.get_item(10).is_err()); }); } #[test] fn test_seq_del_item() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert!(seq.del_item(10).is_err()); assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok()); assert_eq!(1, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok()); assert_eq!(2, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok()); assert_eq!(3, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok()); assert_eq!(5, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok()); assert_eq!(8, seq.get_item(0).unwrap().extract::<i32>().unwrap()); assert!(seq.del_item(0).is_ok()); assert_eq!(0, seq.len().unwrap()); assert!(seq.del_item(0).is_err()); }); } #[test] fn test_seq_set_item() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 2]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!(2, seq.get_item(1).unwrap().extract::<i32>().unwrap()); assert!(seq.set_item(1, 10).is_ok()); assert_eq!(10, seq.get_item(1).unwrap().extract::<i32>().unwrap()); }); } #[test] fn test_seq_set_item_refcnt() { let obj = get_object(); Python::with_gil(|py| { let v: Vec<i32> = vec![1, 2]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert!(seq.set_item(1, &obj).is_ok()); assert!(seq.get_item(1).unwrap().as_ptr() == obj.as_ptr()); }); Python::with_gil(move |py| { assert_eq!(1, obj.get_refcnt(py)); }); } #[test] fn test_seq_get_slice() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!( [1, 2, 3], seq.get_slice(1, 4).unwrap().extract::<[i32; 3]>().unwrap() ); assert_eq!( [3, 5, 8], seq.get_slice(3, 100) .unwrap() .extract::<[i32; 3]>() .unwrap() ); }); } #[test] fn test_set_slice() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let w: Vec<i32> = vec![7, 4]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let ins = w.into_pyobject(py).unwrap(); seq.set_slice(1, 4, &ins).unwrap(); assert_eq!([1, 7, 4, 5, 8], seq.extract::<[i32; 5]>().unwrap()); seq.set_slice(3, 100, &PyList::empty(py)).unwrap(); assert_eq!([1, 7, 4], seq.extract::<[i32; 3]>().unwrap()); }); } #[test] fn test_del_slice() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); seq.del_slice(1, 4).unwrap(); assert_eq!([1, 5, 8], seq.extract::<[i32; 3]>().unwrap()); seq.del_slice(1, 100).unwrap(); assert_eq!([1], seq.extract::<[i32; 1]>().unwrap()); }); } #[test] fn test_seq_index() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!(0, seq.index(1i32).unwrap()); assert_eq!(2, seq.index(2i32).unwrap()); assert_eq!(3, seq.index(3i32).unwrap()); assert_eq!(4, seq.index(5i32).unwrap()); assert_eq!(5, seq.index(8i32).unwrap()); assert!(seq.index(42i32).is_err()); }); } #[test] #[cfg(not(any(PyPy, GraalPy)))] fn test_seq_count() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert_eq!(2, seq.count(1i32).unwrap()); assert_eq!(1, seq.count(2i32).unwrap()); assert_eq!(1, seq.count(3i32).unwrap()); assert_eq!(1, seq.count(5i32).unwrap()); assert_eq!(1, seq.count(8i32).unwrap()); assert_eq!(0, seq.count(42i32).unwrap()); }); } #[test] fn test_seq_iter() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = (&v).into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let mut idx = 0; for el in seq.try_iter().unwrap() { assert_eq!(v[idx], el.unwrap().extract::<i32>().unwrap()); idx += 1; } assert_eq!(idx, v.len()); }); } #[test] fn test_seq_strings() { Python::with_gil(|py| { let v = vec!["It", "was", "the", "worst", "of", "times"]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let bad_needle = "blurst".into_pyobject(py).unwrap(); assert!(!seq.contains(bad_needle).unwrap()); let good_needle = "worst".into_pyobject(py).unwrap(); assert!(seq.contains(good_needle).unwrap()); }); } #[test] fn test_seq_concat() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 2, 3]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let concat_seq = seq.concat(seq).unwrap(); assert_eq!(6, concat_seq.len().unwrap()); let concat_v: Vec<i32> = vec![1, 2, 3, 1, 2, 3]; for (el, cc) in concat_seq.try_iter().unwrap().zip(concat_v) { assert_eq!(cc, el.unwrap().extract::<i32>().unwrap()); } }); } #[test] fn test_seq_concat_string() { Python::with_gil(|py| { let v = "string"; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let concat_seq = seq.concat(seq).unwrap(); assert_eq!(12, concat_seq.len().unwrap()); let concat_v = "stringstring".to_owned(); for (el, cc) in seq.try_iter().unwrap().zip(concat_v.chars()) { assert_eq!(cc, el.unwrap().extract::<char>().unwrap()); } }); } #[test] fn test_seq_repeat() { Python::with_gil(|py| { let v = vec!["foo", "bar"]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let repeat_seq = seq.repeat(3).unwrap(); assert_eq!(6, repeat_seq.len().unwrap()); let repeated = ["foo", "bar", "foo", "bar", "foo", "bar"]; for (el, rpt) in repeat_seq.try_iter().unwrap().zip(repeated.iter()) { assert_eq!(*rpt, el.unwrap().extract::<String>().unwrap()); } }); } #[test] fn test_seq_inplace() { Python::with_gil(|py| { let v = vec!["foo", "bar"]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let rep_seq = seq.in_place_repeat(3).unwrap(); assert_eq!(6, seq.len().unwrap()); assert!(seq.is(&rep_seq)); let conc_seq = seq.in_place_concat(seq).unwrap(); assert_eq!(12, seq.len().unwrap()); assert!(seq.is(&conc_seq)); }); } #[test] fn test_list_coercion() { Python::with_gil(|py| { let v = vec!["foo", "bar"]; let ob = (&v).into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert!(seq .to_list() .unwrap() .eq(PyList::new(py, &v).unwrap()) .unwrap()); }); } #[test] fn test_strings_coerce_to_lists() { Python::with_gil(|py| { let v = "foo"; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert!(seq .to_list() .unwrap() .eq(PyList::new(py, ["f", "o", "o"]).unwrap()) .unwrap()); }); } #[test] fn test_tuple_coercion() { Python::with_gil(|py| { let v = ("foo", "bar"); let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert!(seq .to_tuple() .unwrap() .eq(PyTuple::new(py, ["foo", "bar"]).unwrap()) .unwrap()); }); } #[test] fn test_lists_coerce_to_tuples() { Python::with_gil(|py| { let v = vec!["foo", "bar"]; let ob = (&v).into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); assert!(seq .to_tuple() .unwrap() .eq(PyTuple::new(py, &v).unwrap()) .unwrap()); }); } #[test] fn test_extract_tuple_to_vec() { Python::with_gil(|py| { let v: Vec<i32> = py .eval(ffi::c_str!("(1, 2)"), None, None) .unwrap() .extract() .unwrap(); assert!(v == [1, 2]); }); } #[test] fn test_extract_range_to_vec() { Python::with_gil(|py| { let v: Vec<i32> = py .eval(ffi::c_str!("range(1, 5)"), None, None) .unwrap() .extract() .unwrap(); assert!(v == [1, 2, 3, 4]); }); } #[test] fn test_extract_bytearray_to_vec() { Python::with_gil(|py| { let v: Vec<u8> = py .eval(ffi::c_str!("bytearray(b'abc')"), None, None) .unwrap() .extract() .unwrap(); assert!(v == b"abc"); }); } #[test] fn test_seq_downcast_unchecked() { Python::with_gil(|py| { let v = vec!["foo", "bar"]; let ob = v.into_pyobject(py).unwrap(); let seq = ob.downcast::<PySequence>().unwrap(); let type_ptr = seq.as_ref(); let seq_from = unsafe { type_ptr.downcast_unchecked::<PySequence>() }; assert!(seq_from.to_list().is_ok()); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/function.rs
use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::types::capsule::PyCapsuleMethods; use crate::types::module::PyModuleMethods; use crate::{ ffi, impl_::pymethods::{self, PyMethodDef}, types::{PyCapsule, PyDict, PyModule, PyString, PyTuple}, }; use crate::{Bound, Py, PyAny, PyResult, Python}; use std::cell::UnsafeCell; use std::ffi::CStr; /// Represents a builtin Python function object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyCFunction>`][crate::Py] or [`Bound<'py, PyCFunction>`][Bound]. #[repr(transparent)] pub struct PyCFunction(PyAny); pyobject_native_type_core!(PyCFunction, pyobject_native_static_type_object!(ffi::PyCFunction_Type), #checkfunction=ffi::PyCFunction_Check); impl PyCFunction { /// Create a new built-in function with keywords (*args and/or **kwargs). /// /// To create `name` and `doc` static strings on Rust versions older than 1.77 (which added c"" literals), /// use the [`c_str!`](crate::ffi::c_str) macro. pub fn new_with_keywords<'py>( py: Python<'py>, fun: ffi::PyCFunctionWithKeywords, name: &'static CStr, doc: &'static CStr, module: Option<&Bound<'py, PyModule>>, ) -> PyResult<Bound<'py, Self>> { Self::internal_new( py, &PyMethodDef::cfunction_with_keywords(name, fun, doc), module, ) } /// Deprecated name for [`PyCFunction::new_with_keywords`]. #[deprecated(since = "0.23.0", note = "renamed to `PyCFunction::new_with_keywords`")] #[inline] pub fn new_with_keywords_bound<'py>( py: Python<'py>, fun: ffi::PyCFunctionWithKeywords, name: &'static CStr, doc: &'static CStr, module: Option<&Bound<'py, PyModule>>, ) -> PyResult<Bound<'py, Self>> { Self::new_with_keywords(py, fun, name, doc, module) } /// Create a new built-in function which takes no arguments. /// /// To create `name` and `doc` static strings on Rust versions older than 1.77 (which added c"" literals), /// use the [`c_str!`](crate::ffi::c_str) macro. pub fn new<'py>( py: Python<'py>, fun: ffi::PyCFunction, name: &'static CStr, doc: &'static CStr, module: Option<&Bound<'py, PyModule>>, ) -> PyResult<Bound<'py, Self>> { Self::internal_new(py, &PyMethodDef::noargs(name, fun, doc), module) } /// Deprecated name for [`PyCFunction::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyCFunction::new`")] #[inline] pub fn new_bound<'py>( py: Python<'py>, fun: ffi::PyCFunction, name: &'static CStr, doc: &'static CStr, module: Option<&Bound<'py, PyModule>>, ) -> PyResult<Bound<'py, Self>> { Self::new(py, fun, name, doc, module) } /// Create a new function from a closure. /// /// # Examples /// /// ``` /// # use pyo3::prelude::*; /// # use pyo3::{py_run, types::{PyCFunction, PyDict, PyTuple}}; /// /// Python::with_gil(|py| { /// let add_one = |args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>| -> PyResult<_> { /// let i = args.extract::<(i64,)>()?.0; /// Ok(i+1) /// }; /// let add_one = PyCFunction::new_closure(py, None, None, add_one).unwrap(); /// py_run!(py, add_one, "assert add_one(42) == 43"); /// }); /// ``` pub fn new_closure<'py, F, R>( py: Python<'py>, name: Option<&'static CStr>, doc: Option<&'static CStr>, closure: F, ) -> PyResult<Bound<'py, Self>> where F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> R + Send + 'static, for<'p> R: crate::impl_::callback::IntoPyCallbackOutput<'p, *mut ffi::PyObject>, { let name = name.unwrap_or(ffi::c_str!("pyo3-closure")); let doc = doc.unwrap_or(ffi::c_str!("")); let method_def = pymethods::PyMethodDef::cfunction_with_keywords(name, run_closure::<F, R>, doc); let def = method_def.as_method_def(); let capsule = PyCapsule::new( py, ClosureDestructor::<F> { closure, def: UnsafeCell::new(def), }, Some(CLOSURE_CAPSULE_NAME.to_owned()), )?; // Safety: just created the capsule with type ClosureDestructor<F> above let data = unsafe { capsule.reference::<ClosureDestructor<F>>() }; unsafe { ffi::PyCFunction_NewEx(data.def.get(), capsule.as_ptr(), std::ptr::null_mut()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyCFunction::new_closure`]. #[deprecated(since = "0.23.0", note = "renamed to `PyCFunction::new_closure`")] #[inline] pub fn new_closure_bound<'py, F, R>( py: Python<'py>, name: Option<&'static CStr>, doc: Option<&'static CStr>, closure: F, ) -> PyResult<Bound<'py, Self>> where F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> R + Send + 'static, for<'p> R: crate::impl_::callback::IntoPyCallbackOutput<'p, *mut ffi::PyObject>, { Self::new_closure(py, name, doc, closure) } #[doc(hidden)] pub fn internal_new<'py>( py: Python<'py>, method_def: &PyMethodDef, module: Option<&Bound<'py, PyModule>>, ) -> PyResult<Bound<'py, Self>> { let (mod_ptr, module_name): (_, Option<Py<PyString>>) = if let Some(m) = module { let mod_ptr = m.as_ptr(); (mod_ptr, Some(m.name()?.unbind())) } else { (std::ptr::null_mut(), None) }; let def = method_def.as_method_def(); // FIXME: stop leaking the def let def = Box::into_raw(Box::new(def)); let module_name_ptr = module_name .as_ref() .map_or(std::ptr::null_mut(), Py::as_ptr); unsafe { ffi::PyCFunction_NewEx(def, mod_ptr, module_name_ptr) .assume_owned_or_err(py) .downcast_into_unchecked() } } } static CLOSURE_CAPSULE_NAME: &CStr = ffi::c_str!("pyo3-closure"); unsafe extern "C" fn run_closure<F, R>( capsule_ptr: *mut ffi::PyObject, args: *mut ffi::PyObject, kwargs: *mut ffi::PyObject, ) -> *mut ffi::PyObject where F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> R + Send + 'static, for<'py> R: crate::impl_::callback::IntoPyCallbackOutput<'py, *mut ffi::PyObject>, { use crate::types::any::PyAnyMethods; crate::impl_::trampoline::cfunction_with_keywords( capsule_ptr, args, kwargs, |py, capsule_ptr, args, kwargs| { let boxed_fn: &ClosureDestructor<F> = &*(ffi::PyCapsule_GetPointer(capsule_ptr, CLOSURE_CAPSULE_NAME.as_ptr()) as *mut ClosureDestructor<F>); let args = Bound::ref_from_ptr(py, &args).downcast_unchecked::<PyTuple>(); let kwargs = Bound::ref_from_ptr_or_opt(py, &kwargs) .as_ref() .map(|b| b.downcast_unchecked::<PyDict>()); let result = (boxed_fn.closure)(args, kwargs); crate::impl_::callback::convert(py, result) }, ) } struct ClosureDestructor<F> { closure: F, // Wrapped in UnsafeCell because Python C-API wants a *mut pointer // to this member. def: UnsafeCell<ffi::PyMethodDef>, } // Safety: F is send and none of the fields are ever mutated unsafe impl<F: Send> Send for ClosureDestructor<F> {} /// Represents a Python function object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyFunction>`][crate::Py] or [`Bound<'py, PyFunction>`][Bound]. #[repr(transparent)] #[cfg(not(Py_LIMITED_API))] pub struct PyFunction(PyAny); #[cfg(not(Py_LIMITED_API))] pyobject_native_type_core!(PyFunction, pyobject_native_static_type_object!(ffi::PyFunction_Type), #checkfunction=ffi::PyFunction_Check);
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/ellipsis.rs
use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, types::any::PyAnyMethods, Borrowed, Bound, PyAny, PyTypeInfo, Python, }; /// Represents the Python `Ellipsis` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyEllipsis>`][crate::Py] or [`Bound<'py, PyEllipsis>`][Bound]. #[repr(transparent)] pub struct PyEllipsis(PyAny); pyobject_native_type_named!(PyEllipsis); impl PyEllipsis { /// Returns the `Ellipsis` object. #[inline] pub fn get(py: Python<'_>) -> Borrowed<'_, '_, PyEllipsis> { unsafe { ffi::Py_Ellipsis().assume_borrowed(py).downcast_unchecked() } } /// Deprecated name for [`PyEllipsis::get`]. #[deprecated(since = "0.23.0", note = "renamed to `PyEllipsis::get`")] #[inline] pub fn get_bound(py: Python<'_>) -> Borrowed<'_, '_, PyEllipsis> { Self::get(py) } } unsafe impl PyTypeInfo for PyEllipsis { const NAME: &'static str = "ellipsis"; const MODULE: Option<&'static str> = None; fn type_object_raw(_py: Python<'_>) -> *mut ffi::PyTypeObject { unsafe { ffi::Py_TYPE(ffi::Py_Ellipsis()) } } #[inline] fn is_type_of(object: &Bound<'_, PyAny>) -> bool { // ellipsis is not usable as a base type Self::is_exact_type_of(object) } #[inline] fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool { object.is(&**Self::get(object.py())) } } #[cfg(test)] mod tests { use crate::types::any::PyAnyMethods; use crate::types::{PyDict, PyEllipsis}; use crate::{PyTypeInfo, Python}; #[test] fn test_ellipsis_is_itself() { Python::with_gil(|py| { assert!(PyEllipsis::get(py).is_instance_of::<PyEllipsis>()); assert!(PyEllipsis::get(py).is_exact_instance_of::<PyEllipsis>()); }) } #[test] fn test_ellipsis_type_object_consistent() { Python::with_gil(|py| { assert!(PyEllipsis::get(py) .get_type() .is(&PyEllipsis::type_object(py))); }) } #[test] fn test_dict_is_not_ellipsis() { Python::with_gil(|py| { assert!(PyDict::new(py).downcast::<PyEllipsis>().is_err()); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/memoryview.rs
use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::{ffi, Bound, PyAny}; /// Represents a Python `memoryview`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyMemoryView>`][crate::Py] or [`Bound<'py, PyMemoryView>`][Bound]. #[repr(transparent)] pub struct PyMemoryView(PyAny); pyobject_native_type_core!(PyMemoryView, pyobject_native_static_type_object!(ffi::PyMemoryView_Type), #checkfunction=ffi::PyMemoryView_Check); impl PyMemoryView { /// Creates a new Python `memoryview` object from another Python object that /// implements the buffer protocol. pub fn from<'py>(src: &Bound<'py, PyAny>) -> PyResult<Bound<'py, Self>> { unsafe { ffi::PyMemoryView_FromObject(src.as_ptr()) .assume_owned_or_err(src.py()) .downcast_into_unchecked() } } /// Deprecated name for [`PyMemoryView::from`]. #[deprecated(since = "0.23.0", note = "renamed to `PyMemoryView::from`")] #[inline] pub fn from_bound<'py>(src: &Bound<'py, PyAny>) -> PyResult<Bound<'py, Self>> { Self::from(src) } } impl<'py> TryFrom<&Bound<'py, PyAny>> for Bound<'py, PyMemoryView> { type Error = crate::PyErr; /// Creates a new Python `memoryview` object from another Python object that /// implements the buffer protocol. fn try_from(value: &Bound<'py, PyAny>) -> Result<Self, Self::Error> { PyMemoryView::from(value) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/code.rs
use crate::ffi; use crate::PyAny; /// Represents a Python code object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyCode>`][crate::Py] or [`Bound<'py, PyCode>`][crate::Bound]. #[repr(transparent)] pub struct PyCode(PyAny); pyobject_native_type_core!( PyCode, pyobject_native_static_type_object!(ffi::PyCode_Type), #checkfunction=ffi::PyCode_Check ); #[cfg(test)] mod tests { use super::*; use crate::types::PyTypeMethods; use crate::{PyTypeInfo, Python}; #[test] fn test_type_object() { Python::with_gil(|py| { assert_eq!(PyCode::type_object(py).name().unwrap(), "code"); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/boolobject.rs
#[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; use crate::{ exceptions::PyTypeError, ffi, ffi_ptr_ext::FfiPtrExt, instance::Bound, types::typeobject::PyTypeMethods, Borrowed, FromPyObject, PyAny, PyObject, PyResult, Python, }; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; use super::any::PyAnyMethods; use crate::conversion::IntoPyObject; use crate::BoundObject; use std::convert::Infallible; /// Represents a Python `bool`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyBool>`][crate::Py] or [`Bound<'py, PyBool>`][Bound]. /// /// For APIs available on `bool` objects, see the [`PyBoolMethods`] trait which is implemented for /// [`Bound<'py, PyBool>`][Bound]. #[repr(transparent)] pub struct PyBool(PyAny); pyobject_native_type!(PyBool, ffi::PyObject, pyobject_native_static_type_object!(ffi::PyBool_Type), #checkfunction=ffi::PyBool_Check); impl PyBool { /// Depending on `val`, returns `true` or `false`. /// /// # Note /// This returns a [`Borrowed`] reference to one of Pythons `True` or /// `False` singletons #[inline] pub fn new(py: Python<'_>, val: bool) -> Borrowed<'_, '_, Self> { unsafe { if val { ffi::Py_True() } else { ffi::Py_False() } .assume_borrowed(py) .downcast_unchecked() } } /// Deprecated name for [`PyBool::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyBool::new`")] #[inline] pub fn new_bound(py: Python<'_>, val: bool) -> Borrowed<'_, '_, Self> { Self::new(py, val) } } /// Implementation of functionality for [`PyBool`]. /// /// These methods are defined for the `Bound<'py, PyBool>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyBool")] pub trait PyBoolMethods<'py>: crate::sealed::Sealed { /// Gets whether this boolean is `true`. fn is_true(&self) -> bool; } impl<'py> PyBoolMethods<'py> for Bound<'py, PyBool> { #[inline] fn is_true(&self) -> bool { self.as_ptr() == unsafe { crate::ffi::Py_True() } } } /// Compare `Bound<PyBool>` with `bool`. impl PartialEq<bool> for Bound<'_, PyBool> { #[inline] fn eq(&self, other: &bool) -> bool { self.as_borrowed() == *other } } /// Compare `&Bound<PyBool>` with `bool`. impl PartialEq<bool> for &'_ Bound<'_, PyBool> { #[inline] fn eq(&self, other: &bool) -> bool { self.as_borrowed() == *other } } /// Compare `Bound<PyBool>` with `&bool`. impl PartialEq<&'_ bool> for Bound<'_, PyBool> { #[inline] fn eq(&self, other: &&bool) -> bool { self.as_borrowed() == **other } } /// Compare `bool` with `Bound<PyBool>` impl PartialEq<Bound<'_, PyBool>> for bool { #[inline] fn eq(&self, other: &Bound<'_, PyBool>) -> bool { *self == other.as_borrowed() } } /// Compare `bool` with `&Bound<PyBool>` impl PartialEq<&'_ Bound<'_, PyBool>> for bool { #[inline] fn eq(&self, other: &&'_ Bound<'_, PyBool>) -> bool { *self == other.as_borrowed() } } /// Compare `&bool` with `Bound<PyBool>` impl PartialEq<Bound<'_, PyBool>> for &'_ bool { #[inline] fn eq(&self, other: &Bound<'_, PyBool>) -> bool { **self == other.as_borrowed() } } /// Compare `Borrowed<PyBool>` with `bool` impl PartialEq<bool> for Borrowed<'_, '_, PyBool> { #[inline] fn eq(&self, other: &bool) -> bool { self.is_true() == *other } } /// Compare `Borrowed<PyBool>` with `&bool` impl PartialEq<&bool> for Borrowed<'_, '_, PyBool> { #[inline] fn eq(&self, other: &&bool) -> bool { self.is_true() == **other } } /// Compare `bool` with `Borrowed<PyBool>` impl PartialEq<Borrowed<'_, '_, PyBool>> for bool { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyBool>) -> bool { *self == other.is_true() } } /// Compare `&bool` with `Borrowed<PyBool>` impl PartialEq<Borrowed<'_, '_, PyBool>> for &'_ bool { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyBool>) -> bool { **self == other.is_true() } } /// Converts a Rust `bool` to a Python `bool`. #[allow(deprecated)] impl ToPyObject for bool { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } #[allow(deprecated)] impl IntoPy<PyObject> for bool { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } impl<'py> IntoPyObject<'py> for bool { type Target = PyBool; type Output = Borrowed<'py, 'py, Self::Target>; type Error = Infallible; #[inline] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PyBool::new(py, self)) } #[cfg(feature = "experimental-inspect")] fn type_output() -> TypeInfo { TypeInfo::builtin("bool") } } impl<'py> IntoPyObject<'py> for &bool { type Target = PyBool; type Output = Borrowed<'py, '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("bool") } } /// Converts a Python `bool` to a Rust `bool`. /// /// Fails with `TypeError` if the input is not a Python `bool`. impl FromPyObject<'_> for bool { fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult<Self> { let err = match obj.downcast::<PyBool>() { Ok(obj) => return Ok(obj.is_true()), Err(err) => err, }; let is_numpy_bool = { let ty = obj.get_type(); ty.module().map_or(false, |module| module == "numpy") && ty .name() .map_or(false, |name| name == "bool_" || name == "bool") }; if is_numpy_bool { let missing_conversion = |obj: &Bound<'_, PyAny>| { PyTypeError::new_err(format!( "object of type '{}' does not define a '__bool__' conversion", obj.get_type() )) }; #[cfg(not(any(Py_LIMITED_API, PyPy)))] unsafe { let ptr = obj.as_ptr(); if let Some(tp_as_number) = (*(*ptr).ob_type).tp_as_number.as_ref() { if let Some(nb_bool) = tp_as_number.nb_bool { match (nb_bool)(ptr) { 0 => return Ok(false), 1 => return Ok(true), _ => return Err(crate::PyErr::fetch(obj.py())), } } } return Err(missing_conversion(obj)); } #[cfg(any(Py_LIMITED_API, PyPy))] { let meth = obj .lookup_special(crate::intern!(obj.py(), "__bool__"))? .ok_or_else(|| missing_conversion(obj))?; let obj = meth.call0()?.downcast_into::<PyBool>()?; return Ok(obj.is_true()); } } Err(err.into()) } #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { Self::type_output() } } #[cfg(test)] mod tests { use crate::types::any::PyAnyMethods; use crate::types::boolobject::PyBoolMethods; use crate::types::PyBool; use crate::IntoPyObject; use crate::Python; #[test] fn test_true() { Python::with_gil(|py| { assert!(PyBool::new(py, true).is_true()); let t = PyBool::new(py, true); assert!(t.extract::<bool>().unwrap()); assert!(true.into_pyobject(py).unwrap().is(&*PyBool::new(py, true))); }); } #[test] fn test_false() { Python::with_gil(|py| { assert!(!PyBool::new(py, false).is_true()); let t = PyBool::new(py, false); assert!(!t.extract::<bool>().unwrap()); assert!(false .into_pyobject(py) .unwrap() .is(&*PyBool::new(py, false))); }); } #[test] fn test_pybool_comparisons() { Python::with_gil(|py| { let py_bool = PyBool::new(py, true); let py_bool_false = PyBool::new(py, false); let rust_bool = true; // Bound<'_, PyBool> == bool assert_eq!(*py_bool, rust_bool); assert_ne!(*py_bool_false, rust_bool); // Bound<'_, PyBool> == &bool assert_eq!(*py_bool, &rust_bool); assert_ne!(*py_bool_false, &rust_bool); // &Bound<'_, PyBool> == bool assert_eq!(&*py_bool, rust_bool); assert_ne!(&*py_bool_false, rust_bool); // &Bound<'_, PyBool> == &bool assert_eq!(&*py_bool, &rust_bool); assert_ne!(&*py_bool_false, &rust_bool); // bool == Bound<'_, PyBool> assert_eq!(rust_bool, *py_bool); assert_ne!(rust_bool, *py_bool_false); // bool == &Bound<'_, PyBool> assert_eq!(rust_bool, &*py_bool); assert_ne!(rust_bool, &*py_bool_false); // &bool == Bound<'_, PyBool> assert_eq!(&rust_bool, *py_bool); assert_ne!(&rust_bool, *py_bool_false); // &bool == &Bound<'_, PyBool> assert_eq!(&rust_bool, &*py_bool); assert_ne!(&rust_bool, &*py_bool_false); // Borrowed<'_, '_, PyBool> == bool assert_eq!(py_bool, rust_bool); assert_ne!(py_bool_false, rust_bool); // Borrowed<'_, '_, PyBool> == &bool assert_eq!(py_bool, &rust_bool); assert_ne!(py_bool_false, &rust_bool); // bool == Borrowed<'_, '_, PyBool> assert_eq!(rust_bool, py_bool); assert_ne!(rust_bool, py_bool_false); // &bool == Borrowed<'_, '_, PyBool> assert_eq!(&rust_bool, py_bool); assert_ne!(&rust_bool, py_bool_false); assert_eq!(py_bool, rust_bool); assert_ne!(py_bool_false, rust_bool); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/float.rs
use super::any::PyAnyMethods; use crate::conversion::IntoPyObject; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, instance::Bound, Borrowed, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python, }; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; use std::convert::Infallible; use std::os::raw::c_double; /// Represents a Python `float` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyFloat>`][crate::Py] or [`Bound<'py, PyFloat>`][Bound]. /// /// For APIs available on `float` objects, see the [`PyFloatMethods`] trait which is implemented for /// [`Bound<'py, PyFloat>`][Bound]. /// /// You can usually avoid directly working with this type /// by using [`ToPyObject`] and [`extract`][PyAnyMethods::extract] /// with [`f32`]/[`f64`]. #[repr(transparent)] pub struct PyFloat(PyAny); pyobject_subclassable_native_type!(PyFloat, crate::ffi::PyFloatObject); pyobject_native_type!( PyFloat, ffi::PyFloatObject, pyobject_native_static_type_object!(ffi::PyFloat_Type), #checkfunction=ffi::PyFloat_Check ); impl PyFloat { /// Creates a new Python `float` object. pub fn new(py: Python<'_>, val: c_double) -> Bound<'_, PyFloat> { unsafe { ffi::PyFloat_FromDouble(val) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyFloat::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyFloat::new`")] #[inline] pub fn new_bound(py: Python<'_>, val: c_double) -> Bound<'_, PyFloat> { Self::new(py, val) } } /// Implementation of functionality for [`PyFloat`]. /// /// These methods are defined for the `Bound<'py, PyFloat>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyFloat")] pub trait PyFloatMethods<'py>: crate::sealed::Sealed { /// Gets the value of this float. fn value(&self) -> c_double; } impl<'py> PyFloatMethods<'py> for Bound<'py, PyFloat> { fn value(&self) -> c_double { #[cfg(not(Py_LIMITED_API))] unsafe { // Safety: self is PyFloat object ffi::PyFloat_AS_DOUBLE(self.as_ptr()) } #[cfg(Py_LIMITED_API)] unsafe { ffi::PyFloat_AsDouble(self.as_ptr()) } } } #[allow(deprecated)] impl ToPyObject for f64 { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } #[allow(deprecated)] impl IntoPy<PyObject> for f64 { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } impl<'py> IntoPyObject<'py> for f64 { type Target = PyFloat; type Output = Bound<'py, Self::Target>; type Error = Infallible; #[inline] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PyFloat::new(py, self)) } #[cfg(feature = "experimental-inspect")] fn type_output() -> TypeInfo { TypeInfo::builtin("float") } } impl<'py> IntoPyObject<'py> for &f64 { type Target = PyFloat; 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("float") } } impl<'py> FromPyObject<'py> for f64 { // PyFloat_AsDouble returns -1.0 upon failure #![allow(clippy::float_cmp)] fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> { // On non-limited API, .value() uses PyFloat_AS_DOUBLE which // allows us to have an optimized fast path for the case when // we have exactly a `float` object (it's not worth going through // `isinstance` machinery for subclasses). #[cfg(not(Py_LIMITED_API))] if let Ok(float) = obj.downcast_exact::<PyFloat>() { return Ok(float.value()); } let v = unsafe { ffi::PyFloat_AsDouble(obj.as_ptr()) }; if v == -1.0 { if let Some(err) = PyErr::take(obj.py()) { return Err(err); } } Ok(v) } #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { Self::type_output() } } #[allow(deprecated)] impl ToPyObject for f32 { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } #[allow(deprecated)] impl IntoPy<PyObject> for f32 { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } impl<'py> IntoPyObject<'py> for f32 { type Target = PyFloat; type Output = Bound<'py, Self::Target>; type Error = Infallible; #[inline] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PyFloat::new(py, self.into())) } #[cfg(feature = "experimental-inspect")] fn type_output() -> TypeInfo { TypeInfo::builtin("float") } } impl<'py> IntoPyObject<'py> for &f32 { type Target = PyFloat; 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("float") } } impl<'py> FromPyObject<'py> for f32 { fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> { Ok(obj.extract::<f64>()? as f32) } #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { Self::type_output() } } macro_rules! impl_partial_eq_for_float { ($float_type: ty) => { impl PartialEq<$float_type> for Bound<'_, PyFloat> { #[inline] fn eq(&self, other: &$float_type) -> bool { self.value() as $float_type == *other } } impl PartialEq<$float_type> for &Bound<'_, PyFloat> { #[inline] fn eq(&self, other: &$float_type) -> bool { self.value() as $float_type == *other } } impl PartialEq<&$float_type> for Bound<'_, PyFloat> { #[inline] fn eq(&self, other: &&$float_type) -> bool { self.value() as $float_type == **other } } impl PartialEq<Bound<'_, PyFloat>> for $float_type { #[inline] fn eq(&self, other: &Bound<'_, PyFloat>) -> bool { other.value() as $float_type == *self } } impl PartialEq<&'_ Bound<'_, PyFloat>> for $float_type { #[inline] fn eq(&self, other: &&'_ Bound<'_, PyFloat>) -> bool { other.value() as $float_type == *self } } impl PartialEq<Bound<'_, PyFloat>> for &'_ $float_type { #[inline] fn eq(&self, other: &Bound<'_, PyFloat>) -> bool { other.value() as $float_type == **self } } impl PartialEq<$float_type> for Borrowed<'_, '_, PyFloat> { #[inline] fn eq(&self, other: &$float_type) -> bool { self.value() as $float_type == *other } } impl PartialEq<&$float_type> for Borrowed<'_, '_, PyFloat> { #[inline] fn eq(&self, other: &&$float_type) -> bool { self.value() as $float_type == **other } } impl PartialEq<Borrowed<'_, '_, PyFloat>> for $float_type { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyFloat>) -> bool { other.value() as $float_type == *self } } impl PartialEq<Borrowed<'_, '_, PyFloat>> for &$float_type { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyFloat>) -> bool { other.value() as $float_type == **self } } }; } impl_partial_eq_for_float!(f64); impl_partial_eq_for_float!(f32); #[cfg(test)] mod tests { use crate::{ conversion::IntoPyObject, types::{PyAnyMethods, PyFloat, PyFloatMethods}, Python, }; macro_rules! num_to_py_object_and_back ( ($func_name:ident, $t1:ty, $t2:ty) => ( #[test] fn $func_name() { use assert_approx_eq::assert_approx_eq; Python::with_gil(|py| { let val = 123 as $t1; let obj = val.into_pyobject(py).unwrap(); assert_approx_eq!(obj.extract::<$t2>().unwrap(), val as $t2); }); } ) ); num_to_py_object_and_back!(to_from_f64, f64, f64); num_to_py_object_and_back!(to_from_f32, f32, f32); num_to_py_object_and_back!(int_to_float, i32, f64); #[test] fn test_float_value() { use assert_approx_eq::assert_approx_eq; Python::with_gil(|py| { let v = 1.23f64; let obj = PyFloat::new(py, 1.23); assert_approx_eq!(v, obj.value()); }); } #[test] fn test_pyfloat_comparisons() { Python::with_gil(|py| { let f_64 = 1.01f64; let py_f64 = PyFloat::new(py, 1.01); let py_f64_ref = &py_f64; let py_f64_borrowed = py_f64.as_borrowed(); // Bound<'_, PyFloat> == f64 and vice versa assert_eq!(py_f64, f_64); assert_eq!(f_64, py_f64); // Bound<'_, PyFloat> == &f64 and vice versa assert_eq!(py_f64, &f_64); assert_eq!(&f_64, py_f64); // &Bound<'_, PyFloat> == &f64 and vice versa assert_eq!(py_f64_ref, f_64); assert_eq!(f_64, py_f64_ref); // &Bound<'_, PyFloat> == &f64 and vice versa assert_eq!(py_f64_ref, &f_64); assert_eq!(&f_64, py_f64_ref); // Borrowed<'_, '_, PyFloat> == f64 and vice versa assert_eq!(py_f64_borrowed, f_64); assert_eq!(f_64, py_f64_borrowed); // Borrowed<'_, '_, PyFloat> == &f64 and vice versa assert_eq!(py_f64_borrowed, &f_64); assert_eq!(&f_64, py_f64_borrowed); let f_32 = 2.02f32; let py_f32 = PyFloat::new(py, 2.02); let py_f32_ref = &py_f32; let py_f32_borrowed = py_f32.as_borrowed(); // Bound<'_, PyFloat> == f32 and vice versa assert_eq!(py_f32, f_32); assert_eq!(f_32, py_f32); // Bound<'_, PyFloat> == &f32 and vice versa assert_eq!(py_f32, &f_32); assert_eq!(&f_32, py_f32); // &Bound<'_, PyFloat> == &f32 and vice versa assert_eq!(py_f32_ref, f_32); assert_eq!(f_32, py_f32_ref); // &Bound<'_, PyFloat> == &f32 and vice versa assert_eq!(py_f32_ref, &f_32); assert_eq!(&f_32, py_f32_ref); // Borrowed<'_, '_, PyFloat> == f32 and vice versa assert_eq!(py_f32_borrowed, f_32); assert_eq!(f_32, py_f32_borrowed); // Borrowed<'_, '_, PyFloat> == &f32 and vice versa assert_eq!(py_f32_borrowed, &f_32); assert_eq!(&f_32, py_f32_borrowed); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/traceback.rs
use crate::err::{error_on_minusone, PyResult}; use crate::types::{any::PyAnyMethods, string::PyStringMethods, PyString}; use crate::{ffi, Bound, PyAny}; /// Represents a Python traceback. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyTraceback>`][crate::Py] or [`Bound<'py, PyTraceback>`][Bound]. /// /// For APIs available on traceback objects, see the [`PyTracebackMethods`] trait which is implemented for /// [`Bound<'py, PyTraceback>`][Bound]. #[repr(transparent)] pub struct PyTraceback(PyAny); pyobject_native_type_core!( PyTraceback, pyobject_native_static_type_object!(ffi::PyTraceBack_Type), #checkfunction=ffi::PyTraceBack_Check ); /// Implementation of functionality for [`PyTraceback`]. /// /// These methods are defined for the `Bound<'py, PyTraceback>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyTraceback")] pub trait PyTracebackMethods<'py>: crate::sealed::Sealed { /// Formats the traceback as a string. /// /// This does not include the exception type and value. The exception type and value can be /// formatted using the `Display` implementation for `PyErr`. /// /// # Example /// /// The following code formats a Python traceback and exception pair from Rust: /// /// ```rust /// # use pyo3::{Python, PyResult, prelude::PyTracebackMethods, ffi::c_str}; /// # let result: PyResult<()> = /// Python::with_gil(|py| { /// let err = py /// .run(c_str!("raise Exception('banana')"), None, None) /// .expect_err("raise will create a Python error"); /// /// let traceback = err.traceback(py).expect("raised exception will have a traceback"); /// assert_eq!( /// format!("{}{}", traceback.format()?, err), /// "\ /// Traceback (most recent call last): /// File \"<string>\", line 1, in <module> /// Exception: banana\ /// " /// ); /// Ok(()) /// }) /// # ; /// # result.expect("example failed"); /// ``` fn format(&self) -> PyResult<String>; } impl<'py> PyTracebackMethods<'py> for Bound<'py, PyTraceback> { fn format(&self) -> PyResult<String> { let py = self.py(); let string_io = py .import(intern!(py, "io"))? .getattr(intern!(py, "StringIO"))? .call0()?; let result = unsafe { ffi::PyTraceBack_Print(self.as_ptr(), string_io.as_ptr()) }; error_on_minusone(py, result)?; let formatted = string_io .getattr(intern!(py, "getvalue"))? .call0()? .downcast::<PyString>()? .to_cow()? .into_owned(); Ok(formatted) } } #[cfg(test)] mod tests { use crate::IntoPyObject; use crate::{ ffi, types::{any::PyAnyMethods, dict::PyDictMethods, traceback::PyTracebackMethods, PyDict}, PyErr, Python, }; #[test] fn format_traceback() { Python::with_gil(|py| { let err = py .run(ffi::c_str!("raise Exception('banana')"), None, None) .expect_err("raising should have given us an error"); assert_eq!( err.traceback(py).unwrap().format().unwrap(), "Traceback (most recent call last):\n File \"<string>\", line 1, in <module>\n" ); }) } #[test] fn test_err_from_value() { Python::with_gil(|py| { let locals = PyDict::new(py); // Produce an error from python so that it has a traceback py.run( ffi::c_str!( r" try: raise ValueError('raised exception') except Exception as e: err = e " ), None, Some(&locals), ) .unwrap(); let err = PyErr::from_value(locals.get_item("err").unwrap().unwrap()); let traceback = err.value(py).getattr("__traceback__").unwrap(); assert!(err.traceback(py).unwrap().is(&traceback)); }) } #[test] fn test_err_into_py() { Python::with_gil(|py| { let locals = PyDict::new(py); // Produce an error from python so that it has a traceback py.run( ffi::c_str!( r" def f(): raise ValueError('raised exception') " ), None, Some(&locals), ) .unwrap(); let f = locals.get_item("f").unwrap().unwrap(); let err = f.call0().unwrap_err(); let traceback = err.traceback(py).unwrap(); let err_object = err.clone_ref(py).into_pyobject(py).unwrap(); assert!(err_object.getattr("__traceback__").unwrap().is(&traceback)); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/notimplemented.rs
use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, types::any::PyAnyMethods, Borrowed, Bound, PyAny, PyTypeInfo, Python, }; /// Represents the Python `NotImplemented` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyNotImplemented>`][crate::Py] or [`Bound<'py, PyNotImplemented>`][Bound]. #[repr(transparent)] pub struct PyNotImplemented(PyAny); pyobject_native_type_named!(PyNotImplemented); impl PyNotImplemented { /// Returns the `NotImplemented` object. #[inline] pub fn get(py: Python<'_>) -> Borrowed<'_, '_, PyNotImplemented> { unsafe { ffi::Py_NotImplemented() .assume_borrowed(py) .downcast_unchecked() } } /// Deprecated name for [`PyNotImplemented::get`]. #[deprecated(since = "0.23.0", note = "renamed to `PyNotImplemented::get`")] #[inline] pub fn get_bound(py: Python<'_>) -> Borrowed<'_, '_, PyNotImplemented> { Self::get(py) } } unsafe impl PyTypeInfo for PyNotImplemented { const NAME: &'static str = "NotImplementedType"; const MODULE: Option<&'static str> = None; fn type_object_raw(_py: Python<'_>) -> *mut ffi::PyTypeObject { unsafe { ffi::Py_TYPE(ffi::Py_NotImplemented()) } } #[inline] fn is_type_of(object: &Bound<'_, PyAny>) -> bool { // NotImplementedType is not usable as a base type Self::is_exact_type_of(object) } #[inline] fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool { object.is(&**Self::get(object.py())) } } #[cfg(test)] mod tests { use crate::types::any::PyAnyMethods; use crate::types::{PyDict, PyNotImplemented}; use crate::{PyTypeInfo, Python}; #[test] fn test_notimplemented_is_itself() { Python::with_gil(|py| { assert!(PyNotImplemented::get(py).is_instance_of::<PyNotImplemented>()); assert!(PyNotImplemented::get(py).is_exact_instance_of::<PyNotImplemented>()); }) } #[test] fn test_notimplemented_type_object_consistent() { Python::with_gil(|py| { assert!(PyNotImplemented::get(py) .get_type() .is(&PyNotImplemented::type_object(py))); }) } #[test] fn test_dict_is_not_notimplemented() { Python::with_gil(|py| { assert!(PyDict::new(py).downcast::<PyNotImplemented>().is_err()); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/bytearray.rs
use crate::err::{PyErr, PyResult}; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::{Borrowed, Bound}; use crate::py_result_ext::PyResultExt; use crate::types::any::PyAnyMethods; use crate::{ffi, PyAny, Python}; use std::slice; /// Represents a Python `bytearray`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyByteArray>`][crate::Py] or [`Bound<'py, PyByteArray>`][Bound]. /// /// For APIs available on `bytearray` objects, see the [`PyByteArrayMethods`] trait which is implemented for /// [`Bound<'py, PyByteArray>`][Bound]. #[repr(transparent)] pub struct PyByteArray(PyAny); pyobject_native_type_core!(PyByteArray, pyobject_native_static_type_object!(ffi::PyByteArray_Type), #checkfunction=ffi::PyByteArray_Check); impl PyByteArray { /// Creates a new Python bytearray object. /// /// The byte string is initialized by copying the data from the `&[u8]`. pub fn new<'py>(py: Python<'py>, src: &[u8]) -> Bound<'py, PyByteArray> { let ptr = src.as_ptr().cast(); let len = src.len() as ffi::Py_ssize_t; unsafe { ffi::PyByteArray_FromStringAndSize(ptr, len) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyByteArray::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyByteArray::new`")] #[inline] pub fn new_bound<'py>(py: Python<'py>, src: &[u8]) -> Bound<'py, PyByteArray> { Self::new(py, src) } /// Creates a new Python `bytearray` object with an `init` closure to write its contents. /// Before calling `init` the bytearray is zero-initialised. /// * If Python raises a MemoryError on the allocation, `new_with` will return /// it inside `Err`. /// * If `init` returns `Err(e)`, `new_with` will return `Err(e)`. /// * If `init` returns `Ok(())`, `new_with` will return `Ok(&PyByteArray)`. /// /// # Examples /// /// ``` /// use pyo3::{prelude::*, types::PyByteArray}; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let py_bytearray = PyByteArray::new_with(py, 10, |bytes: &mut [u8]| { /// bytes.copy_from_slice(b"Hello Rust"); /// Ok(()) /// })?; /// let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; /// assert_eq!(bytearray, b"Hello Rust"); /// Ok(()) /// }) /// # } /// ``` pub fn new_with<F>(py: Python<'_>, len: usize, init: F) -> PyResult<Bound<'_, PyByteArray>> where F: FnOnce(&mut [u8]) -> PyResult<()>, { unsafe { // Allocate buffer and check for an error let pybytearray: Bound<'_, Self> = ffi::PyByteArray_FromStringAndSize(std::ptr::null(), len as ffi::Py_ssize_t) .assume_owned_or_err(py)? .downcast_into_unchecked(); let buffer: *mut u8 = ffi::PyByteArray_AsString(pybytearray.as_ptr()).cast(); debug_assert!(!buffer.is_null()); // Zero-initialise the uninitialised bytearray std::ptr::write_bytes(buffer, 0u8, len); // (Further) Initialise the bytearray in init // If init returns an Err, pypybytearray will automatically deallocate the buffer init(std::slice::from_raw_parts_mut(buffer, len)).map(|_| pybytearray) } } /// Deprecated name for [`PyByteArray::new_with`]. #[deprecated(since = "0.23.0", note = "renamed to `PyByteArray::new_with`")] #[inline] pub fn new_bound_with<F>( py: Python<'_>, len: usize, init: F, ) -> PyResult<Bound<'_, PyByteArray>> where F: FnOnce(&mut [u8]) -> PyResult<()>, { Self::new_with(py, len, init) } /// Creates a new Python `bytearray` object from another Python object that /// implements the buffer protocol. pub fn from<'py>(src: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyByteArray>> { unsafe { ffi::PyByteArray_FromObject(src.as_ptr()) .assume_owned_or_err(src.py()) .downcast_into_unchecked() } } ///Deprecated name for [`PyByteArray::from`]. #[deprecated(since = "0.23.0", note = "renamed to `PyByteArray::from`")] #[inline] pub fn from_bound<'py>(src: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyByteArray>> { Self::from(src) } } /// Implementation of functionality for [`PyByteArray`]. /// /// These methods are defined for the `Bound<'py, PyByteArray>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyByteArray")] pub trait PyByteArrayMethods<'py>: crate::sealed::Sealed { /// Gets the length of the bytearray. fn len(&self) -> usize; /// Checks if the bytearray is empty. fn is_empty(&self) -> bool; /// Gets the start of the buffer containing the contents of the bytearray. /// /// # Safety /// /// See the safety requirements of [`PyByteArrayMethods::as_bytes`] and [`PyByteArrayMethods::as_bytes_mut`]. fn data(&self) -> *mut u8; /// Extracts a slice of the `ByteArray`'s entire buffer. /// /// # Safety /// /// Mutation of the `bytearray` invalidates the slice. If it is used afterwards, the behavior is /// undefined. /// /// These mutations may occur in Python code as well as from Rust: /// - Calling methods like [`PyByteArrayMethods::as_bytes_mut`] and [`PyByteArrayMethods::resize`] will /// invalidate the slice. /// - Actions like dropping objects or raising exceptions can invoke `__del__`methods or signal /// handlers, which may execute arbitrary Python code. This means that if Python code has a /// reference to the `bytearray` you cannot safely use the vast majority of PyO3's API whilst /// using the slice. /// /// As a result, this slice should only be used for short-lived operations without executing any /// Python code, such as copying into a Vec. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::exceptions::PyRuntimeError; /// use pyo3::types::PyByteArray; /// /// #[pyfunction] /// fn a_valid_function(bytes: &Bound<'_, PyByteArray>) -> PyResult<()> { /// let section = { /// // SAFETY: We promise to not let the interpreter regain control /// // or invoke any PyO3 APIs while using the slice. /// let slice = unsafe { bytes.as_bytes() }; /// /// // Copy only a section of `bytes` while avoiding /// // `to_vec` which copies the entire thing. /// let section = slice /// .get(6..11) /// .ok_or_else(|| PyRuntimeError::new_err("input is not long enough"))?; /// Vec::from(section) /// }; /// /// // Now we can do things with `section` and call PyO3 APIs again. /// // ... /// # assert_eq!(&section, b"world"); /// /// Ok(()) /// } /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| -> PyResult<()> { /// # let fun = wrap_pyfunction!(a_valid_function, py)?; /// # let locals = pyo3::types::PyDict::new(py); /// # locals.set_item("a_valid_function", fun)?; /// # /// # py.run(pyo3::ffi::c_str!( /// # r#"b = bytearray(b"hello world") /// # a_valid_function(b) /// # /// # try: /// # a_valid_function(bytearray()) /// # except RuntimeError as e: /// # assert str(e) == 'input is not long enough'"#), /// # None, /// # Some(&locals), /// # )?; /// # /// # Ok(()) /// # }) /// # } /// ``` /// /// # Incorrect usage /// /// The following `bug` function is unsound ⚠️ /// /// ```rust,no_run /// # use pyo3::prelude::*; /// # use pyo3::types::PyByteArray; /// /// # #[allow(dead_code)] /// #[pyfunction] /// fn bug(py: Python<'_>, bytes: &Bound<'_, PyByteArray>) { /// let slice = unsafe { bytes.as_bytes() }; /// /// // This explicitly yields control back to the Python interpreter... /// // ...but it's not always this obvious. Many things do this implicitly. /// py.allow_threads(|| { /// // Python code could be mutating through its handle to `bytes`, /// // which makes reading it a data race, which is undefined behavior. /// println!("{:?}", slice[0]); /// }); /// /// // Python code might have mutated it, so we can not rely on the slice /// // remaining valid. As such this is also undefined behavior. /// println!("{:?}", slice[0]); /// } /// ``` unsafe fn as_bytes(&self) -> &[u8]; /// Extracts a mutable slice of the `ByteArray`'s entire buffer. /// /// # Safety /// /// Any other accesses of the `bytearray`'s buffer invalidate the slice. If it is used /// afterwards, the behavior is undefined. The safety requirements of [`PyByteArrayMethods::as_bytes`] /// apply to this function as well. #[allow(clippy::mut_from_ref)] unsafe fn as_bytes_mut(&self) -> &mut [u8]; /// Copies the contents of the bytearray to a Rust vector. /// /// # Examples /// /// ``` /// # use pyo3::prelude::*; /// # use pyo3::types::PyByteArray; /// # Python::with_gil(|py| { /// let bytearray = PyByteArray::new(py, b"Hello World."); /// let mut copied_message = bytearray.to_vec(); /// assert_eq!(b"Hello World.", copied_message.as_slice()); /// /// copied_message[11] = b'!'; /// assert_eq!(b"Hello World!", copied_message.as_slice()); /// /// pyo3::py_run!(py, bytearray, "assert bytearray == b'Hello World.'"); /// # }); /// ``` fn to_vec(&self) -> Vec<u8>; /// Resizes the bytearray object to the new length `len`. /// /// Note that this will invalidate any pointers obtained by [PyByteArrayMethods::data], as well as /// any (unsafe) slices obtained from [PyByteArrayMethods::as_bytes] and [PyByteArrayMethods::as_bytes_mut]. fn resize(&self, len: usize) -> PyResult<()>; } impl<'py> PyByteArrayMethods<'py> for Bound<'py, PyByteArray> { #[inline] fn len(&self) -> usize { // non-negative Py_ssize_t should always fit into Rust usize unsafe { ffi::PyByteArray_Size(self.as_ptr()) as usize } } fn is_empty(&self) -> bool { self.len() == 0 } fn data(&self) -> *mut u8 { self.as_borrowed().data() } unsafe fn as_bytes(&self) -> &[u8] { self.as_borrowed().as_bytes() } #[allow(clippy::mut_from_ref)] unsafe fn as_bytes_mut(&self) -> &mut [u8] { self.as_borrowed().as_bytes_mut() } fn to_vec(&self) -> Vec<u8> { unsafe { self.as_bytes() }.to_vec() } fn resize(&self, len: usize) -> PyResult<()> { unsafe { let result = ffi::PyByteArray_Resize(self.as_ptr(), len as ffi::Py_ssize_t); if result == 0 { Ok(()) } else { Err(PyErr::fetch(self.py())) } } } } impl<'a> Borrowed<'a, '_, PyByteArray> { fn data(&self) -> *mut u8 { unsafe { ffi::PyByteArray_AsString(self.as_ptr()).cast() } } #[allow(clippy::wrong_self_convention)] unsafe fn as_bytes(self) -> &'a [u8] { slice::from_raw_parts(self.data(), self.len()) } #[allow(clippy::wrong_self_convention)] unsafe fn as_bytes_mut(self) -> &'a mut [u8] { slice::from_raw_parts_mut(self.data(), self.len()) } } impl<'py> TryFrom<&Bound<'py, PyAny>> for Bound<'py, PyByteArray> { type Error = crate::PyErr; /// Creates a new Python `bytearray` object from another Python object that /// implements the buffer protocol. fn try_from(value: &Bound<'py, PyAny>) -> Result<Self, Self::Error> { PyByteArray::from(value) } } #[cfg(test)] mod tests { use crate::types::{PyAnyMethods, PyByteArray, PyByteArrayMethods}; use crate::{exceptions, Bound, PyAny, PyObject, Python}; #[test] fn test_len() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray = PyByteArray::new(py, src); assert_eq!(src.len(), bytearray.len()); }); } #[test] fn test_as_bytes() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray = PyByteArray::new(py, src); let slice = unsafe { bytearray.as_bytes() }; assert_eq!(src, slice); assert_eq!(bytearray.data() as *const _, slice.as_ptr()); }); } #[test] fn test_as_bytes_mut() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray = PyByteArray::new(py, src); let slice = unsafe { bytearray.as_bytes_mut() }; assert_eq!(src, slice); assert_eq!(bytearray.data(), slice.as_mut_ptr()); slice[0..5].copy_from_slice(b"Hi..."); assert_eq!(bytearray.str().unwrap(), "bytearray(b'Hi... Python')"); }); } #[test] fn test_to_vec() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray = PyByteArray::new(py, src); let vec = bytearray.to_vec(); assert_eq!(src, vec.as_slice()); }); } #[test] fn test_from() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray = PyByteArray::new(py, src); let ba: PyObject = bytearray.into(); let bytearray = PyByteArray::from(ba.bind(py)).unwrap(); assert_eq!(src, unsafe { bytearray.as_bytes() }); }); } #[test] fn test_from_err() { Python::with_gil(|py| { if let Err(err) = PyByteArray::from(py.None().bind(py)) { assert!(err.is_instance_of::<exceptions::PyTypeError>(py)); } else { panic!("error"); } }); } #[test] fn test_try_from() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray: &Bound<'_, PyAny> = &PyByteArray::new(py, src); let bytearray: Bound<'_, PyByteArray> = TryInto::try_into(bytearray).unwrap(); assert_eq!(src, unsafe { bytearray.as_bytes() }); }); } #[test] fn test_resize() { Python::with_gil(|py| { let src = b"Hello Python"; let bytearray = PyByteArray::new(py, src); bytearray.resize(20).unwrap(); assert_eq!(20, bytearray.len()); }); } #[test] fn test_byte_array_new_with() -> super::PyResult<()> { Python::with_gil(|py| -> super::PyResult<()> { let py_bytearray = PyByteArray::new_with(py, 10, |b: &mut [u8]| { b.copy_from_slice(b"Hello Rust"); Ok(()) })?; let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; assert_eq!(bytearray, b"Hello Rust"); Ok(()) }) } #[test] fn test_byte_array_new_with_zero_initialised() -> super::PyResult<()> { Python::with_gil(|py| -> super::PyResult<()> { let py_bytearray = PyByteArray::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; let bytearray: &[u8] = unsafe { py_bytearray.as_bytes() }; assert_eq!(bytearray, &[0; 10]); Ok(()) }) } #[test] fn test_byte_array_new_with_error() { use crate::exceptions::PyValueError; Python::with_gil(|py| { let py_bytearray_result = PyByteArray::new_with(py, 10, |_b: &mut [u8]| { Err(PyValueError::new_err("Hello Crustaceans!")) }); assert!(py_bytearray_result.is_err()); assert!(py_bytearray_result .err() .unwrap() .is_instance_of::<PyValueError>(py)); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/tuple.rs
use std::iter::FusedIterator; use crate::conversion::IntoPyObject; use crate::ffi::{self, Py_ssize_t}; use crate::ffi_ptr_ext::FfiPtrExt; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; use crate::instance::Borrowed; use crate::internal_tricks::get_ssize_index; use crate::types::{any::PyAnyMethods, sequence::PySequenceMethods, PyList, PySequence}; use crate::{ exceptions, Bound, BoundObject, FromPyObject, Py, PyAny, PyErr, PyObject, PyResult, Python, }; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; #[inline] #[track_caller] fn try_new_from_iter<'py>( py: Python<'py>, mut elements: impl ExactSizeIterator<Item = PyResult<Bound<'py, PyAny>>>, ) -> PyResult<Bound<'py, PyTuple>> { unsafe { // PyTuple_New checks for overflow but has a bad error message, so we check ourselves let len: Py_ssize_t = elements .len() .try_into() .expect("out of range integral type conversion attempted on `elements.len()`"); let ptr = ffi::PyTuple_New(len); // - Panics if the ptr is null // - Cleans up the tuple if `convert` or the asserts panic let tup = ptr.assume_owned(py).downcast_into_unchecked(); let mut counter: Py_ssize_t = 0; for obj in (&mut elements).take(len as usize) { #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] ffi::PyTuple_SET_ITEM(ptr, counter, obj?.into_ptr()); #[cfg(any(Py_LIMITED_API, PyPy, GraalPy))] ffi::PyTuple_SetItem(ptr, counter, obj?.into_ptr()); counter += 1; } assert!(elements.next().is_none(), "Attempted to create PyTuple but `elements` was larger than reported by its `ExactSizeIterator` implementation."); assert_eq!(len, counter, "Attempted to create PyTuple but `elements` was smaller than reported by its `ExactSizeIterator` implementation."); Ok(tup) } } /// Represents a Python `tuple` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyTuple>`][crate::Py] or [`Bound<'py, PyTuple>`][Bound]. /// /// For APIs available on `tuple` objects, see the [`PyTupleMethods`] trait which is implemented for /// [`Bound<'py, PyTuple>`][Bound]. #[repr(transparent)] pub struct PyTuple(PyAny); pyobject_native_type_core!(PyTuple, pyobject_native_static_type_object!(ffi::PyTuple_Type), #checkfunction=ffi::PyTuple_Check); impl PyTuple { /// Constructs a new tuple with the given elements. /// /// If you want to create a [`PyTuple`] with elements of different or unknown types, or from an /// iterable that doesn't implement [`ExactSizeIterator`], create a Rust tuple with the given /// elements and convert it at once using `into_py`. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyTuple; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let elements: Vec<i32> = vec![0, 1, 2, 3, 4, 5]; /// let tuple = PyTuple::new(py, elements)?; /// assert_eq!(format!("{:?}", tuple), "(0, 1, 2, 3, 4, 5)"); /// # Ok(()) /// }) /// # } /// ``` /// /// # Panics /// /// This function will panic if `element`'s [`ExactSizeIterator`] implementation is incorrect. /// All standard library structures implement this trait correctly, if they do, so calling this /// function using [`Vec`]`<T>` or `&[T]` will always succeed. #[track_caller] pub fn new<'py, T, U>( py: Python<'py>, elements: impl IntoIterator<Item = T, IntoIter = U>, ) -> PyResult<Bound<'py, PyTuple>> where T: IntoPyObject<'py>, U: ExactSizeIterator<Item = T>, { let elements = elements.into_iter().map(|e| { e.into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::into_bound) .map_err(Into::into) }); try_new_from_iter(py, elements) } /// Deprecated name for [`PyTuple::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTuple::new`")] #[allow(deprecated)] #[track_caller] #[inline] pub fn new_bound<T, U>( py: Python<'_>, elements: impl IntoIterator<Item = T, IntoIter = U>, ) -> Bound<'_, PyTuple> where T: ToPyObject, U: ExactSizeIterator<Item = T>, { PyTuple::new(py, elements.into_iter().map(|e| e.to_object(py))).unwrap() } /// Constructs an empty tuple (on the Python side, a singleton object). pub fn empty(py: Python<'_>) -> Bound<'_, PyTuple> { unsafe { ffi::PyTuple_New(0) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyTuple::empty`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTuple::empty`")] #[inline] pub fn empty_bound(py: Python<'_>) -> Bound<'_, PyTuple> { PyTuple::empty(py) } } /// Implementation of functionality for [`PyTuple`]. /// /// These methods are defined for the `Bound<'py, PyTuple>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyTuple")] pub trait PyTupleMethods<'py>: crate::sealed::Sealed { /// Gets the length of the tuple. fn len(&self) -> usize; /// Checks if the tuple is empty. fn is_empty(&self) -> bool; /// Returns `self` cast as a `PySequence`. fn as_sequence(&self) -> &Bound<'py, PySequence>; /// Returns `self` cast as a `PySequence`. fn into_sequence(self) -> Bound<'py, PySequence>; /// Takes the slice `self[low:high]` and returns it as a new tuple. /// /// Indices must be nonnegative, and out-of-range indices are clipped to /// `self.len()`. fn get_slice(&self, low: usize, high: usize) -> Bound<'py, PyTuple>; /// Gets the tuple item at the specified index. /// # Example /// ``` /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let tuple = (1, 2, 3).into_pyobject(py)?; /// let obj = tuple.get_item(0); /// assert_eq!(obj?.extract::<i32>()?, 1); /// Ok(()) /// }) /// # } /// ``` fn get_item(&self, index: usize) -> PyResult<Bound<'py, PyAny>>; /// Like [`get_item`][PyTupleMethods::get_item], but returns a borrowed object, which is a slight performance optimization /// by avoiding a reference count change. fn get_borrowed_item<'a>(&'a self, index: usize) -> PyResult<Borrowed<'a, 'py, PyAny>>; /// Gets the tuple item at the specified index. Undefined behavior on bad index. Use with caution. /// /// # Safety /// /// Caller must verify that the index is within the bounds of the tuple. #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny>; /// Like [`get_item_unchecked`][PyTupleMethods::get_item_unchecked], but returns a borrowed object, /// which is a slight performance optimization by avoiding a reference count change. /// /// # Safety /// /// Caller must verify that the index is within the bounds of the tuple. #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] unsafe fn get_borrowed_item_unchecked<'a>(&'a self, index: usize) -> Borrowed<'a, 'py, PyAny>; /// Returns `self` as a slice of objects. #[cfg(not(any(Py_LIMITED_API, GraalPy)))] fn as_slice(&self) -> &[Bound<'py, PyAny>]; /// Determines if self contains `value`. /// /// This is equivalent to the Python expression `value in self`. fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>; /// Returns the first index `i` for which `self[i] == value`. /// /// This is equivalent to the Python expression `self.index(value)`. fn index<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>; /// Returns an iterator over the tuple items. fn iter(&self) -> BoundTupleIterator<'py>; /// Like [`iter`][PyTupleMethods::iter], but produces an iterator which returns borrowed objects, /// which is a slight performance optimization by avoiding a reference count change. fn iter_borrowed<'a>(&'a self) -> BorrowedTupleIterator<'a, 'py>; /// Return a new list containing the contents of this tuple; equivalent to the Python expression `list(tuple)`. /// /// This method is equivalent to `self.as_sequence().to_list()` and faster than `PyList::new(py, self)`. fn to_list(&self) -> Bound<'py, PyList>; } impl<'py> PyTupleMethods<'py> for Bound<'py, PyTuple> { fn len(&self) -> usize { unsafe { #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] let size = ffi::PyTuple_GET_SIZE(self.as_ptr()); #[cfg(any(Py_LIMITED_API, PyPy, GraalPy))] let size = ffi::PyTuple_Size(self.as_ptr()); // non-negative Py_ssize_t should always fit into Rust uint size as usize } } fn is_empty(&self) -> bool { self.len() == 0 } fn as_sequence(&self) -> &Bound<'py, PySequence> { unsafe { self.downcast_unchecked() } } fn into_sequence(self) -> Bound<'py, PySequence> { unsafe { self.into_any().downcast_into_unchecked() } } fn get_slice(&self, low: usize, high: usize) -> Bound<'py, PyTuple> { unsafe { ffi::PyTuple_GetSlice(self.as_ptr(), get_ssize_index(low), get_ssize_index(high)) .assume_owned(self.py()) .downcast_into_unchecked() } } fn get_item(&self, index: usize) -> PyResult<Bound<'py, PyAny>> { self.get_borrowed_item(index).map(Borrowed::to_owned) } fn get_borrowed_item<'a>(&'a self, index: usize) -> PyResult<Borrowed<'a, 'py, PyAny>> { self.as_borrowed().get_borrowed_item(index) } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny> { self.get_borrowed_item_unchecked(index).to_owned() } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] unsafe fn get_borrowed_item_unchecked<'a>(&'a self, index: usize) -> Borrowed<'a, 'py, PyAny> { self.as_borrowed().get_borrowed_item_unchecked(index) } #[cfg(not(any(Py_LIMITED_API, GraalPy)))] fn as_slice(&self) -> &[Bound<'py, PyAny>] { // SAFETY: self is known to be a tuple object, and tuples are immutable let items = unsafe { &(*self.as_ptr().cast::<ffi::PyTupleObject>()).ob_item }; // SAFETY: Bound<'py, PyAny> has the same memory layout as *mut ffi::PyObject unsafe { std::slice::from_raw_parts(items.as_ptr().cast(), self.len()) } } #[inline] fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>, { self.as_sequence().contains(value) } #[inline] fn index<V>(&self, value: V) -> PyResult<usize> where V: IntoPyObject<'py>, { self.as_sequence().index(value) } fn iter(&self) -> BoundTupleIterator<'py> { BoundTupleIterator::new(self.clone()) } fn iter_borrowed<'a>(&'a self) -> BorrowedTupleIterator<'a, 'py> { self.as_borrowed().iter_borrowed() } fn to_list(&self) -> Bound<'py, PyList> { self.as_sequence() .to_list() .expect("failed to convert tuple to list") } } impl<'a, 'py> Borrowed<'a, 'py, PyTuple> { fn get_borrowed_item(self, index: usize) -> PyResult<Borrowed<'a, 'py, PyAny>> { unsafe { ffi::PyTuple_GetItem(self.as_ptr(), index as Py_ssize_t) .assume_borrowed_or_err(self.py()) } } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] unsafe fn get_borrowed_item_unchecked(self, index: usize) -> Borrowed<'a, 'py, PyAny> { ffi::PyTuple_GET_ITEM(self.as_ptr(), index as Py_ssize_t).assume_borrowed(self.py()) } pub(crate) fn iter_borrowed(self) -> BorrowedTupleIterator<'a, 'py> { BorrowedTupleIterator::new(self) } } /// Used by `PyTuple::into_iter()`. pub struct BoundTupleIterator<'py> { tuple: Bound<'py, PyTuple>, index: usize, length: usize, } impl<'py> BoundTupleIterator<'py> { fn new(tuple: Bound<'py, PyTuple>) -> Self { let length = tuple.len(); BoundTupleIterator { tuple, index: 0, length, } } } impl<'py> Iterator for BoundTupleIterator<'py> { type Item = Bound<'py, PyAny>; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.index < self.length { let item = unsafe { BorrowedTupleIterator::get_item(self.tuple.as_borrowed(), self.index).to_owned() }; self.index += 1; Some(item) } else { None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } } impl DoubleEndedIterator for BoundTupleIterator<'_> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.index < self.length { let item = unsafe { BorrowedTupleIterator::get_item(self.tuple.as_borrowed(), self.length - 1) .to_owned() }; self.length -= 1; Some(item) } else { None } } } impl ExactSizeIterator for BoundTupleIterator<'_> { fn len(&self) -> usize { self.length.saturating_sub(self.index) } } impl FusedIterator for BoundTupleIterator<'_> {} impl<'py> IntoIterator for Bound<'py, PyTuple> { type Item = Bound<'py, PyAny>; type IntoIter = BoundTupleIterator<'py>; fn into_iter(self) -> Self::IntoIter { BoundTupleIterator::new(self) } } impl<'py> IntoIterator for &Bound<'py, PyTuple> { type Item = Bound<'py, PyAny>; type IntoIter = BoundTupleIterator<'py>; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// Used by `PyTuple::iter_borrowed()`. pub struct BorrowedTupleIterator<'a, 'py> { tuple: Borrowed<'a, 'py, PyTuple>, index: usize, length: usize, } impl<'a, 'py> BorrowedTupleIterator<'a, 'py> { fn new(tuple: Borrowed<'a, 'py, PyTuple>) -> Self { let length = tuple.len(); BorrowedTupleIterator { tuple, index: 0, length, } } unsafe fn get_item( tuple: Borrowed<'a, 'py, PyTuple>, index: usize, ) -> Borrowed<'a, 'py, PyAny> { #[cfg(any(Py_LIMITED_API, PyPy, GraalPy))] let item = tuple.get_borrowed_item(index).expect("tuple.get failed"); #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] let item = tuple.get_borrowed_item_unchecked(index); item } } impl<'a, 'py> Iterator for BorrowedTupleIterator<'a, 'py> { type Item = Borrowed<'a, 'py, PyAny>; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.index < self.length { let item = unsafe { Self::get_item(self.tuple, self.index) }; self.index += 1; Some(item) } else { None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } } impl DoubleEndedIterator for BorrowedTupleIterator<'_, '_> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.index < self.length { let item = unsafe { Self::get_item(self.tuple, self.length - 1) }; self.length -= 1; Some(item) } else { None } } } impl ExactSizeIterator for BorrowedTupleIterator<'_, '_> { fn len(&self) -> usize { self.length.saturating_sub(self.index) } } impl FusedIterator for BorrowedTupleIterator<'_, '_> {} #[allow(deprecated)] impl IntoPy<Py<PyTuple>> for Bound<'_, PyTuple> { fn into_py(self, _: Python<'_>) -> Py<PyTuple> { self.unbind() } } #[allow(deprecated)] impl IntoPy<Py<PyTuple>> for &'_ Bound<'_, PyTuple> { fn into_py(self, _: Python<'_>) -> Py<PyTuple> { self.clone().unbind() } } #[cold] fn wrong_tuple_length(t: &Bound<'_, PyTuple>, expected_length: usize) -> PyErr { let msg = format!( "expected tuple of length {}, but got tuple of length {}", expected_length, t.len() ); exceptions::PyValueError::new_err(msg) } macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => { #[allow(deprecated)] impl <$($T: ToPyObject),+> ToPyObject for ($($T,)+) { fn to_object(&self, py: Python<'_>) -> PyObject { array_into_tuple(py, [$(self.$n.to_object(py)),+]).into() } } #[allow(deprecated)] impl <$($T: IntoPy<PyObject>),+> IntoPy<PyObject> for ($($T,)+) { fn into_py(self, py: Python<'_>) -> PyObject { array_into_tuple(py, [$(self.$n.into_py(py)),+]).into() } } impl <'py, $($T),+> IntoPyObject<'py> for ($($T,)+) where $($T: IntoPyObject<'py>,)+ { type Target = PyTuple; type Output = Bound<'py, Self::Target>; type Error = PyErr; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(array_into_tuple(py, [$(self.$n.into_pyobject(py).map_err(Into::into)?.into_any().unbind()),+]).into_bound(py)) } #[cfg(feature = "experimental-inspect")] fn type_output() -> TypeInfo { TypeInfo::Tuple(Some(vec![$( $T::type_output() ),+])) } } impl <'a, 'py, $($T),+> IntoPyObject<'py> for &'a ($($T,)+) where $(&'a $T: IntoPyObject<'py>,)+ $($T: 'a,)+ // MSRV { type Target = PyTuple; type Output = Bound<'py, Self::Target>; type Error = PyErr; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(array_into_tuple(py, [$(self.$n.into_pyobject(py).map_err(Into::into)?.into_any().unbind()),+]).into_bound(py)) } #[cfg(feature = "experimental-inspect")] fn type_output() -> TypeInfo { TypeInfo::Tuple(Some(vec![$( <&$T>::type_output() ),+])) } } #[allow(deprecated)] impl <$($T: IntoPy<PyObject>),+> IntoPy<Py<PyTuple>> for ($($T,)+) { fn into_py(self, py: Python<'_>) -> Py<PyTuple> { array_into_tuple(py, [$(self.$n.into_py(py)),+]) } } impl<'py, $($T: FromPyObject<'py>),+> FromPyObject<'py> for ($($T,)+) { fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> { let t = obj.downcast::<PyTuple>()?; if t.len() == $length { #[cfg(any(Py_LIMITED_API, PyPy, GraalPy))] return Ok(($(t.get_borrowed_item($n)?.extract::<$T>()?,)+)); #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] unsafe {return Ok(($(t.get_borrowed_item_unchecked($n).extract::<$T>()?,)+));} } else { Err(wrong_tuple_length(t, $length)) } } #[cfg(feature = "experimental-inspect")] fn type_input() -> TypeInfo { TypeInfo::Tuple(Some(vec![$( $T::type_input() ),+])) } } }); fn array_into_tuple<const N: usize>(py: Python<'_>, array: [PyObject; N]) -> Py<PyTuple> { unsafe { let ptr = ffi::PyTuple_New(N.try_into().expect("0 < N <= 12")); let tup = Py::from_owned_ptr(py, ptr); for (index, obj) in array.into_iter().enumerate() { #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] ffi::PyTuple_SET_ITEM(ptr, index as ffi::Py_ssize_t, obj.into_ptr()); #[cfg(any(Py_LIMITED_API, PyPy, GraalPy))] ffi::PyTuple_SetItem(ptr, index as ffi::Py_ssize_t, obj.into_ptr()); } tup } } tuple_conversion!(1, (ref0, 0, T0)); tuple_conversion!(2, (ref0, 0, T0), (ref1, 1, T1)); tuple_conversion!(3, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2)); tuple_conversion!( 4, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3) ); tuple_conversion!( 5, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4) ); tuple_conversion!( 6, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5) ); tuple_conversion!( 7, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5), (ref6, 6, T6) ); tuple_conversion!( 8, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5), (ref6, 6, T6), (ref7, 7, T7) ); tuple_conversion!( 9, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5), (ref6, 6, T6), (ref7, 7, T7), (ref8, 8, T8) ); tuple_conversion!( 10, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5), (ref6, 6, T6), (ref7, 7, T7), (ref8, 8, T8), (ref9, 9, T9) ); tuple_conversion!( 11, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5), (ref6, 6, T6), (ref7, 7, T7), (ref8, 8, T8), (ref9, 9, T9), (ref10, 10, T10) ); tuple_conversion!( 12, (ref0, 0, T0), (ref1, 1, T1), (ref2, 2, T2), (ref3, 3, T3), (ref4, 4, T4), (ref5, 5, T5), (ref6, 6, T6), (ref7, 7, T7), (ref8, 8, T8), (ref9, 9, T9), (ref10, 10, T10), (ref11, 11, T11) ); #[cfg(test)] mod tests { use crate::types::{any::PyAnyMethods, tuple::PyTupleMethods, PyList, PyTuple}; use crate::{IntoPyObject, Python}; use std::collections::HashSet; use std::ops::Range; #[test] fn test_new() { Python::with_gil(|py| { let ob = PyTuple::new(py, [1, 2, 3]).unwrap(); assert_eq!(3, ob.len()); let ob = ob.as_any(); assert_eq!((1, 2, 3), ob.extract().unwrap()); let mut map = HashSet::new(); map.insert(1); map.insert(2); PyTuple::new(py, map).unwrap(); }); } #[test] fn test_len() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); assert_eq!(3, tuple.len()); assert!(!tuple.is_empty()); let ob = tuple.as_any(); assert_eq!((1, 2, 3), ob.extract().unwrap()); }); } #[test] fn test_empty() { Python::with_gil(|py| { let tuple = PyTuple::empty(py); assert!(tuple.is_empty()); assert_eq!(0, tuple.len()); }); } #[test] fn test_slice() { Python::with_gil(|py| { let tup = PyTuple::new(py, [2, 3, 5, 7]).unwrap(); let slice = tup.get_slice(1, 3); assert_eq!(2, slice.len()); let slice = tup.get_slice(1, 7); assert_eq!(3, slice.len()); }); } #[test] fn test_iter() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); assert_eq!(3, tuple.len()); let mut iter = tuple.iter(); assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(1_i32, iter.next().unwrap().extract::<'_, i32>().unwrap()); assert_eq!(iter.size_hint(), (2, Some(2))); assert_eq!(2_i32, iter.next().unwrap().extract::<'_, i32>().unwrap()); assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(3_i32, iter.next().unwrap().extract::<'_, i32>().unwrap()); assert_eq!(iter.size_hint(), (0, Some(0))); assert!(iter.next().is_none()); assert!(iter.next().is_none()); }); } #[test] fn test_iter_rev() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); assert_eq!(3, tuple.len()); let mut iter = tuple.iter().rev(); assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(3_i32, iter.next().unwrap().extract::<'_, i32>().unwrap()); assert_eq!(iter.size_hint(), (2, Some(2))); assert_eq!(2_i32, iter.next().unwrap().extract::<'_, i32>().unwrap()); assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(1_i32, iter.next().unwrap().extract::<'_, i32>().unwrap()); assert_eq!(iter.size_hint(), (0, Some(0))); assert!(iter.next().is_none()); assert!(iter.next().is_none()); }); } #[test] fn test_bound_iter() { Python::with_gil(|py| { let tuple = PyTuple::new(py, [1, 2, 3]).unwrap(); assert_eq!(3, tuple.len()); let mut iter = tuple.iter(); assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(1, iter.next().unwrap().extract::<i32>().unwrap()); assert_eq!(iter.size_hint(), (2, Some(2))); assert_eq!(2, iter.next().unwrap().extract::<i32>().unwrap()); assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(3, iter.next().unwrap().extract::<i32>().unwrap()); assert_eq!(iter.size_hint(), (0, Some(0))); assert!(iter.next().is_none()); assert!(iter.next().is_none()); }); } #[test] fn test_bound_iter_rev() { Python::with_gil(|py| { let tuple = PyTuple::new(py, [1, 2, 3]).unwrap(); assert_eq!(3, tuple.len()); let mut iter = tuple.iter().rev(); assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(3, iter.next().unwrap().extract::<i32>().unwrap()); assert_eq!(iter.size_hint(), (2, Some(2))); assert_eq!(2, iter.next().unwrap().extract::<i32>().unwrap()); assert_eq!(iter.size_hint(), (1, Some(1))); assert_eq!(1, iter.next().unwrap().extract::<i32>().unwrap()); assert_eq!(iter.size_hint(), (0, Some(0))); assert!(iter.next().is_none()); assert!(iter.next().is_none()); }); } #[test] fn test_into_iter() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); assert_eq!(3, tuple.len()); for (i, item) in tuple.iter().enumerate() { assert_eq!(i + 1, item.extract::<'_, usize>().unwrap()); } }); } #[test] fn test_into_iter_bound() { Python::with_gil(|py| { let tuple = (1, 2, 3).into_pyobject(py).unwrap(); assert_eq!(3, tuple.len()); let mut items = vec![]; for item in tuple { items.push(item.extract::<usize>().unwrap()); } assert_eq!(items, vec![1, 2, 3]); }); } #[test] #[cfg(not(any(Py_LIMITED_API, GraalPy)))] fn test_as_slice() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); let slice = tuple.as_slice(); assert_eq!(3, slice.len()); assert_eq!(1_i32, slice[0].extract::<'_, i32>().unwrap()); assert_eq!(2_i32, slice[1].extract::<'_, i32>().unwrap()); assert_eq!(3_i32, slice[2].extract::<'_, i32>().unwrap()); }); } #[test] fn test_tuple_lengths_up_to_12() { Python::with_gil(|py| { let t0 = (0,).into_pyobject(py).unwrap(); let t1 = (0, 1).into_pyobject(py).unwrap(); let t2 = (0, 1, 2).into_pyobject(py).unwrap(); let t3 = (0, 1, 2, 3).into_pyobject(py).unwrap(); let t4 = (0, 1, 2, 3, 4).into_pyobject(py).unwrap(); let t5 = (0, 1, 2, 3, 4, 5).into_pyobject(py).unwrap(); let t6 = (0, 1, 2, 3, 4, 5, 6).into_pyobject(py).unwrap(); let t7 = (0, 1, 2, 3, 4, 5, 6, 7).into_pyobject(py).unwrap(); let t8 = (0, 1, 2, 3, 4, 5, 6, 7, 8).into_pyobject(py).unwrap(); let t9 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).into_pyobject(py).unwrap(); let t10 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .into_pyobject(py) .unwrap(); let t11 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) .into_pyobject(py) .unwrap(); assert_eq!(t0.extract::<(i32,)>().unwrap(), (0,)); assert_eq!(t1.extract::<(i32, i32)>().unwrap(), (0, 1,)); assert_eq!(t2.extract::<(i32, i32, i32)>().unwrap(), (0, 1, 2,)); assert_eq!( t3.extract::<(i32, i32, i32, i32,)>().unwrap(), (0, 1, 2, 3,) ); assert_eq!( t4.extract::<(i32, i32, i32, i32, i32,)>().unwrap(), (0, 1, 2, 3, 4,) ); assert_eq!( t5.extract::<(i32, i32, i32, i32, i32, i32,)>().unwrap(), (0, 1, 2, 3, 4, 5,) ); assert_eq!( t6.extract::<(i32, i32, i32, i32, i32, i32, i32,)>() .unwrap(), (0, 1, 2, 3, 4, 5, 6,) ); assert_eq!( t7.extract::<(i32, i32, i32, i32, i32, i32, i32, i32,)>() .unwrap(), (0, 1, 2, 3, 4, 5, 6, 7,) ); assert_eq!( t8.extract::<(i32, i32, i32, i32, i32, i32, i32, i32, i32,)>() .unwrap(), (0, 1, 2, 3, 4, 5, 6, 7, 8,) ); assert_eq!( t9.extract::<(i32, i32, i32, i32, i32, i32, i32, i32, i32, i32,)>() .unwrap(), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9,) ); assert_eq!( t10.extract::<(i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32,)>() .unwrap(), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,) ); assert_eq!( t11.extract::<(i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32,)>() .unwrap(), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,) ); }) } #[test] fn test_tuple_get_item_invalid_index() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); let obj = tuple.get_item(5); assert!(obj.is_err()); assert_eq!( obj.unwrap_err().to_string(), "IndexError: tuple index out of range" ); }); } #[test] fn test_tuple_get_item_sanity() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); let obj = tuple.get_item(0); assert_eq!(obj.unwrap().extract::<i32>().unwrap(), 1); }); } #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] #[test] fn test_tuple_get_item_unchecked_sanity() { Python::with_gil(|py| { let ob = (1, 2, 3).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); let obj = unsafe { tuple.get_item_unchecked(0) }; assert_eq!(obj.extract::<i32>().unwrap(), 1); }); } #[test] fn test_tuple_contains() { Python::with_gil(|py| { let ob = (1, 1, 2, 3, 5, 8).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); assert_eq!(6, tuple.len()); let bad_needle = 7i32.into_pyobject(py).unwrap(); assert!(!tuple.contains(&bad_needle).unwrap()); let good_needle = 8i32.into_pyobject(py).unwrap(); assert!(tuple.contains(&good_needle).unwrap()); let type_coerced_needle = 8f32.into_pyobject(py).unwrap(); assert!(tuple.contains(&type_coerced_needle).unwrap()); }); } #[test] fn test_tuple_index() { Python::with_gil(|py| { let ob = (1, 1, 2, 3, 5, 8).into_pyobject(py).unwrap(); let tuple = ob.downcast::<PyTuple>().unwrap(); assert_eq!(0, tuple.index(1i32).unwrap()); assert_eq!(2, tuple.index(2i32).unwrap()); assert_eq!(3, tuple.index(3i32).unwrap()); assert_eq!(4, tuple.index(5i32).unwrap()); assert_eq!(5, tuple.index(8i32).unwrap()); assert!(tuple.index(42i32).is_err()); }); } // An iterator that lies about its `ExactSizeIterator` implementation. // See https://github.com/PyO3/pyo3/issues/2118 struct FaultyIter(Range<usize>, usize); impl Iterator for FaultyIter { type Item = usize; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } impl ExactSizeIterator for FaultyIter { fn len(&self) -> usize { self.1 } } #[test] #[should_panic( expected = "Attempted to create PyTuple but `elements` was larger than reported by its `ExactSizeIterator` implementation." )] fn too_long_iterator() { Python::with_gil(|py| { let iter = FaultyIter(0..usize::MAX, 73); let _tuple = PyTuple::new(py, iter); }) } #[test] #[should_panic( expected = "Attempted to create PyTuple but `elements` was smaller than reported by its `ExactSizeIterator` implementation." )] fn too_short_iterator() { Python::with_gil(|py| { let iter = FaultyIter(0..35, 73); let _tuple = PyTuple::new(py, iter); }) } #[test] #[should_panic( expected = "out of range integral type conversion attempted on `elements.len()`" )] fn overflowing_size() { Python::with_gil(|py| { let iter = FaultyIter(0..0, usize::MAX); let _tuple = PyTuple::new(py, iter); }) } #[test] fn bad_intopyobject_doesnt_cause_leaks() { use crate::types::PyInt; use std::convert::Infallible; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; static NEEDS_DESTRUCTING_COUNT: AtomicUsize = AtomicUsize::new(0); struct Bad(usize); impl Drop for Bad { fn drop(&mut self) { NEEDS_DESTRUCTING_COUNT.fetch_sub(1, SeqCst); } } impl<'py> IntoPyObject<'py> for Bad { type Target = PyInt; type Output = crate::Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { // This panic should not lead to a memory leak assert_ne!(self.0, 42); self.0.into_pyobject(py) } } struct FaultyIter(Range<usize>, usize); impl Iterator for FaultyIter { type Item = Bad; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|i| { NEEDS_DESTRUCTING_COUNT.fetch_add(1, SeqCst); Bad(i) }) } } impl ExactSizeIterator for FaultyIter { fn len(&self) -> usize { self.1 } } Python::with_gil(|py| { std::panic::catch_unwind(|| { let iter = FaultyIter(0..50, 50); let _tuple = PyTuple::new(py, iter); }) .unwrap_err(); }); assert_eq!( NEEDS_DESTRUCTING_COUNT.load(SeqCst), 0, "Some destructors did not run" ); } #[test] fn bad_intopyobject_doesnt_cause_leaks_2() { use crate::types::PyInt; use std::convert::Infallible; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; static NEEDS_DESTRUCTING_COUNT: AtomicUsize = AtomicUsize::new(0); struct Bad(usize); impl Drop for Bad { fn drop(&mut self) { NEEDS_DESTRUCTING_COUNT.fetch_sub(1, SeqCst); } } impl<'py> IntoPyObject<'py> for &Bad { type Target = PyInt; type Output = crate::Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { // This panic should not lead to a memory leak assert_ne!(self.0, 3); self.0.into_pyobject(py) } } let s = (Bad(1), Bad(2), Bad(3), Bad(4)); NEEDS_DESTRUCTING_COUNT.store(4, SeqCst); Python::with_gil(|py| { std::panic::catch_unwind(|| { let _tuple = (&s).into_pyobject(py).unwrap(); }) .unwrap_err(); }); drop(s); assert_eq!( NEEDS_DESTRUCTING_COUNT.load(SeqCst), 0, "Some destructors did not run" ); } #[test] fn test_tuple_to_list() { Python::with_gil(|py| { let tuple = PyTuple::new(py, vec![1, 2, 3]).unwrap(); let list = tuple.to_list(); let list_expected = PyList::new(py, vec![1, 2, 3]).unwrap(); assert!(list.eq(list_expected).unwrap()); }) } #[test] fn test_tuple_as_sequence() { Python::with_gil(|py| { let tuple = PyTuple::new(py, vec![1, 2, 3]).unwrap(); let sequence = tuple.as_sequence(); assert!(tuple.get_item(0).unwrap().eq(1).unwrap()); assert!(sequence.get_item(0).unwrap().eq(1).unwrap()); assert_eq!(tuple.len(), 3); assert_eq!(sequence.len().unwrap(), 3); }) } #[test] fn test_tuple_into_sequence() { Python::with_gil(|py| { let tuple = PyTuple::new(py, vec![1, 2, 3]).unwrap(); let sequence = tuple.into_sequence(); assert!(sequence.get_item(0).unwrap().eq(1).unwrap()); assert_eq!(sequence.len().unwrap(), 3); }) } #[test] fn test_bound_tuple_get_item() { Python::with_gil(|py| { let tuple = PyTuple::new(py, vec![1, 2, 3, 4]).unwrap(); assert_eq!(tuple.len(), 4); assert_eq!(tuple.get_item(0).unwrap().extract::<i32>().unwrap(), 1); assert_eq!( tuple .get_borrowed_item(1) .unwrap() .extract::<i32>() .unwrap(), 2 ); #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] { assert_eq!( unsafe { tuple.get_item_unchecked(2) } .extract::<i32>() .unwrap(), 3 ); assert_eq!( unsafe { tuple.get_borrowed_item_unchecked(3) } .extract::<i32>() .unwrap(), 4 ); } }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/set.rs
use crate::conversion::IntoPyObject; use crate::types::PyIterator; #[allow(deprecated)] use crate::ToPyObject; use crate::{ err::{self, PyErr, PyResult}, ffi_ptr_ext::FfiPtrExt, instance::Bound, py_result_ext::PyResultExt, types::any::PyAnyMethods, }; use crate::{ffi, Borrowed, BoundObject, PyAny, Python}; use std::ptr; /// Represents a Python `set`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PySet>`][crate::Py] or [`Bound<'py, PySet>`][Bound]. /// /// For APIs available on `set` objects, see the [`PySetMethods`] trait which is implemented for /// [`Bound<'py, PySet>`][Bound]. #[repr(transparent)] pub struct PySet(PyAny); #[cfg(not(any(PyPy, GraalPy)))] pyobject_subclassable_native_type!(PySet, crate::ffi::PySetObject); #[cfg(not(any(PyPy, GraalPy)))] pyobject_native_type!( PySet, ffi::PySetObject, pyobject_native_static_type_object!(ffi::PySet_Type), #checkfunction=ffi::PySet_Check ); #[cfg(any(PyPy, GraalPy))] pyobject_native_type_core!( PySet, pyobject_native_static_type_object!(ffi::PySet_Type), #checkfunction=ffi::PySet_Check ); impl PySet { /// Creates a new set with elements from the given slice. /// /// Returns an error if some element is not hashable. #[inline] pub fn new<'py, T>( py: Python<'py>, elements: impl IntoIterator<Item = T>, ) -> PyResult<Bound<'py, PySet>> where T: IntoPyObject<'py>, { try_new_from_iter(py, elements) } /// Deprecated name for [`PySet::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PySet::new`")] #[allow(deprecated)] #[inline] pub fn new_bound<'a, 'p, T: ToPyObject + 'a>( py: Python<'p>, elements: impl IntoIterator<Item = &'a T>, ) -> PyResult<Bound<'p, PySet>> { Self::new(py, elements.into_iter().map(|e| e.to_object(py))) } /// Creates a new empty set. pub fn empty(py: Python<'_>) -> PyResult<Bound<'_, PySet>> { unsafe { ffi::PySet_New(ptr::null_mut()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PySet::empty`]. #[deprecated(since = "0.23.0", note = "renamed to `PySet::empty`")] #[inline] pub fn empty_bound(py: Python<'_>) -> PyResult<Bound<'_, PySet>> { Self::empty(py) } } /// Implementation of functionality for [`PySet`]. /// /// These methods are defined for the `Bound<'py, PySet>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PySet")] pub trait PySetMethods<'py>: crate::sealed::Sealed { /// Removes all elements from the set. fn clear(&self); /// Returns the number of items in the set. /// /// This is equivalent to the Python expression `len(self)`. fn len(&self) -> usize; /// Checks if set is empty. fn is_empty(&self) -> bool { self.len() == 0 } /// Determines if the set contains the specified key. /// /// This is equivalent to the Python expression `key in self`. fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>; /// Removes the element from the set if it is present. /// /// Returns `true` if the element was present in the set. fn discard<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>; /// Adds an element to the set. fn add<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>; /// Removes and returns an arbitrary element from the set. fn pop(&self) -> Option<Bound<'py, PyAny>>; /// Returns an iterator of values in this set. /// /// # Panics /// /// If PyO3 detects that the set is mutated during iteration, it will panic. fn iter(&self) -> BoundSetIterator<'py>; } impl<'py> PySetMethods<'py> for Bound<'py, PySet> { #[inline] fn clear(&self) { unsafe { ffi::PySet_Clear(self.as_ptr()); } } #[inline] fn len(&self) -> usize { unsafe { ffi::PySet_Size(self.as_ptr()) as usize } } fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>, { fn inner(set: &Bound<'_, PySet>, key: Borrowed<'_, '_, PyAny>) -> PyResult<bool> { match unsafe { ffi::PySet_Contains(set.as_ptr(), key.as_ptr()) } { 1 => Ok(true), 0 => Ok(false), _ => Err(PyErr::fetch(set.py())), } } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn discard<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>, { fn inner(set: &Bound<'_, PySet>, key: Borrowed<'_, '_, PyAny>) -> PyResult<bool> { match unsafe { ffi::PySet_Discard(set.as_ptr(), key.as_ptr()) } { 1 => Ok(true), 0 => Ok(false), _ => Err(PyErr::fetch(set.py())), } } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn add<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>, { fn inner(set: &Bound<'_, PySet>, key: Borrowed<'_, '_, PyAny>) -> PyResult<()> { err::error_on_minusone(set.py(), unsafe { ffi::PySet_Add(set.as_ptr(), key.as_ptr()) }) } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn pop(&self) -> Option<Bound<'py, PyAny>> { let element = unsafe { ffi::PySet_Pop(self.as_ptr()).assume_owned_or_err(self.py()) }; match element { Ok(e) => Some(e), Err(_) => None, } } fn iter(&self) -> BoundSetIterator<'py> { BoundSetIterator::new(self.clone()) } } impl<'py> IntoIterator for Bound<'py, PySet> { type Item = Bound<'py, PyAny>; type IntoIter = BoundSetIterator<'py>; /// Returns an iterator of values in this set. /// /// # Panics /// /// If PyO3 detects that the set is mutated during iteration, it will panic. fn into_iter(self) -> Self::IntoIter { BoundSetIterator::new(self) } } impl<'py> IntoIterator for &Bound<'py, PySet> { type Item = Bound<'py, PyAny>; type IntoIter = BoundSetIterator<'py>; /// Returns an iterator of values in this set. /// /// # Panics /// /// If PyO3 detects that the set is mutated during iteration, it will panic. fn into_iter(self) -> Self::IntoIter { self.iter() } } /// PyO3 implementation of an iterator for a Python `set` object. pub struct BoundSetIterator<'p> { it: Bound<'p, PyIterator>, // Remaining elements in the set. This is fine to store because // Python will error if the set changes size during iteration. remaining: usize, } impl<'py> BoundSetIterator<'py> { pub(super) fn new(set: Bound<'py, PySet>) -> Self { Self { it: PyIterator::from_object(&set).unwrap(), remaining: set.len(), } } } impl<'py> Iterator for BoundSetIterator<'py> { type Item = Bound<'py, super::PyAny>; /// Advances the iterator and returns the next value. fn next(&mut self) -> Option<Self::Item> { self.remaining = self.remaining.saturating_sub(1); self.it.next().map(Result::unwrap) } fn size_hint(&self) -> (usize, Option<usize>) { (self.remaining, Some(self.remaining)) } } impl ExactSizeIterator for BoundSetIterator<'_> { fn len(&self) -> usize { self.remaining } } #[allow(deprecated)] #[inline] pub(crate) fn new_from_iter<T: ToPyObject>( py: Python<'_>, elements: impl IntoIterator<Item = T>, ) -> PyResult<Bound<'_, PySet>> { let mut iter = elements.into_iter().map(|e| e.to_object(py)); try_new_from_iter(py, &mut iter) } #[inline] pub(crate) fn try_new_from_iter<'py, T>( py: Python<'py>, elements: impl IntoIterator<Item = T>, ) -> PyResult<Bound<'py, PySet>> where T: IntoPyObject<'py>, { let set = unsafe { // We create the `Bound` pointer because its Drop cleans up the set if // user code errors or panics. ffi::PySet_New(std::ptr::null_mut()) .assume_owned_or_err(py)? .downcast_into_unchecked() }; let ptr = set.as_ptr(); elements.into_iter().try_for_each(|element| { let obj = element.into_pyobject(py).map_err(Into::into)?; err::error_on_minusone(py, unsafe { ffi::PySet_Add(ptr, obj.as_ptr()) }) })?; Ok(set) } #[cfg(test)] mod tests { use super::PySet; use crate::{ conversion::IntoPyObject, ffi, types::{PyAnyMethods, PySetMethods}, Python, }; use std::collections::HashSet; #[test] fn test_set_new() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); assert_eq!(1, set.len()); let v = vec![1]; assert!(PySet::new(py, &[v]).is_err()); }); } #[test] fn test_set_empty() { Python::with_gil(|py| { let set = PySet::empty(py).unwrap(); assert_eq!(0, set.len()); assert!(set.is_empty()); }); } #[test] fn test_set_len() { Python::with_gil(|py| { let mut v = HashSet::<i32>::new(); let ob = (&v).into_pyobject(py).unwrap(); let set = ob.downcast::<PySet>().unwrap(); assert_eq!(0, set.len()); v.insert(7); let ob = v.into_pyobject(py).unwrap(); let set2 = ob.downcast::<PySet>().unwrap(); assert_eq!(1, set2.len()); }); } #[test] fn test_set_clear() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); assert_eq!(1, set.len()); set.clear(); assert_eq!(0, set.len()); }); } #[test] fn test_set_contains() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); assert!(set.contains(1).unwrap()); }); } #[test] fn test_set_discard() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); assert!(!set.discard(2).unwrap()); assert_eq!(1, set.len()); assert!(set.discard(1).unwrap()); assert_eq!(0, set.len()); assert!(!set.discard(1).unwrap()); assert!(set.discard(vec![1, 2]).is_err()); }); } #[test] fn test_set_add() { Python::with_gil(|py| { let set = PySet::new(py, [1, 2]).unwrap(); set.add(1).unwrap(); // Add a dupliated element assert!(set.contains(1).unwrap()); }); } #[test] fn test_set_pop() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); let val = set.pop(); assert!(val.is_some()); let val2 = set.pop(); assert!(val2.is_none()); assert!(py .eval( ffi::c_str!("print('Exception state should not be set.')"), None, None ) .is_ok()); }); } #[test] fn test_set_iter() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); for el in set { assert_eq!(1i32, el.extract::<'_, i32>().unwrap()); } }); } #[test] fn test_set_iter_bound() { use crate::types::any::PyAnyMethods; Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); for el in &set { assert_eq!(1i32, el.extract::<i32>().unwrap()); } }); } #[test] #[should_panic] fn test_set_iter_mutation() { Python::with_gil(|py| { let set = PySet::new(py, [1, 2, 3, 4, 5]).unwrap(); for _ in &set { let _ = set.add(42); } }); } #[test] #[should_panic] fn test_set_iter_mutation_same_len() { Python::with_gil(|py| { let set = PySet::new(py, [1, 2, 3, 4, 5]).unwrap(); for item in &set { let item: i32 = item.extract().unwrap(); let _ = set.del_item(item); let _ = set.add(item + 10); } }); } #[test] fn test_set_iter_size_hint() { Python::with_gil(|py| { let set = PySet::new(py, [1]).unwrap(); let mut iter = set.iter(); // Exact size assert_eq!(iter.len(), 1); assert_eq!(iter.size_hint(), (1, Some(1))); iter.next(); assert_eq!(iter.len(), 0); assert_eq!(iter.size_hint(), (0, Some(0))); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/datetime.rs
//! Safe Rust wrappers for types defined in the Python `datetime` library //! //! For more details about these types, see the [Python //! documentation](https://docs.python.org/3/library/datetime.html) use crate::err::PyResult; use crate::ffi::{ self, PyDateTime_CAPI, PyDateTime_FromTimestamp, PyDateTime_IMPORT, PyDate_FromTimestamp, }; use crate::ffi::{ PyDateTime_DATE_GET_FOLD, PyDateTime_DATE_GET_HOUR, PyDateTime_DATE_GET_MICROSECOND, PyDateTime_DATE_GET_MINUTE, PyDateTime_DATE_GET_SECOND, }; #[cfg(GraalPy)] use crate::ffi::{PyDateTime_DATE_GET_TZINFO, PyDateTime_TIME_GET_TZINFO, Py_IsNone}; use crate::ffi::{ PyDateTime_DELTA_GET_DAYS, PyDateTime_DELTA_GET_MICROSECONDS, PyDateTime_DELTA_GET_SECONDS, }; use crate::ffi::{PyDateTime_GET_DAY, PyDateTime_GET_MONTH, PyDateTime_GET_YEAR}; use crate::ffi::{ PyDateTime_TIME_GET_FOLD, PyDateTime_TIME_GET_HOUR, PyDateTime_TIME_GET_MICROSECOND, PyDateTime_TIME_GET_MINUTE, PyDateTime_TIME_GET_SECOND, }; use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::types::any::PyAnyMethods; use crate::types::PyTuple; use crate::{Bound, IntoPyObject, PyAny, PyErr, Python}; use std::os::raw::c_int; #[cfg(feature = "chrono")] use std::ptr; fn ensure_datetime_api(py: Python<'_>) -> PyResult<&'static PyDateTime_CAPI> { if let Some(api) = unsafe { pyo3_ffi::PyDateTimeAPI().as_ref() } { Ok(api) } else { unsafe { PyDateTime_IMPORT(); pyo3_ffi::PyDateTimeAPI().as_ref() } .ok_or_else(|| PyErr::fetch(py)) } } fn expect_datetime_api(py: Python<'_>) -> &'static PyDateTime_CAPI { ensure_datetime_api(py).expect("failed to import `datetime` C API") } // Type Check macros // // These are bindings around the C API typecheck macros, all of them return // `1` if True and `0` if False. In all type check macros, the argument (`op`) // must not be `NULL`. The implementations here all call ensure_datetime_api // to ensure that the PyDateTimeAPI is initialized before use // // // # Safety // // These functions must only be called when the GIL is held! macro_rules! ffi_fun_with_autoinit { ($(#[$outer:meta] unsafe fn $name: ident($arg: ident: *mut PyObject) -> $ret: ty;)*) => { $( #[$outer] #[allow(non_snake_case)] /// # Safety /// /// Must only be called while the GIL is held unsafe fn $name($arg: *mut crate::ffi::PyObject) -> $ret { let _ = ensure_datetime_api(Python::assume_gil_acquired()); crate::ffi::$name($arg) } )* }; } ffi_fun_with_autoinit! { /// Check if `op` is a `PyDateTimeAPI.DateType` or subtype. unsafe fn PyDate_Check(op: *mut PyObject) -> c_int; /// Check if `op` is a `PyDateTimeAPI.DateTimeType` or subtype. unsafe fn PyDateTime_Check(op: *mut PyObject) -> c_int; /// Check if `op` is a `PyDateTimeAPI.TimeType` or subtype. unsafe fn PyTime_Check(op: *mut PyObject) -> c_int; /// Check if `op` is a `PyDateTimeAPI.DetaType` or subtype. unsafe fn PyDelta_Check(op: *mut PyObject) -> c_int; /// Check if `op` is a `PyDateTimeAPI.TZInfoType` or subtype. unsafe fn PyTZInfo_Check(op: *mut PyObject) -> c_int; } // Access traits /// Trait for accessing the date components of a struct containing a date. pub trait PyDateAccess { /// Returns the year, as a positive int. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_GET_YEAR> fn get_year(&self) -> i32; /// Returns the month, as an int from 1 through 12. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_GET_MONTH> fn get_month(&self) -> u8; /// Returns the day, as an int from 1 through 31. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_GET_DAY> fn get_day(&self) -> u8; } /// Trait for accessing the components of a struct containing a timedelta. /// /// Note: These access the individual components of a (day, second, /// microsecond) representation of the delta, they are *not* intended as /// aliases for calculating the total duration in each of these units. pub trait PyDeltaAccess { /// Returns the number of days, as an int from -999999999 to 999999999. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DELTA_GET_DAYS> fn get_days(&self) -> i32; /// Returns the number of seconds, as an int from 0 through 86399. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DELTA_GET_DAYS> fn get_seconds(&self) -> i32; /// Returns the number of microseconds, as an int from 0 through 999999. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DELTA_GET_DAYS> fn get_microseconds(&self) -> i32; } /// Trait for accessing the time components of a struct containing a time. pub trait PyTimeAccess { /// Returns the hour, as an int from 0 through 23. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DATE_GET_HOUR> fn get_hour(&self) -> u8; /// Returns the minute, as an int from 0 through 59. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DATE_GET_MINUTE> fn get_minute(&self) -> u8; /// Returns the second, as an int from 0 through 59. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DATE_GET_SECOND> fn get_second(&self) -> u8; /// Returns the microsecond, as an int from 0 through 999999. /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DATE_GET_MICROSECOND> fn get_microsecond(&self) -> u32; /// Returns whether this date is the later of two moments with the /// same representation, during a repeated interval. /// /// This typically occurs at the end of daylight savings time. Only valid if the /// represented time is ambiguous. /// See [PEP 495](https://www.python.org/dev/peps/pep-0495/) for more detail. fn get_fold(&self) -> bool; } /// Trait for accessing the components of a struct containing a tzinfo. pub trait PyTzInfoAccess<'py> { /// Returns the tzinfo (which may be None). /// /// Implementations should conform to the upstream documentation: /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DATE_GET_TZINFO> /// <https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_TIME_GET_TZINFO> fn get_tzinfo(&self) -> Option<Bound<'py, PyTzInfo>>; /// Deprecated name for [`PyTzInfoAccess::get_tzinfo`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTzInfoAccess::get_tzinfo`")] #[inline] fn get_tzinfo_bound(&self) -> Option<Bound<'py, PyTzInfo>> { self.get_tzinfo() } } /// Bindings around `datetime.date`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyDate>`][crate::Py] or [`Bound<'py, PyDate>`][Bound]. #[repr(transparent)] pub struct PyDate(PyAny); pyobject_native_type!( PyDate, crate::ffi::PyDateTime_Date, |py| expect_datetime_api(py).DateType, #module=Some("datetime"), #checkfunction=PyDate_Check ); pyobject_subclassable_native_type!(PyDate, crate::ffi::PyDateTime_Date); impl PyDate { /// Creates a new `datetime.date`. pub fn new(py: Python<'_>, year: i32, month: u8, day: u8) -> PyResult<Bound<'_, PyDate>> { let api = ensure_datetime_api(py)?; unsafe { (api.Date_FromDate)(year, c_int::from(month), c_int::from(day), api.DateType) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyDate::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDate::new`")] #[inline] pub fn new_bound(py: Python<'_>, year: i32, month: u8, day: u8) -> PyResult<Bound<'_, PyDate>> { Self::new(py, year, month, day) } /// Construct a `datetime.date` from a POSIX timestamp /// /// This is equivalent to `datetime.date.fromtimestamp` pub fn from_timestamp(py: Python<'_>, timestamp: i64) -> PyResult<Bound<'_, PyDate>> { let time_tuple = PyTuple::new(py, [timestamp])?; // safety ensure that the API is loaded let _api = ensure_datetime_api(py)?; unsafe { PyDate_FromTimestamp(time_tuple.as_ptr()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyDate::from_timestamp`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDate::from_timestamp`")] #[inline] pub fn from_timestamp_bound(py: Python<'_>, timestamp: i64) -> PyResult<Bound<'_, PyDate>> { Self::from_timestamp(py, timestamp) } } impl PyDateAccess for Bound<'_, PyDate> { fn get_year(&self) -> i32 { unsafe { PyDateTime_GET_YEAR(self.as_ptr()) } } fn get_month(&self) -> u8 { unsafe { PyDateTime_GET_MONTH(self.as_ptr()) as u8 } } fn get_day(&self) -> u8 { unsafe { PyDateTime_GET_DAY(self.as_ptr()) as u8 } } } /// Bindings for `datetime.datetime`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyDateTime>`][crate::Py] or [`Bound<'py, PyDateTime>`][Bound]. #[repr(transparent)] pub struct PyDateTime(PyAny); pyobject_native_type!( PyDateTime, crate::ffi::PyDateTime_DateTime, |py| expect_datetime_api(py).DateTimeType, #module=Some("datetime"), #checkfunction=PyDateTime_Check ); pyobject_subclassable_native_type!(PyDateTime, crate::ffi::PyDateTime_DateTime); impl PyDateTime { /// Creates a new `datetime.datetime` object. #[allow(clippy::too_many_arguments)] pub fn new<'py>( py: Python<'py>, year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, ) -> PyResult<Bound<'py, PyDateTime>> { let api = ensure_datetime_api(py)?; unsafe { (api.DateTime_FromDateAndTime)( year, c_int::from(month), c_int::from(day), c_int::from(hour), c_int::from(minute), c_int::from(second), microsecond as c_int, opt_to_pyobj(tzinfo), api.DateTimeType, ) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyDateTime::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDateTime::new`")] #[inline] #[allow(clippy::too_many_arguments)] pub fn new_bound<'py>( py: Python<'py>, year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, ) -> PyResult<Bound<'py, PyDateTime>> { Self::new( py, year, month, day, hour, minute, second, microsecond, tzinfo, ) } /// Alternate constructor that takes a `fold` parameter. A `true` value for this parameter /// signifies this this datetime is the later of two moments with the same representation, /// during a repeated interval. /// /// This typically occurs at the end of daylight savings time. Only valid if the /// represented time is ambiguous. /// See [PEP 495](https://www.python.org/dev/peps/pep-0495/) for more detail. #[allow(clippy::too_many_arguments)] pub fn new_with_fold<'py>( py: Python<'py>, year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, fold: bool, ) -> PyResult<Bound<'py, PyDateTime>> { let api = ensure_datetime_api(py)?; unsafe { (api.DateTime_FromDateAndTimeAndFold)( year, c_int::from(month), c_int::from(day), c_int::from(hour), c_int::from(minute), c_int::from(second), microsecond as c_int, opt_to_pyobj(tzinfo), c_int::from(fold), api.DateTimeType, ) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyDateTime::new_with_fold`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDateTime::new_with_fold`")] #[inline] #[allow(clippy::too_many_arguments)] pub fn new_bound_with_fold<'py>( py: Python<'py>, year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, fold: bool, ) -> PyResult<Bound<'py, PyDateTime>> { Self::new_with_fold( py, year, month, day, hour, minute, second, microsecond, tzinfo, fold, ) } /// Construct a `datetime` object from a POSIX timestamp /// /// This is equivalent to `datetime.datetime.fromtimestamp` pub fn from_timestamp<'py>( py: Python<'py>, timestamp: f64, tzinfo: Option<&Bound<'py, PyTzInfo>>, ) -> PyResult<Bound<'py, PyDateTime>> { let args = (timestamp, tzinfo).into_pyobject(py)?; // safety ensure API is loaded let _api = ensure_datetime_api(py)?; unsafe { PyDateTime_FromTimestamp(args.as_ptr()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyDateTime::from_timestamp`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDateTime::from_timestamp`")] #[inline] pub fn from_timestamp_bound<'py>( py: Python<'py>, timestamp: f64, tzinfo: Option<&Bound<'py, PyTzInfo>>, ) -> PyResult<Bound<'py, PyDateTime>> { Self::from_timestamp(py, timestamp, tzinfo) } } impl PyDateAccess for Bound<'_, PyDateTime> { fn get_year(&self) -> i32 { unsafe { PyDateTime_GET_YEAR(self.as_ptr()) } } fn get_month(&self) -> u8 { unsafe { PyDateTime_GET_MONTH(self.as_ptr()) as u8 } } fn get_day(&self) -> u8 { unsafe { PyDateTime_GET_DAY(self.as_ptr()) as u8 } } } impl PyTimeAccess for Bound<'_, PyDateTime> { fn get_hour(&self) -> u8 { unsafe { PyDateTime_DATE_GET_HOUR(self.as_ptr()) as u8 } } fn get_minute(&self) -> u8 { unsafe { PyDateTime_DATE_GET_MINUTE(self.as_ptr()) as u8 } } fn get_second(&self) -> u8 { unsafe { PyDateTime_DATE_GET_SECOND(self.as_ptr()) as u8 } } fn get_microsecond(&self) -> u32 { unsafe { PyDateTime_DATE_GET_MICROSECOND(self.as_ptr()) as u32 } } fn get_fold(&self) -> bool { unsafe { PyDateTime_DATE_GET_FOLD(self.as_ptr()) > 0 } } } impl<'py> PyTzInfoAccess<'py> for Bound<'py, PyDateTime> { fn get_tzinfo(&self) -> Option<Bound<'py, PyTzInfo>> { let ptr = self.as_ptr() as *mut ffi::PyDateTime_DateTime; #[cfg(not(GraalPy))] unsafe { if (*ptr).hastzinfo != 0 { Some( (*ptr) .tzinfo .assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked(), ) } else { None } } #[cfg(GraalPy)] unsafe { let res = PyDateTime_DATE_GET_TZINFO(ptr as *mut ffi::PyObject); if Py_IsNone(res) == 1 { None } else { Some( res.assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked(), ) } } } } /// Bindings for `datetime.time`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyTime>`][crate::Py] or [`Bound<'py, PyTime>`][Bound]. #[repr(transparent)] pub struct PyTime(PyAny); pyobject_native_type!( PyTime, crate::ffi::PyDateTime_Time, |py| expect_datetime_api(py).TimeType, #module=Some("datetime"), #checkfunction=PyTime_Check ); pyobject_subclassable_native_type!(PyTime, crate::ffi::PyDateTime_Time); impl PyTime { /// Creates a new `datetime.time` object. pub fn new<'py>( py: Python<'py>, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, ) -> PyResult<Bound<'py, PyTime>> { let api = ensure_datetime_api(py)?; unsafe { (api.Time_FromTime)( c_int::from(hour), c_int::from(minute), c_int::from(second), microsecond as c_int, opt_to_pyobj(tzinfo), api.TimeType, ) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyTime::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTime::new`")] #[inline] pub fn new_bound<'py>( py: Python<'py>, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, ) -> PyResult<Bound<'py, PyTime>> { Self::new(py, hour, minute, second, microsecond, tzinfo) } /// Alternate constructor that takes a `fold` argument. See [`PyDateTime::new_bound_with_fold`]. pub fn new_with_fold<'py>( py: Python<'py>, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, fold: bool, ) -> PyResult<Bound<'py, PyTime>> { let api = ensure_datetime_api(py)?; unsafe { (api.Time_FromTimeAndFold)( c_int::from(hour), c_int::from(minute), c_int::from(second), microsecond as c_int, opt_to_pyobj(tzinfo), fold as c_int, api.TimeType, ) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyTime::new_with_fold`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTime::new_with_fold`")] #[inline] pub fn new_bound_with_fold<'py>( py: Python<'py>, hour: u8, minute: u8, second: u8, microsecond: u32, tzinfo: Option<&Bound<'py, PyTzInfo>>, fold: bool, ) -> PyResult<Bound<'py, PyTime>> { Self::new_with_fold(py, hour, minute, second, microsecond, tzinfo, fold) } } impl PyTimeAccess for Bound<'_, PyTime> { fn get_hour(&self) -> u8 { unsafe { PyDateTime_TIME_GET_HOUR(self.as_ptr()) as u8 } } fn get_minute(&self) -> u8 { unsafe { PyDateTime_TIME_GET_MINUTE(self.as_ptr()) as u8 } } fn get_second(&self) -> u8 { unsafe { PyDateTime_TIME_GET_SECOND(self.as_ptr()) as u8 } } fn get_microsecond(&self) -> u32 { unsafe { PyDateTime_TIME_GET_MICROSECOND(self.as_ptr()) as u32 } } fn get_fold(&self) -> bool { unsafe { PyDateTime_TIME_GET_FOLD(self.as_ptr()) != 0 } } } impl<'py> PyTzInfoAccess<'py> for Bound<'py, PyTime> { fn get_tzinfo(&self) -> Option<Bound<'py, PyTzInfo>> { let ptr = self.as_ptr() as *mut ffi::PyDateTime_Time; #[cfg(not(GraalPy))] unsafe { if (*ptr).hastzinfo != 0 { Some( (*ptr) .tzinfo .assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked(), ) } else { None } } #[cfg(GraalPy)] unsafe { let res = PyDateTime_TIME_GET_TZINFO(ptr as *mut ffi::PyObject); if Py_IsNone(res) == 1 { None } else { Some( res.assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked(), ) } } } } /// Bindings for `datetime.tzinfo`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyTzInfo>`][crate::Py] or [`Bound<'py, PyTzInfo>`][Bound]. /// /// This is an abstract base class and cannot be constructed directly. /// For concrete time zone implementations, see [`timezone_utc_bound`] and /// the [`zoneinfo` module](https://docs.python.org/3/library/zoneinfo.html). #[repr(transparent)] pub struct PyTzInfo(PyAny); pyobject_native_type!( PyTzInfo, crate::ffi::PyObject, |py| expect_datetime_api(py).TZInfoType, #module=Some("datetime"), #checkfunction=PyTZInfo_Check ); pyobject_subclassable_native_type!(PyTzInfo, crate::ffi::PyObject); /// Equivalent to `datetime.timezone.utc` pub fn timezone_utc(py: Python<'_>) -> Bound<'_, PyTzInfo> { // TODO: this _could_ have a borrowed form `timezone_utc_borrowed`, but that seems // like an edge case optimization and we'd prefer in PyO3 0.21 to use `Bound` as // much as possible unsafe { expect_datetime_api(py) .TimeZone_UTC .assume_borrowed(py) .to_owned() .downcast_into_unchecked() } } /// Deprecated name for [`timezone_utc`]. #[deprecated(since = "0.23.0", note = "renamed to `timezone_utc`")] #[inline] pub fn timezone_utc_bound(py: Python<'_>) -> Bound<'_, PyTzInfo> { timezone_utc(py) } /// Equivalent to `datetime.timezone` constructor /// /// Only used internally #[cfg(feature = "chrono")] pub(crate) fn timezone_from_offset<'py>( offset: &Bound<'py, PyDelta>, ) -> PyResult<Bound<'py, PyTzInfo>> { let py = offset.py(); let api = ensure_datetime_api(py)?; unsafe { (api.TimeZone_FromTimeZone)(offset.as_ptr(), ptr::null_mut()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Bindings for `datetime.timedelta`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyDelta>`][crate::Py] or [`Bound<'py, PyDelta>`][Bound]. #[repr(transparent)] pub struct PyDelta(PyAny); pyobject_native_type!( PyDelta, crate::ffi::PyDateTime_Delta, |py| expect_datetime_api(py).DeltaType, #module=Some("datetime"), #checkfunction=PyDelta_Check ); pyobject_subclassable_native_type!(PyDelta, crate::ffi::PyDateTime_Delta); impl PyDelta { /// Creates a new `timedelta`. pub fn new( py: Python<'_>, days: i32, seconds: i32, microseconds: i32, normalize: bool, ) -> PyResult<Bound<'_, PyDelta>> { let api = ensure_datetime_api(py)?; unsafe { (api.Delta_FromDelta)( days as c_int, seconds as c_int, microseconds as c_int, normalize as c_int, api.DeltaType, ) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyDelta::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDelta::new`")] #[inline] pub fn new_bound( py: Python<'_>, days: i32, seconds: i32, microseconds: i32, normalize: bool, ) -> PyResult<Bound<'_, PyDelta>> { Self::new(py, days, seconds, microseconds, normalize) } } impl PyDeltaAccess for Bound<'_, PyDelta> { fn get_days(&self) -> i32 { unsafe { PyDateTime_DELTA_GET_DAYS(self.as_ptr()) } } fn get_seconds(&self) -> i32 { unsafe { PyDateTime_DELTA_GET_SECONDS(self.as_ptr()) } } fn get_microseconds(&self) -> i32 { unsafe { PyDateTime_DELTA_GET_MICROSECONDS(self.as_ptr()) } } } // Utility function which returns a borrowed reference to either // the underlying tzinfo or None. fn opt_to_pyobj(opt: Option<&Bound<'_, PyTzInfo>>) -> *mut ffi::PyObject { match opt { Some(tzi) => tzi.as_ptr(), None => unsafe { ffi::Py_None() }, } } #[cfg(test)] mod tests { use super::*; #[cfg(feature = "macros")] use crate::py_run; #[test] #[cfg(feature = "macros")] #[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons fn test_datetime_fromtimestamp() { Python::with_gil(|py| { let dt = PyDateTime::from_timestamp(py, 100.0, None).unwrap(); py_run!( py, dt, "import datetime; assert dt == datetime.datetime.fromtimestamp(100)" ); let dt = PyDateTime::from_timestamp(py, 100.0, Some(&timezone_utc(py))).unwrap(); py_run!( py, dt, "import datetime; assert dt == datetime.datetime.fromtimestamp(100, datetime.timezone.utc)" ); }) } #[test] #[cfg(feature = "macros")] #[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons fn test_date_fromtimestamp() { Python::with_gil(|py| { let dt = PyDate::from_timestamp(py, 100).unwrap(); py_run!( py, dt, "import datetime; assert dt == datetime.date.fromtimestamp(100)" ); }) } #[test] #[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons fn test_new_with_fold() { Python::with_gil(|py| { let a = PyDateTime::new_with_fold(py, 2021, 1, 23, 20, 32, 40, 341516, None, false); let b = PyDateTime::new_with_fold(py, 2021, 1, 23, 20, 32, 40, 341516, None, true); assert!(!a.unwrap().get_fold()); assert!(b.unwrap().get_fold()); }); } #[test] #[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons fn test_get_tzinfo() { crate::Python::with_gil(|py| { let utc = timezone_utc(py); let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, Some(&utc)).unwrap(); assert!(dt.get_tzinfo().unwrap().eq(&utc).unwrap()); let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, None).unwrap(); assert!(dt.get_tzinfo().is_none()); let t = PyTime::new(py, 0, 0, 0, 0, Some(&utc)).unwrap(); assert!(t.get_tzinfo().unwrap().eq(utc).unwrap()); let t = PyTime::new(py, 0, 0, 0, 0, None).unwrap(); assert!(t.get_tzinfo().is_none()); }); } #[test] #[cfg(all(feature = "macros", feature = "chrono"))] #[cfg_attr(target_arch = "wasm32", ignore)] // DateTime import fails on wasm for mysterious reasons fn test_timezone_from_offset() { use crate::types::PyNone; Python::with_gil(|py| { assert!( timezone_from_offset(&PyDelta::new(py, 0, -3600, 0, true).unwrap()) .unwrap() .call_method1("utcoffset", (PyNone::get(py),)) .unwrap() .downcast_into::<PyDelta>() .unwrap() .eq(PyDelta::new(py, 0, -3600, 0, true).unwrap()) .unwrap() ); assert!( timezone_from_offset(&PyDelta::new(py, 0, 3600, 0, true).unwrap()) .unwrap() .call_method1("utcoffset", (PyNone::get(py),)) .unwrap() .downcast_into::<PyDelta>() .unwrap() .eq(PyDelta::new(py, 0, 3600, 0, true).unwrap()) .unwrap() ); timezone_from_offset(&PyDelta::new(py, 1, 0, 0, true).unwrap()).unwrap_err(); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/frozenset.rs
use crate::conversion::IntoPyObject; use crate::types::PyIterator; use crate::{ err::{self, PyErr, PyResult}, ffi, ffi_ptr_ext::FfiPtrExt, py_result_ext::PyResultExt, types::any::PyAnyMethods, Bound, PyAny, Python, }; use crate::{Borrowed, BoundObject}; use std::ptr; /// Allows building a Python `frozenset` one item at a time pub struct PyFrozenSetBuilder<'py> { py_frozen_set: Bound<'py, PyFrozenSet>, } impl<'py> PyFrozenSetBuilder<'py> { /// Create a new `FrozenSetBuilder`. /// Since this allocates a `PyFrozenSet` internally it may /// panic when running out of memory. pub fn new(py: Python<'py>) -> PyResult<PyFrozenSetBuilder<'py>> { Ok(PyFrozenSetBuilder { py_frozen_set: PyFrozenSet::empty(py)?, }) } /// Adds an element to the set. pub fn add<K>(&mut self, key: K) -> PyResult<()> where K: IntoPyObject<'py>, { fn inner(frozenset: &Bound<'_, PyFrozenSet>, key: Borrowed<'_, '_, PyAny>) -> PyResult<()> { err::error_on_minusone(frozenset.py(), unsafe { ffi::PySet_Add(frozenset.as_ptr(), key.as_ptr()) }) } inner( &self.py_frozen_set, key.into_pyobject(self.py_frozen_set.py()) .map_err(Into::into)? .into_any() .as_borrowed(), ) } /// Finish building the set and take ownership of its current value pub fn finalize(self) -> Bound<'py, PyFrozenSet> { self.py_frozen_set } /// Deprecated name for [`PyFrozenSetBuilder::finalize`]. #[deprecated(since = "0.23.0", note = "renamed to `PyFrozenSetBuilder::finalize`")] #[inline] pub fn finalize_bound(self) -> Bound<'py, PyFrozenSet> { self.finalize() } } /// Represents a Python `frozenset`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyFrozenSet>`][crate::Py] or [`Bound<'py, PyFrozenSet>`][Bound]. /// /// For APIs available on `frozenset` objects, see the [`PyFrozenSetMethods`] trait which is implemented for /// [`Bound<'py, PyFrozenSet>`][Bound]. #[repr(transparent)] pub struct PyFrozenSet(PyAny); #[cfg(not(any(PyPy, GraalPy)))] pyobject_subclassable_native_type!(PyFrozenSet, crate::ffi::PySetObject); #[cfg(not(any(PyPy, GraalPy)))] pyobject_native_type!( PyFrozenSet, ffi::PySetObject, pyobject_native_static_type_object!(ffi::PyFrozenSet_Type), #checkfunction=ffi::PyFrozenSet_Check ); #[cfg(any(PyPy, GraalPy))] pyobject_native_type_core!( PyFrozenSet, pyobject_native_static_type_object!(ffi::PyFrozenSet_Type), #checkfunction=ffi::PyFrozenSet_Check ); impl PyFrozenSet { /// Creates a new frozenset. /// /// May panic when running out of memory. #[inline] pub fn new<'py, T>( py: Python<'py>, elements: impl IntoIterator<Item = T>, ) -> PyResult<Bound<'py, PyFrozenSet>> where T: IntoPyObject<'py>, { try_new_from_iter(py, elements) } /// Deprecated name for [`PyFrozenSet::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyFrozenSet::new`")] #[allow(deprecated)] #[inline] pub fn new_bound<'a, 'p, T: crate::ToPyObject + 'a>( py: Python<'p>, elements: impl IntoIterator<Item = &'a T>, ) -> PyResult<Bound<'p, PyFrozenSet>> { Self::new(py, elements.into_iter().map(|e| e.to_object(py))) } /// Creates a new empty frozen set pub fn empty(py: Python<'_>) -> PyResult<Bound<'_, PyFrozenSet>> { unsafe { ffi::PyFrozenSet_New(ptr::null_mut()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyFrozenSet::empty`]. #[deprecated(since = "0.23.0", note = "renamed to `PyFrozenSet::empty`")] #[inline] pub fn empty_bound(py: Python<'_>) -> PyResult<Bound<'_, PyFrozenSet>> { Self::empty(py) } } /// Implementation of functionality for [`PyFrozenSet`]. /// /// These methods are defined for the `Bound<'py, PyFrozenSet>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyFrozenSet")] pub trait PyFrozenSetMethods<'py>: crate::sealed::Sealed { /// Returns the number of items in the set. /// /// This is equivalent to the Python expression `len(self)`. fn len(&self) -> usize; /// Checks if set is empty. fn is_empty(&self) -> bool { self.len() == 0 } /// Determines if the set contains the specified key. /// /// This is equivalent to the Python expression `key in self`. fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>; /// Returns an iterator of values in this set. fn iter(&self) -> BoundFrozenSetIterator<'py>; } impl<'py> PyFrozenSetMethods<'py> for Bound<'py, PyFrozenSet> { #[inline] fn len(&self) -> usize { unsafe { ffi::PySet_Size(self.as_ptr()) as usize } } fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>, { fn inner( frozenset: &Bound<'_, PyFrozenSet>, key: Borrowed<'_, '_, PyAny>, ) -> PyResult<bool> { match unsafe { ffi::PySet_Contains(frozenset.as_ptr(), key.as_ptr()) } { 1 => Ok(true), 0 => Ok(false), _ => Err(PyErr::fetch(frozenset.py())), } } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn iter(&self) -> BoundFrozenSetIterator<'py> { BoundFrozenSetIterator::new(self.clone()) } } impl<'py> IntoIterator for Bound<'py, PyFrozenSet> { type Item = Bound<'py, PyAny>; type IntoIter = BoundFrozenSetIterator<'py>; /// Returns an iterator of values in this set. fn into_iter(self) -> Self::IntoIter { BoundFrozenSetIterator::new(self) } } impl<'py> IntoIterator for &Bound<'py, PyFrozenSet> { type Item = Bound<'py, PyAny>; type IntoIter = BoundFrozenSetIterator<'py>; /// Returns an iterator of values in this set. fn into_iter(self) -> Self::IntoIter { self.iter() } } /// PyO3 implementation of an iterator for a Python `frozenset` object. pub struct BoundFrozenSetIterator<'p> { it: Bound<'p, PyIterator>, // Remaining elements in the frozenset remaining: usize, } impl<'py> BoundFrozenSetIterator<'py> { pub(super) fn new(set: Bound<'py, PyFrozenSet>) -> Self { Self { it: PyIterator::from_object(&set).unwrap(), remaining: set.len(), } } } impl<'py> Iterator for BoundFrozenSetIterator<'py> { type Item = Bound<'py, super::PyAny>; /// Advances the iterator and returns the next value. fn next(&mut self) -> Option<Self::Item> { self.remaining = self.remaining.saturating_sub(1); self.it.next().map(Result::unwrap) } fn size_hint(&self) -> (usize, Option<usize>) { (self.remaining, Some(self.remaining)) } } impl ExactSizeIterator for BoundFrozenSetIterator<'_> { fn len(&self) -> usize { self.remaining } } #[inline] pub(crate) fn try_new_from_iter<'py, T>( py: Python<'py>, elements: impl IntoIterator<Item = T>, ) -> PyResult<Bound<'py, PyFrozenSet>> where T: IntoPyObject<'py>, { let set = unsafe { // We create the `Py` pointer because its Drop cleans up the set if user code panics. ffi::PyFrozenSet_New(std::ptr::null_mut()) .assume_owned_or_err(py)? .downcast_into_unchecked() }; let ptr = set.as_ptr(); for e in elements { let obj = e.into_pyobject(py).map_err(Into::into)?; err::error_on_minusone(py, unsafe { ffi::PySet_Add(ptr, obj.as_ptr()) })?; } Ok(set) } #[cfg(test)] mod tests { use super::*; #[test] fn test_frozenset_new_and_len() { Python::with_gil(|py| { let set = PyFrozenSet::new(py, [1]).unwrap(); assert_eq!(1, set.len()); let v = vec![1]; assert!(PyFrozenSet::new(py, &[v]).is_err()); }); } #[test] fn test_frozenset_empty() { Python::with_gil(|py| { let set = PyFrozenSet::empty(py).unwrap(); assert_eq!(0, set.len()); assert!(set.is_empty()); }); } #[test] fn test_frozenset_contains() { Python::with_gil(|py| { let set = PyFrozenSet::new(py, [1]).unwrap(); assert!(set.contains(1).unwrap()); }); } #[test] fn test_frozenset_iter() { Python::with_gil(|py| { let set = PyFrozenSet::new(py, [1]).unwrap(); for el in set { assert_eq!(1i32, el.extract::<i32>().unwrap()); } }); } #[test] fn test_frozenset_iter_bound() { Python::with_gil(|py| { let set = PyFrozenSet::new(py, [1]).unwrap(); for el in &set { assert_eq!(1i32, el.extract::<i32>().unwrap()); } }); } #[test] fn test_frozenset_iter_size_hint() { Python::with_gil(|py| { let set = PyFrozenSet::new(py, [1]).unwrap(); let mut iter = set.iter(); // Exact size assert_eq!(iter.len(), 1); assert_eq!(iter.size_hint(), (1, Some(1))); iter.next(); assert_eq!(iter.len(), 0); assert_eq!(iter.size_hint(), (0, Some(0))); }); } #[test] fn test_frozenset_builder() { use super::PyFrozenSetBuilder; Python::with_gil(|py| { let mut builder = PyFrozenSetBuilder::new(py).unwrap(); // add an item builder.add(1).unwrap(); builder.add(2).unwrap(); builder.add(2).unwrap(); // finalize it let set = builder.finalize(); assert!(set.contains(1).unwrap()); assert!(set.contains(2).unwrap()); assert!(!set.contains(3).unwrap()); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/frame.rs
use crate::ffi; use crate::PyAny; /// Represents a Python frame. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyFrame>`][crate::Py] or [`Bound<'py, PyFrame>`][crate::Bound]. #[repr(transparent)] pub struct PyFrame(PyAny); pyobject_native_type_core!( PyFrame, pyobject_native_static_type_object!(ffi::PyFrame_Type), #checkfunction=ffi::PyFrame_Check );
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/any.rs
use crate::class::basic::CompareOp; use crate::conversion::{AsPyPointer, FromPyObjectBound, IntoPyObject}; use crate::err::{DowncastError, DowncastIntoError, PyErr, PyResult}; use crate::exceptions::{PyAttributeError, PyTypeError}; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Bound; use crate::internal::get_slot::TP_DESCR_GET; use crate::internal_tricks::ptr_from_ref; use crate::py_result_ext::PyResultExt; use crate::type_object::{PyTypeCheck, PyTypeInfo}; #[cfg(not(any(PyPy, GraalPy)))] use crate::types::PySuper; use crate::types::{PyDict, PyIterator, PyList, PyString, PyTuple, PyType}; use crate::{err, ffi, Borrowed, BoundObject, Python}; use std::cell::UnsafeCell; use std::cmp::Ordering; use std::os::raw::c_int; /// Represents any Python object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyAny>`][crate::Py] or [`Bound<'py, PyAny>`][Bound]. /// /// For APIs available on all Python objects, see the [`PyAnyMethods`] trait which is implemented for /// [`Bound<'py, PyAny>`][Bound]. /// /// See #[doc = concat!("[the guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html#concrete-python-types)")] /// for an explanation of the different Python object types. #[repr(transparent)] pub struct PyAny(UnsafeCell<ffi::PyObject>); #[allow(non_snake_case)] // Copied here as the macro does not accept deprecated functions. // Originally ffi::object::PyObject_Check, but this is not in the Python C API. fn PyObject_Check(_: *mut ffi::PyObject) -> c_int { 1 } pyobject_native_type_info!( PyAny, pyobject_native_static_type_object!(ffi::PyBaseObject_Type), Some("builtins"), #checkfunction=PyObject_Check ); pyobject_native_type_sized!(PyAny, ffi::PyObject); // We cannot use `pyobject_subclassable_native_type!()` because it cfgs out on `Py_LIMITED_API`. impl crate::impl_::pyclass::PyClassBaseType for PyAny { type LayoutAsBase = crate::impl_::pycell::PyClassObjectBase<ffi::PyObject>; type BaseNativeType = PyAny; type Initializer = crate::impl_::pyclass_init::PyNativeTypeInitializer<Self>; type PyClassMutability = crate::pycell::impl_::ImmutableClass; } /// This trait represents the Python APIs which are usable on all Python objects. /// /// It is recommended you import this trait via `use pyo3::prelude::*` rather than /// by importing this trait directly. #[doc(alias = "PyAny")] pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// Returns whether `self` and `other` point to the same object. To compare /// the equality of two objects (the `==` operator), use [`eq`](PyAnyMethods::eq). /// /// This is equivalent to the Python expression `self is other`. fn is<T: AsPyPointer>(&self, other: &T) -> bool; /// Determines whether this object has the given attribute. /// /// This is equivalent to the Python expression `hasattr(self, attr_name)`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `attr_name`. /// /// # Example: `intern!`ing the attribute name /// /// ``` /// # use pyo3::{prelude::*, intern}; /// # /// #[pyfunction] /// fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> { /// sys.hasattr(intern!(sys.py(), "version")) /// } /// # /// # Python::with_gil(|py| { /// # let sys = py.import("sys").unwrap(); /// # has_version(&sys).unwrap(); /// # }); /// ``` fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> where N: IntoPyObject<'py, Target = PyString>; /// Retrieves an attribute value. /// /// This is equivalent to the Python expression `self.attr_name`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `attr_name`. /// /// # Example: `intern!`ing the attribute name /// /// ``` /// # use pyo3::{prelude::*, intern}; /// # /// #[pyfunction] /// fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> { /// sys.getattr(intern!(sys.py(), "version")) /// } /// # /// # Python::with_gil(|py| { /// # let sys = py.import("sys").unwrap(); /// # version(&sys).unwrap(); /// # }); /// ``` fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>; /// Sets an attribute value. /// /// This is equivalent to the Python expression `self.attr_name = value`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `name`. /// /// # Example: `intern!`ing the attribute name /// /// ``` /// # use pyo3::{prelude::*, intern}; /// # /// #[pyfunction] /// fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> { /// ob.setattr(intern!(ob.py(), "answer"), 42) /// } /// # /// # Python::with_gil(|py| { /// # let ob = PyModule::new(py, "empty").unwrap(); /// # set_answer(&ob).unwrap(); /// # }); /// ``` fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>, V: IntoPyObject<'py>; /// Deletes an attribute. /// /// This is equivalent to the Python statement `del self.attr_name`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `attr_name`. fn delattr<N>(&self, attr_name: N) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>; /// Returns an [`Ordering`] between `self` and `other`. /// /// This is equivalent to the following Python code: /// ```python /// if self == other: /// return Equal /// elif a < b: /// return Less /// elif a > b: /// return Greater /// else: /// raise TypeError("PyAny::compare(): All comparisons returned false") /// ``` /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyFloat; /// use std::cmp::Ordering; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let a = PyFloat::new(py, 0_f64); /// let b = PyFloat::new(py, 42_f64); /// assert_eq!(a.compare(b)?, Ordering::Less); /// Ok(()) /// })?; /// # Ok(())} /// ``` /// /// It will return `PyErr` for values that cannot be compared: /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::{PyFloat, PyString}; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let a = PyFloat::new(py, 0_f64); /// let b = PyString::new(py, "zero"); /// assert!(a.compare(b).is_err()); /// Ok(()) /// })?; /// # Ok(())} /// ``` fn compare<O>(&self, other: O) -> PyResult<Ordering> where O: IntoPyObject<'py>; /// Tests whether two Python objects obey a given [`CompareOp`]. /// /// [`lt`](Self::lt), [`le`](Self::le), [`eq`](Self::eq), [`ne`](Self::ne), /// [`gt`](Self::gt) and [`ge`](Self::ge) are the specialized versions /// of this function. /// /// Depending on the value of `compare_op`, this is equivalent to one of the /// following Python expressions: /// /// | `compare_op` | Python expression | /// | :---: | :----: | /// | [`CompareOp::Eq`] | `self == other` | /// | [`CompareOp::Ne`] | `self != other` | /// | [`CompareOp::Lt`] | `self < other` | /// | [`CompareOp::Le`] | `self <= other` | /// | [`CompareOp::Gt`] | `self > other` | /// | [`CompareOp::Ge`] | `self >= other` | /// /// # Examples /// /// ```rust /// use pyo3::class::basic::CompareOp; /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let a = 0_u8.into_pyobject(py)?; /// let b = 42_u8.into_pyobject(py)?; /// assert!(a.rich_compare(b, CompareOp::Le)?.is_truthy()?); /// Ok(()) /// })?; /// # Ok(())} /// ``` fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes the negative of self. /// /// Equivalent to the Python expression `-self`. fn neg(&self) -> PyResult<Bound<'py, PyAny>>; /// Computes the positive of self. /// /// Equivalent to the Python expression `+self`. fn pos(&self) -> PyResult<Bound<'py, PyAny>>; /// Computes the absolute of self. /// /// Equivalent to the Python expression `abs(self)`. fn abs(&self) -> PyResult<Bound<'py, PyAny>>; /// Computes `~self`. fn bitnot(&self) -> PyResult<Bound<'py, PyAny>>; /// Tests whether this object is less than another. /// /// This is equivalent to the Python expression `self < other`. fn lt<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>; /// Tests whether this object is less than or equal to another. /// /// This is equivalent to the Python expression `self <= other`. fn le<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>; /// Tests whether this object is equal to another. /// /// This is equivalent to the Python expression `self == other`. fn eq<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>; /// Tests whether this object is not equal to another. /// /// This is equivalent to the Python expression `self != other`. fn ne<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>; /// Tests whether this object is greater than another. /// /// This is equivalent to the Python expression `self > other`. fn gt<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>; /// Tests whether this object is greater than or equal to another. /// /// This is equivalent to the Python expression `self >= other`. fn ge<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>; /// Computes `self + other`. fn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self - other`. fn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self * other`. fn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self @ other`. fn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self / other`. fn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self // other`. fn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self % other`. fn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `divmod(self, other)`. fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self << other`. fn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self >> other`. fn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self ** other % modulus` (`pow(self, other, modulus)`). /// `py.None()` may be passed for the `modulus`. fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>> where O1: IntoPyObject<'py>, O2: IntoPyObject<'py>; /// Computes `self & other`. fn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self | other`. fn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Computes `self ^ other`. fn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>; /// Determines whether this object appears callable. /// /// This is equivalent to Python's [`callable()`][1] function. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let builtins = PyModule::import(py, "builtins")?; /// let print = builtins.getattr("print")?; /// assert!(print.is_callable()); /// Ok(()) /// })?; /// # Ok(())} /// ``` /// /// This is equivalent to the Python statement `assert callable(print)`. /// /// Note that unless an API needs to distinguish between callable and /// non-callable objects, there is no point in checking for callability. /// Instead, it is better to just do the call and handle potential /// exceptions. /// /// [1]: https://docs.python.org/3/library/functions.html#callable fn is_callable(&self) -> bool; /// Calls the object. /// /// This is equivalent to the Python expression `self(*args, **kwargs)`. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// use pyo3_ffi::c_str; /// use std::ffi::CStr; /// /// const CODE: &CStr = c_str!(r#" /// def function(*args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {"cruel": "world"} /// return "called with args and kwargs" /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let fun = module.getattr("function")?; /// let args = ("hello",); /// let kwargs = PyDict::new(py); /// kwargs.set_item("cruel", "world")?; /// let result = fun.call(args, Some(&kwargs))?; /// assert_eq!(result.extract::<String>()?, "called with args and kwargs"); /// Ok(()) /// }) /// # } /// ``` fn call<A>(&self, args: A, kwargs: Option<&Bound<'py, PyDict>>) -> PyResult<Bound<'py, PyAny>> where A: IntoPyObject<'py, Target = PyTuple>; /// Calls the object without arguments. /// /// This is equivalent to the Python expression `self()`. /// /// # Examples /// /// ```no_run /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let module = PyModule::import(py, "builtins")?; /// let help = module.getattr("help")?; /// help.call0()?; /// Ok(()) /// })?; /// # Ok(())} /// ``` /// /// This is equivalent to the Python expression `help()`. fn call0(&self) -> PyResult<Bound<'py, PyAny>>; /// Calls the object with only positional arguments. /// /// This is equivalent to the Python expression `self(*args)`. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3_ffi::c_str; /// use std::ffi::CStr; /// /// const CODE: &CStr = c_str!(r#" /// def function(*args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {} /// return "called with args" /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let fun = module.getattr("function")?; /// let args = ("hello",); /// let result = fun.call1(args)?; /// assert_eq!(result.extract::<String>()?, "called with args"); /// Ok(()) /// }) /// # } /// ``` fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>> where A: IntoPyObject<'py, Target = PyTuple>; /// Calls a method on the object. /// /// This is equivalent to the Python expression `self.name(*args, **kwargs)`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `name`. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// use pyo3_ffi::c_str; /// use std::ffi::CStr; /// /// const CODE: &CStr = c_str!(r#" /// class A: /// def method(self, *args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {"cruel": "world"} /// return "called with args and kwargs" /// a = A() /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let instance = module.getattr("a")?; /// let args = ("hello",); /// let kwargs = PyDict::new(py); /// kwargs.set_item("cruel", "world")?; /// let result = instance.call_method("method", args, Some(&kwargs))?; /// assert_eq!(result.extract::<String>()?, "called with args and kwargs"); /// Ok(()) /// }) /// # } /// ``` fn call_method<N, A>( &self, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>, A: IntoPyObject<'py, Target = PyTuple>; /// Calls a method on the object without arguments. /// /// This is equivalent to the Python expression `self.name()`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `name`. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3_ffi::c_str; /// use std::ffi::CStr; /// /// const CODE: &CStr = c_str!(r#" /// class A: /// def method(self, *args, **kwargs): /// assert args == () /// assert kwargs == {} /// return "called with no arguments" /// a = A() /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let instance = module.getattr("a")?; /// let result = instance.call_method0("method")?; /// assert_eq!(result.extract::<String>()?, "called with no arguments"); /// Ok(()) /// }) /// # } /// ``` fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>; /// Calls a method on the object with only positional arguments. /// /// This is equivalent to the Python expression `self.name(*args)`. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `name`. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3_ffi::c_str; /// use std::ffi::CStr; /// /// const CODE: &CStr = c_str!(r#" /// class A: /// def method(self, *args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {} /// return "called with args" /// a = A() /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let instance = module.getattr("a")?; /// let args = ("hello",); /// let result = instance.call_method1("method", args)?; /// assert_eq!(result.extract::<String>()?, "called with args"); /// Ok(()) /// }) /// # } /// ``` fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>, A: IntoPyObject<'py, Target = PyTuple>; /// Returns whether the object is considered to be true. /// /// This is equivalent to the Python expression `bool(self)`. fn is_truthy(&self) -> PyResult<bool>; /// Returns whether the object is considered to be None. /// /// This is equivalent to the Python expression `self is None`. fn is_none(&self) -> bool; /// Returns whether the object is Ellipsis, e.g. `...`. /// /// This is equivalent to the Python expression `self is ...`. #[deprecated(since = "0.23.0", note = "use `.is(py.Ellipsis())` instead")] fn is_ellipsis(&self) -> bool; /// Returns true if the sequence or mapping has a length of 0. /// /// This is equivalent to the Python expression `len(self) == 0`. fn is_empty(&self) -> PyResult<bool>; /// Gets an item from the collection. /// /// This is equivalent to the Python expression `self[key]`. fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>> where K: IntoPyObject<'py>; /// Sets a collection item value. /// /// This is equivalent to the Python expression `self[key] = value`. fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()> where K: IntoPyObject<'py>, V: IntoPyObject<'py>; /// Deletes an item from the collection. /// /// This is equivalent to the Python expression `del self[key]`. fn del_item<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>; /// Takes an object and returns an iterator for it. Returns an error if the object is not /// iterable. /// /// This is typically a new iterator but if the argument is an iterator, /// this returns itself. /// /// # Example: Checking a Python object for iterability /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::{PyAny, PyNone}; /// /// fn is_iterable(obj: &Bound<'_, PyAny>) -> bool { /// match obj.try_iter() { /// Ok(_) => true, /// Err(_) => false, /// } /// } /// /// Python::with_gil(|py| { /// assert!(is_iterable(&vec![1, 2, 3].into_pyobject(py).unwrap())); /// assert!(!is_iterable(&PyNone::get(py))); /// }); /// ``` fn try_iter(&self) -> PyResult<Bound<'py, PyIterator>>; /// Takes an object and returns an iterator for it. /// /// This is typically a new iterator but if the argument is an iterator, /// this returns itself. #[deprecated(since = "0.23.0", note = "use `try_iter` instead")] fn iter(&self) -> PyResult<Bound<'py, PyIterator>>; /// Returns the Python type object for this object's type. fn get_type(&self) -> Bound<'py, PyType>; /// Returns the Python type pointer for this object. fn get_type_ptr(&self) -> *mut ffi::PyTypeObject; /// Downcast this `PyAny` to a concrete Python type or pyclass. /// /// Note that you can often avoid downcasting yourself by just specifying /// the desired type in function or method signatures. /// However, manual downcasting is sometimes necessary. /// /// For extracting a Rust-only type, see [`PyAny::extract`](struct.PyAny.html#method.extract). /// /// # Example: Downcasting to a specific Python object /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::{PyDict, PyList}; /// /// Python::with_gil(|py| { /// let dict = PyDict::new(py); /// assert!(dict.is_instance_of::<PyAny>()); /// let any = dict.as_any(); /// /// assert!(any.downcast::<PyDict>().is_ok()); /// assert!(any.downcast::<PyList>().is_err()); /// }); /// ``` /// /// # Example: Getting a reference to a pyclass /// /// This is useful if you want to mutate a `PyObject` that /// might actually be a pyclass. /// /// ```rust /// # fn main() -> Result<(), pyo3::PyErr> { /// use pyo3::prelude::*; /// /// #[pyclass] /// struct Class { /// i: i32, /// } /// /// Python::with_gil(|py| { /// let class = Py::new(py, Class { i: 0 }).unwrap().into_bound(py).into_any(); /// /// let class_bound: &Bound<'_, Class> = class.downcast()?; /// /// class_bound.borrow_mut().i += 1; /// /// // Alternatively you can get a `PyRefMut` directly /// let class_ref: PyRefMut<'_, Class> = class.extract()?; /// assert_eq!(class_ref.i, 1); /// Ok(()) /// }) /// # } /// ``` fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> where T: PyTypeCheck; /// Like `downcast` but takes ownership of `self`. /// /// In case of an error, it is possible to retrieve `self` again via [`DowncastIntoError::into_inner`]. /// /// # Example /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::{PyDict, PyList}; /// /// Python::with_gil(|py| { /// let obj: Bound<'_, PyAny> = PyDict::new(py).into_any(); /// /// let obj: Bound<'_, PyAny> = match obj.downcast_into::<PyList>() { /// Ok(_) => panic!("obj should not be a list"), /// Err(err) => err.into_inner(), /// }; /// /// // obj is a dictionary /// assert!(obj.downcast_into::<PyDict>().is_ok()); /// }) /// ``` fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> where T: PyTypeCheck; /// Downcast this `PyAny` to a concrete Python type or pyclass (but not a subclass of it). /// /// It is almost always better to use [`PyAnyMethods::downcast`] because it accounts for Python /// subtyping. Use this method only when you do not want to allow subtypes. /// /// The advantage of this method over [`PyAnyMethods::downcast`] is that it is faster. The implementation /// of `downcast_exact` uses the equivalent of the Python expression `type(self) is T`, whereas /// `downcast` uses `isinstance(self, T)`. /// /// For extracting a Rust-only type, see [`PyAny::extract`](struct.PyAny.html#method.extract). /// /// # Example: Downcasting to a specific Python object but not a subtype /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::{PyBool, PyInt}; /// /// Python::with_gil(|py| { /// let b = PyBool::new(py, true); /// assert!(b.is_instance_of::<PyBool>()); /// let any: &Bound<'_, PyAny> = b.as_any(); /// /// // `bool` is a subtype of `int`, so `downcast` will accept a `bool` as an `int` /// // but `downcast_exact` will not. /// assert!(any.downcast::<PyInt>().is_ok()); /// assert!(any.downcast_exact::<PyInt>().is_err()); /// /// assert!(any.downcast_exact::<PyBool>().is_ok()); /// }); /// ``` fn downcast_exact<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> where T: PyTypeInfo; /// Like `downcast_exact` but takes ownership of `self`. fn downcast_into_exact<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> where T: PyTypeInfo; /// Converts this `PyAny` to a concrete Python type without checking validity. /// /// # Safety /// /// Callers must ensure that the type is valid or risk type confusion. unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T>; /// Like `downcast_unchecked` but takes ownership of `self`. /// /// # Safety /// /// Callers must ensure that the type is valid or risk type confusion. unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T>; /// Extracts some type from the Python object. /// /// This is a wrapper function around /// [`FromPyObject::extract_bound()`](crate::FromPyObject::extract_bound). fn extract<'a, T>(&'a self) -> PyResult<T> where T: FromPyObjectBound<'a, 'py>; /// Returns the reference count for the Python object. fn get_refcnt(&self) -> isize; /// Computes the "repr" representation of self. /// /// This is equivalent to the Python expression `repr(self)`. fn repr(&self) -> PyResult<Bound<'py, PyString>>; /// Computes the "str" representation of self. /// /// This is equivalent to the Python expression `str(self)`. fn str(&self) -> PyResult<Bound<'py, PyString>>; /// Retrieves the hash code of self. /// /// This is equivalent to the Python expression `hash(self)`. fn hash(&self) -> PyResult<isize>; /// Returns the length of the sequence or mapping. /// /// This is equivalent to the Python expression `len(self)`. fn len(&self) -> PyResult<usize>; /// Returns the list of attributes of this object. /// /// This is equivalent to the Python expression `dir(self)`. fn dir(&self) -> PyResult<Bound<'py, PyList>>; /// Checks whether this object is an instance of type `ty`. /// /// This is equivalent to the Python expression `isinstance(self, ty)`. fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>; /// Checks whether this object is an instance of exactly type `ty` (not a subclass). /// /// This is equivalent to the Python expression `type(self) is ty`. fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool; /// Checks whether this object is an instance of type `T`. /// /// This is equivalent to the Python expression `isinstance(self, T)`, /// if the type `T` is known at compile time. fn is_instance_of<T: PyTypeInfo>(&self) -> bool; /// Checks whether this object is an instance of exactly type `T`. /// /// This is equivalent to the Python expression `type(self) is T`, /// if the type `T` is known at compile time. fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool; /// Determines if self contains `value`. /// /// This is equivalent to the Python expression `value in self`. fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>; /// Return a proxy object that delegates method calls to a parent or sibling class of type. /// /// This is equivalent to the Python expression `super()` #[cfg(not(any(PyPy, GraalPy)))] fn py_super(&self) -> PyResult<Bound<'py, PySuper>>; } macro_rules! implement_binop { ($name:ident, $c_api:ident, $op:expr) => { #[doc = concat!("Computes `self ", $op, " other`.")] fn $name<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>, { fn inner<'py>( any: &Bound<'py, PyAny>, other: Borrowed<'_, 'py, PyAny>, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::$c_api(any.as_ptr(), other.as_ptr()).assume_owned_or_err(any.py()) } } let py = self.py(); inner( self, other .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } }; } impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> { #[inline] fn is<T: AsPyPointer>(&self, other: &T) -> bool { self.as_ptr() == other.as_ptr() } fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> where N: IntoPyObject<'py, Target = PyString>, { // PyObject_HasAttr suppresses all exceptions, which was the behaviour of `hasattr` in Python 2. // Use an implementation which suppresses only AttributeError, which is consistent with `hasattr` in Python 3. fn inner(py: Python<'_>, getattr_result: PyResult<Bound<'_, PyAny>>) -> PyResult<bool> { match getattr_result { Ok(_) => Ok(true), Err(err) if err.is_instance_of::<PyAttributeError>(py) => Ok(false), Err(e) => Err(e), } } inner(self.py(), self.getattr(attr_name).map_err(Into::into)) } fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>, { fn inner<'py>( any: &Bound<'py, PyAny>, attr_name: Borrowed<'_, '_, PyString>, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyObject_GetAttr(any.as_ptr(), attr_name.as_ptr()) .assume_owned_or_err(any.py()) } } inner( self, attr_name .into_pyobject(self.py()) .map_err(Into::into)? .as_borrowed(), ) } fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>, V: IntoPyObject<'py>, { fn inner( any: &Bound<'_, PyAny>, attr_name: Borrowed<'_, '_, PyString>, value: Borrowed<'_, '_, PyAny>, ) -> PyResult<()> { err::error_on_minusone(any.py(), unsafe { ffi::PyObject_SetAttr(any.as_ptr(), attr_name.as_ptr(), value.as_ptr()) }) } let py = self.py(); inner( self, attr_name .into_pyobject(py) .map_err(Into::into)? .as_borrowed(), value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn delattr<N>(&self, attr_name: N) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>, { fn inner(any: &Bound<'_, PyAny>, attr_name: Borrowed<'_, '_, PyString>) -> PyResult<()> { err::error_on_minusone(any.py(), unsafe { ffi::PyObject_DelAttr(any.as_ptr(), attr_name.as_ptr()) }) } let py = self.py(); inner( self, attr_name .into_pyobject(py) .map_err(Into::into)? .as_borrowed(), ) } fn compare<O>(&self, other: O) -> PyResult<Ordering> where O: IntoPyObject<'py>, { fn inner(any: &Bound<'_, PyAny>, other: Borrowed<'_, '_, PyAny>) -> PyResult<Ordering> { let other = other.as_ptr(); // Almost the same as ffi::PyObject_RichCompareBool, but this one doesn't try self == other. // See https://github.com/PyO3/pyo3/issues/985 for more. let do_compare = |other, op| unsafe { ffi::PyObject_RichCompare(any.as_ptr(), other, op) .assume_owned_or_err(any.py()) .and_then(|obj| obj.is_truthy()) }; if do_compare(other, ffi::Py_EQ)? { Ok(Ordering::Equal) } else if do_compare(other, ffi::Py_LT)? { Ok(Ordering::Less) } else if do_compare(other, ffi::Py_GT)? { Ok(Ordering::Greater) } else { Err(PyTypeError::new_err( "PyAny::compare(): All comparisons returned false", )) } } let py = self.py(); inner( self, other .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>, { fn inner<'py>( any: &Bound<'py, PyAny>, other: Borrowed<'_, 'py, PyAny>, compare_op: CompareOp, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyObject_RichCompare(any.as_ptr(), other.as_ptr(), compare_op as c_int) .assume_owned_or_err(any.py()) } } let py = self.py(); inner( self, other .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), compare_op, ) } fn neg(&self) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyNumber_Negative(self.as_ptr()).assume_owned_or_err(self.py()) } } fn pos(&self) -> PyResult<Bound<'py, PyAny>> { fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyNumber_Positive(any.as_ptr()).assume_owned_or_err(any.py()) } } inner(self) } fn abs(&self) -> PyResult<Bound<'py, PyAny>> { fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyNumber_Absolute(any.as_ptr()).assume_owned_or_err(any.py()) } } inner(self) } fn bitnot(&self) -> PyResult<Bound<'py, PyAny>> { fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyNumber_Invert(any.as_ptr()).assume_owned_or_err(any.py()) } } inner(self) } fn lt<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>, { self.rich_compare(other, CompareOp::Lt) .and_then(|any| any.is_truthy()) } fn le<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>, { self.rich_compare(other, CompareOp::Le) .and_then(|any| any.is_truthy()) } fn eq<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>, { self.rich_compare(other, CompareOp::Eq) .and_then(|any| any.is_truthy()) } fn ne<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>, { self.rich_compare(other, CompareOp::Ne) .and_then(|any| any.is_truthy()) } fn gt<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>, { self.rich_compare(other, CompareOp::Gt) .and_then(|any| any.is_truthy()) } fn ge<O>(&self, other: O) -> PyResult<bool> where O: IntoPyObject<'py>, { self.rich_compare(other, CompareOp::Ge) .and_then(|any| any.is_truthy()) } implement_binop!(add, PyNumber_Add, "+"); implement_binop!(sub, PyNumber_Subtract, "-"); implement_binop!(mul, PyNumber_Multiply, "*"); implement_binop!(matmul, PyNumber_MatrixMultiply, "@"); implement_binop!(div, PyNumber_TrueDivide, "/"); implement_binop!(floor_div, PyNumber_FloorDivide, "//"); implement_binop!(rem, PyNumber_Remainder, "%"); implement_binop!(lshift, PyNumber_Lshift, "<<"); implement_binop!(rshift, PyNumber_Rshift, ">>"); implement_binop!(bitand, PyNumber_And, "&"); implement_binop!(bitor, PyNumber_Or, "|"); implement_binop!(bitxor, PyNumber_Xor, "^"); /// Computes `divmod(self, other)`. fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>> where O: IntoPyObject<'py>, { fn inner<'py>( any: &Bound<'py, PyAny>, other: Borrowed<'_, 'py, PyAny>, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyNumber_Divmod(any.as_ptr(), other.as_ptr()).assume_owned_or_err(any.py()) } } let py = self.py(); inner( self, other .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } /// Computes `self ** other % modulus` (`pow(self, other, modulus)`). /// `py.None()` may be passed for the `modulus`. fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>> where O1: IntoPyObject<'py>, O2: IntoPyObject<'py>, { fn inner<'py>( any: &Bound<'py, PyAny>, other: Borrowed<'_, 'py, PyAny>, modulus: Borrowed<'_, 'py, PyAny>, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyNumber_Power(any.as_ptr(), other.as_ptr(), modulus.as_ptr()) .assume_owned_or_err(any.py()) } } let py = self.py(); inner( self, other .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), modulus .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn is_callable(&self) -> bool { unsafe { ffi::PyCallable_Check(self.as_ptr()) != 0 } } fn call<A>(&self, args: A, kwargs: Option<&Bound<'py, PyDict>>) -> PyResult<Bound<'py, PyAny>> where A: IntoPyObject<'py, Target = PyTuple>, { fn inner<'py>( any: &Bound<'py, PyAny>, args: Borrowed<'_, 'py, PyTuple>, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyObject_Call( any.as_ptr(), args.as_ptr(), kwargs.map_or(std::ptr::null_mut(), |dict| dict.as_ptr()), ) .assume_owned_or_err(any.py()) } } let py = self.py(); inner( self, args.into_pyobject(py).map_err(Into::into)?.as_borrowed(), kwargs, ) } #[inline] fn call0(&self) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::compat::PyObject_CallNoArgs(self.as_ptr()).assume_owned_or_err(self.py()) } } fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>> where A: IntoPyObject<'py, Target = PyTuple>, { self.call(args, None) } #[inline] fn call_method<N, A>( &self, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>, A: IntoPyObject<'py, Target = PyTuple>, { self.getattr(name) .and_then(|method| method.call(args, kwargs)) } #[inline] fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>, { let py = self.py(); let name = name.into_pyobject(py).map_err(Into::into)?.into_bound(); unsafe { ffi::compat::PyObject_CallMethodNoArgs(self.as_ptr(), name.as_ptr()) .assume_owned_or_err(py) } } fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>> where N: IntoPyObject<'py, Target = PyString>, A: IntoPyObject<'py, Target = PyTuple>, { self.call_method(name, args, None) } fn is_truthy(&self) -> PyResult<bool> { let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) }; err::error_on_minusone(self.py(), v)?; Ok(v != 0) } #[inline] fn is_none(&self) -> bool { unsafe { ffi::Py_None() == self.as_ptr() } } fn is_ellipsis(&self) -> bool { unsafe { ffi::Py_Ellipsis() == self.as_ptr() } } fn is_empty(&self) -> PyResult<bool> { self.len().map(|l| l == 0) } fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>> where K: IntoPyObject<'py>, { fn inner<'py>( any: &Bound<'py, PyAny>, key: Borrowed<'_, 'py, PyAny>, ) -> PyResult<Bound<'py, PyAny>> { unsafe { ffi::PyObject_GetItem(any.as_ptr(), key.as_ptr()).assume_owned_or_err(any.py()) } } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()> where K: IntoPyObject<'py>, V: IntoPyObject<'py>, { fn inner( any: &Bound<'_, PyAny>, key: Borrowed<'_, '_, PyAny>, value: Borrowed<'_, '_, PyAny>, ) -> PyResult<()> { err::error_on_minusone(any.py(), unsafe { ffi::PyObject_SetItem(any.as_ptr(), key.as_ptr(), value.as_ptr()) }) } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn del_item<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>, { fn inner(any: &Bound<'_, PyAny>, key: Borrowed<'_, '_, PyAny>) -> PyResult<()> { err::error_on_minusone(any.py(), unsafe { ffi::PyObject_DelItem(any.as_ptr(), key.as_ptr()) }) } let py = self.py(); inner( self, key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn try_iter(&self) -> PyResult<Bound<'py, PyIterator>> { PyIterator::from_object(self) } fn iter(&self) -> PyResult<Bound<'py, PyIterator>> { self.try_iter() } fn get_type(&self) -> Bound<'py, PyType> { unsafe { PyType::from_borrowed_type_ptr(self.py(), ffi::Py_TYPE(self.as_ptr())) } } #[inline] fn get_type_ptr(&self) -> *mut ffi::PyTypeObject { unsafe { ffi::Py_TYPE(self.as_ptr()) } } #[inline] fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> where T: PyTypeCheck, { if T::type_check(self) { // Safety: type_check is responsible for ensuring that the type is correct Ok(unsafe { self.downcast_unchecked() }) } else { Err(DowncastError::new(self, T::NAME)) } } #[inline] fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> where T: PyTypeCheck, { if T::type_check(&self) { // Safety: type_check is responsible for ensuring that the type is correct Ok(unsafe { self.downcast_into_unchecked() }) } else { Err(DowncastIntoError::new(self, T::NAME)) } } #[inline] fn downcast_exact<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> where T: PyTypeInfo, { if self.is_exact_instance_of::<T>() { // Safety: is_exact_instance_of is responsible for ensuring that the type is correct Ok(unsafe { self.downcast_unchecked() }) } else { Err(DowncastError::new(self, T::NAME)) } } #[inline] fn downcast_into_exact<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> where T: PyTypeInfo, { if self.is_exact_instance_of::<T>() { // Safety: is_exact_instance_of is responsible for ensuring that the type is correct Ok(unsafe { self.downcast_into_unchecked() }) } else { Err(DowncastIntoError::new(self, T::NAME)) } } #[inline] unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T> { &*ptr_from_ref(self).cast() } #[inline] unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T> { std::mem::transmute(self) } fn extract<'a, T>(&'a self) -> PyResult<T> where T: FromPyObjectBound<'a, 'py>, { FromPyObjectBound::from_py_object_bound(self.as_borrowed()) } fn get_refcnt(&self) -> isize { unsafe { ffi::Py_REFCNT(self.as_ptr()) } } fn repr(&self) -> PyResult<Bound<'py, PyString>> { unsafe { ffi::PyObject_Repr(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } fn str(&self) -> PyResult<Bound<'py, PyString>> { unsafe { ffi::PyObject_Str(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } fn hash(&self) -> PyResult<isize> { let v = unsafe { ffi::PyObject_Hash(self.as_ptr()) }; crate::err::error_on_minusone(self.py(), v)?; Ok(v) } fn len(&self) -> PyResult<usize> { let v = unsafe { ffi::PyObject_Size(self.as_ptr()) }; crate::err::error_on_minusone(self.py(), v)?; Ok(v as usize) } fn dir(&self) -> PyResult<Bound<'py, PyList>> { unsafe { ffi::PyObject_Dir(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool> { let result = unsafe { ffi::PyObject_IsInstance(self.as_ptr(), ty.as_ptr()) }; err::error_on_minusone(self.py(), result)?; Ok(result == 1) } #[inline] fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool { self.get_type().is(ty) } #[inline] fn is_instance_of<T: PyTypeInfo>(&self) -> bool { T::is_type_of(self) } #[inline] fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool { T::is_exact_type_of(self) } fn contains<V>(&self, value: V) -> PyResult<bool> where V: IntoPyObject<'py>, { fn inner(any: &Bound<'_, PyAny>, value: Borrowed<'_, '_, PyAny>) -> PyResult<bool> { match unsafe { ffi::PySequence_Contains(any.as_ptr(), value.as_ptr()) } { 0 => Ok(false), 1 => Ok(true), _ => Err(PyErr::fetch(any.py())), } } let py = self.py(); inner( self, value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } #[cfg(not(any(PyPy, GraalPy)))] fn py_super(&self) -> PyResult<Bound<'py, PySuper>> { PySuper::new(&self.get_type(), self) } } impl<'py> Bound<'py, PyAny> { /// Retrieve an attribute value, skipping the instance dictionary during the lookup but still /// binding the object to the instance. /// /// This is useful when trying to resolve Python's "magic" methods like `__getitem__`, which /// are looked up starting from the type object. This returns an `Option` as it is not /// typically a direct error for the special lookup to fail, as magic methods are optional in /// many situations in which they might be called. /// /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used /// to intern `attr_name`. #[allow(dead_code)] // Currently only used with num-complex+abi3, so dead without that. pub(crate) fn lookup_special<N>(&self, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>> where N: IntoPyObject<'py, Target = PyString>, { let py = self.py(); let self_type = self.get_type(); let attr = if let Ok(attr) = self_type.getattr(attr_name) { attr } else { return Ok(None); }; // Manually resolve descriptor protocol. (Faster than going through Python.) if let Some(descr_get) = attr.get_type().get_slot(TP_DESCR_GET) { // attribute is a descriptor, resolve it unsafe { descr_get(attr.as_ptr(), self.as_ptr(), self_type.as_ptr()) .assume_owned_or_err(py) .map(Some) } } else { Ok(Some(attr)) } } } #[cfg(test)] mod tests { use crate::{ basic::CompareOp, ffi, tests::common::generate_unique_module_name, types::{IntoPyDict, PyAny, PyAnyMethods, PyBool, PyInt, PyList, PyModule, PyTypeMethods}, Bound, BoundObject, IntoPyObject, PyTypeInfo, Python, }; use pyo3_ffi::c_str; use std::fmt::Debug; #[test] fn test_lookup_special() { Python::with_gil(|py| { let module = PyModule::from_code( py, c_str!( r#" class CustomCallable: def __call__(self): return 1 class SimpleInt: def __int__(self): return 1 class InheritedInt(SimpleInt): pass class NoInt: pass class NoDescriptorInt: __int__ = CustomCallable() class InstanceOverrideInt: def __int__(self): return 1 instance_override = InstanceOverrideInt() instance_override.__int__ = lambda self: 2 class ErrorInDescriptorInt: @property def __int__(self): raise ValueError("uh-oh!") class NonHeapNonDescriptorInt: # A static-typed callable that doesn't implement `__get__`. These are pretty hard to come by. __int__ = int "# ), c_str!("test.py"), &generate_unique_module_name("test"), ) .unwrap(); let int = crate::intern!(py, "__int__"); let eval_int = |obj: Bound<'_, PyAny>| obj.lookup_special(int)?.unwrap().call0()?.extract::<u32>(); let simple = module.getattr("SimpleInt").unwrap().call0().unwrap(); assert_eq!(eval_int(simple).unwrap(), 1); let inherited = module.getattr("InheritedInt").unwrap().call0().unwrap(); assert_eq!(eval_int(inherited).unwrap(), 1); let no_descriptor = module.getattr("NoDescriptorInt").unwrap().call0().unwrap(); assert_eq!(eval_int(no_descriptor).unwrap(), 1); let missing = module.getattr("NoInt").unwrap().call0().unwrap(); assert!(missing.lookup_special(int).unwrap().is_none()); // Note the instance override should _not_ call the instance method that returns 2, // because that's not how special lookups are meant to work. let instance_override = module.getattr("instance_override").unwrap(); assert_eq!(eval_int(instance_override).unwrap(), 1); let descriptor_error = module .getattr("ErrorInDescriptorInt") .unwrap() .call0() .unwrap(); assert!(descriptor_error.lookup_special(int).is_err()); let nonheap_nondescriptor = module .getattr("NonHeapNonDescriptorInt") .unwrap() .call0() .unwrap(); assert_eq!(eval_int(nonheap_nondescriptor).unwrap(), 0); }) } #[test] fn test_call_for_non_existing_method() { Python::with_gil(|py| { let a = py.eval(ffi::c_str!("42"), None, None).unwrap(); a.call_method0("__str__").unwrap(); // ok assert!(a.call_method("nonexistent_method", (1,), None).is_err()); assert!(a.call_method0("nonexistent_method").is_err()); assert!(a.call_method1("nonexistent_method", (1,)).is_err()); }); } #[test] fn test_call_with_kwargs() { Python::with_gil(|py| { let list = vec![3, 6, 5, 4, 7].into_pyobject(py).unwrap(); let dict = vec![("reverse", true)].into_py_dict(py).unwrap(); list.call_method("sort", (), Some(&dict)).unwrap(); assert_eq!(list.extract::<Vec<i32>>().unwrap(), vec![7, 6, 5, 4, 3]); }); } #[test] fn test_call_method0() { Python::with_gil(|py| { let module = PyModule::from_code( py, c_str!( r#" class SimpleClass: def foo(self): return 42 "# ), c_str!(file!()), &generate_unique_module_name("test_module"), ) .expect("module creation failed"); let simple_class = module.getattr("SimpleClass").unwrap().call0().unwrap(); assert_eq!( simple_class .call_method0("foo") .unwrap() .extract::<u32>() .unwrap(), 42 ); }) } #[test] fn test_type() { Python::with_gil(|py| { let obj = py.eval(ffi::c_str!("42"), None, None).unwrap(); assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr()); }); } #[test] fn test_dir() { Python::with_gil(|py| { let obj = py.eval(ffi::c_str!("42"), None, None).unwrap(); let dir = py .eval(ffi::c_str!("dir(42)"), None, None) .unwrap() .downcast_into::<PyList>() .unwrap(); let a = obj .dir() .unwrap() .into_iter() .map(|x| x.extract::<String>().unwrap()); let b = dir.into_iter().map(|x| x.extract::<String>().unwrap()); assert!(a.eq(b)); }); } #[test] fn test_hasattr() { Python::with_gil(|py| { let x = 5i32.into_pyobject(py).unwrap(); assert!(x.is_instance_of::<PyInt>()); assert!(x.hasattr("to_bytes").unwrap()); assert!(!x.hasattr("bbbbbbytes").unwrap()); }) } #[cfg(feature = "macros")] #[test] #[allow(unknown_lints, non_local_definitions)] fn test_hasattr_error() { use crate::exceptions::PyValueError; use crate::prelude::*; #[pyclass(crate = "crate")] struct GetattrFail; #[pymethods(crate = "crate")] impl GetattrFail { fn __getattr__(&self, attr: PyObject) -> PyResult<PyObject> { Err(PyValueError::new_err(attr)) } } Python::with_gil(|py| { let obj = Py::new(py, GetattrFail).unwrap(); let obj = obj.bind(py).as_ref(); assert!(obj .hasattr("foo") .unwrap_err() .is_instance_of::<PyValueError>(py)); }) } #[test] fn test_nan_eq() { Python::with_gil(|py| { let nan = py.eval(ffi::c_str!("float('nan')"), None, None).unwrap(); assert!(nan.compare(&nan).is_err()); }); } #[test] fn test_any_is_instance_of() { Python::with_gil(|py| { let x = 5i32.into_pyobject(py).unwrap(); assert!(x.is_instance_of::<PyInt>()); let l = vec![&x, &x].into_pyobject(py).unwrap(); assert!(l.is_instance_of::<PyList>()); }); } #[test] fn test_any_is_instance() { Python::with_gil(|py| { let l = vec![1i8, 2].into_pyobject(py).unwrap(); assert!(l.is_instance(&py.get_type::<PyList>()).unwrap()); }); } #[test] fn test_any_is_exact_instance_of() { Python::with_gil(|py| { let x = 5i32.into_pyobject(py).unwrap(); assert!(x.is_exact_instance_of::<PyInt>()); let t = PyBool::new(py, true); assert!(t.is_instance_of::<PyInt>()); assert!(!t.is_exact_instance_of::<PyInt>()); assert!(t.is_exact_instance_of::<PyBool>()); let l = vec![&x, &x].into_pyobject(py).unwrap(); assert!(l.is_exact_instance_of::<PyList>()); }); } #[test] fn test_any_is_exact_instance() { Python::with_gil(|py| { let t = PyBool::new(py, true); assert!(t.is_instance(&py.get_type::<PyInt>()).unwrap()); assert!(!t.is_exact_instance(&py.get_type::<PyInt>())); assert!(t.is_exact_instance(&py.get_type::<PyBool>())); }); } #[test] fn test_any_contains() { Python::with_gil(|py| { let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8]; let ob = v.into_pyobject(py).unwrap(); let bad_needle = 7i32.into_pyobject(py).unwrap(); assert!(!ob.contains(&bad_needle).unwrap()); let good_needle = 8i32.into_pyobject(py).unwrap(); assert!(ob.contains(&good_needle).unwrap()); let type_coerced_needle = 8f32.into_pyobject(py).unwrap(); assert!(ob.contains(&type_coerced_needle).unwrap()); let n: u32 = 42; let bad_haystack = n.into_pyobject(py).unwrap(); let irrelevant_needle = 0i32.into_pyobject(py).unwrap(); assert!(bad_haystack.contains(&irrelevant_needle).is_err()); }); } // This is intentionally not a test, it's a generic function used by the tests below. fn test_eq_methods_generic<'a, T>(list: &'a [T]) where T: PartialEq + PartialOrd, for<'py> &'a T: IntoPyObject<'py>, for<'py> <&'a T as IntoPyObject<'py>>::Error: Debug, { Python::with_gil(|py| { for a in list { for b in list { let a_py = a.into_pyobject(py).unwrap().into_any().into_bound(); let b_py = b.into_pyobject(py).unwrap().into_any().into_bound(); assert_eq!( a.lt(b), a_py.lt(&b_py).unwrap(), "{} < {} should be {}.", a_py, b_py, a.lt(b) ); assert_eq!( a.le(b), a_py.le(&b_py).unwrap(), "{} <= {} should be {}.", a_py, b_py, a.le(b) ); assert_eq!( a.eq(b), a_py.eq(&b_py).unwrap(), "{} == {} should be {}.", a_py, b_py, a.eq(b) ); assert_eq!( a.ne(b), a_py.ne(&b_py).unwrap(), "{} != {} should be {}.", a_py, b_py, a.ne(b) ); assert_eq!( a.gt(b), a_py.gt(&b_py).unwrap(), "{} > {} should be {}.", a_py, b_py, a.gt(b) ); assert_eq!( a.ge(b), a_py.ge(&b_py).unwrap(), "{} >= {} should be {}.", a_py, b_py, a.ge(b) ); } } }); } #[test] fn test_eq_methods_integers() { let ints = [-4, -4, 1, 2, 0, -100, 1_000_000]; test_eq_methods_generic::<i32>(&ints); } #[test] fn test_eq_methods_strings() { let strings = ["Let's", "test", "some", "eq", "methods"]; test_eq_methods_generic::<&str>(&strings); } #[test] fn test_eq_methods_floats() { let floats = [ -1.0, 2.5, 0.0, 3.0, std::f64::consts::PI, 10.0, 10.0 / 3.0, -1_000_000.0, ]; test_eq_methods_generic::<f64>(&floats); } #[test] fn test_eq_methods_bools() { let bools = [true, false]; test_eq_methods_generic::<bool>(&bools); } #[test] fn test_rich_compare_type_error() { Python::with_gil(|py| { let py_int = 1i32.into_pyobject(py).unwrap(); let py_str = "1".into_pyobject(py).unwrap(); assert!(py_int.rich_compare(&py_str, CompareOp::Lt).is_err()); assert!(!py_int .rich_compare(py_str, CompareOp::Eq) .unwrap() .is_truthy() .unwrap()); }) } #[test] #[allow(deprecated)] fn test_is_ellipsis() { Python::with_gil(|py| { let v = py .eval(ffi::c_str!("..."), None, None) .map_err(|e| e.display(py)) .unwrap(); assert!(v.is_ellipsis()); let not_ellipsis = 5i32.into_pyobject(py).unwrap(); assert!(!not_ellipsis.is_ellipsis()); }); } #[test] fn test_is_callable() { Python::with_gil(|py| { assert!(PyList::type_object(py).is_callable()); let not_callable = 5i32.into_pyobject(py).unwrap(); assert!(!not_callable.is_callable()); }); } #[test] fn test_is_empty() { Python::with_gil(|py| { let empty_list = PyList::empty(py).into_any(); assert!(empty_list.is_empty().unwrap()); let list = PyList::new(py, vec![1, 2, 3]).unwrap().into_any(); assert!(!list.is_empty().unwrap()); let not_container = 5i32.into_pyobject(py).unwrap(); assert!(not_container.is_empty().is_err()); }); } #[cfg(feature = "macros")] #[test] #[allow(unknown_lints, non_local_definitions)] fn test_fallible_dir() { use crate::exceptions::PyValueError; use crate::prelude::*; #[pyclass(crate = "crate")] struct DirFail; #[pymethods(crate = "crate")] impl DirFail { fn __dir__(&self) -> PyResult<PyObject> { Err(PyValueError::new_err("uh-oh!")) } } Python::with_gil(|py| { let obj = Bound::new(py, DirFail).unwrap(); assert!(obj.dir().unwrap_err().is_instance_of::<PyValueError>(py)); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/string.rs
#[cfg(not(Py_LIMITED_API))] use crate::exceptions::PyUnicodeDecodeError; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Borrowed; use crate::py_result_ext::PyResultExt; use crate::types::any::PyAnyMethods; use crate::types::bytes::PyBytesMethods; use crate::types::PyBytes; #[allow(deprecated)] use crate::IntoPy; use crate::{ffi, Bound, Py, PyAny, PyResult, Python}; use std::borrow::Cow; use std::str; /// Deprecated alias for [`PyString`]. #[deprecated(since = "0.23.0", note = "use `PyString` instead")] pub type PyUnicode = PyString; /// Represents raw data backing a Python `str`. /// /// Python internally stores strings in various representations. This enumeration /// represents those variations. #[cfg(not(Py_LIMITED_API))] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PyStringData<'a> { /// UCS1 representation. Ucs1(&'a [u8]), /// UCS2 representation. Ucs2(&'a [u16]), /// UCS4 representation. Ucs4(&'a [u32]), } #[cfg(not(Py_LIMITED_API))] impl<'a> PyStringData<'a> { /// Obtain the raw bytes backing this instance as a [u8] slice. pub fn as_bytes(&self) -> &[u8] { match self { Self::Ucs1(s) => s, Self::Ucs2(s) => unsafe { std::slice::from_raw_parts(s.as_ptr().cast(), s.len() * self.value_width_bytes()) }, Self::Ucs4(s) => unsafe { std::slice::from_raw_parts(s.as_ptr().cast(), s.len() * self.value_width_bytes()) }, } } /// Size in bytes of each value/item in the underlying slice. #[inline] pub fn value_width_bytes(&self) -> usize { match self { Self::Ucs1(_) => 1, Self::Ucs2(_) => 2, Self::Ucs4(_) => 4, } } /// Convert the raw data to a Rust string. /// /// For UCS-1 / UTF-8, returns a borrow into the original slice. For UCS-2 and UCS-4, /// returns an owned string. /// /// Returns [PyUnicodeDecodeError] if the string data isn't valid in its purported /// storage format. This should only occur for strings that were created via Python /// C APIs that skip input validation (like `PyUnicode_FromKindAndData`) and should /// never occur for strings that were created from Python code. pub fn to_string(self, py: Python<'_>) -> PyResult<Cow<'a, str>> { use std::ffi::CStr; match self { Self::Ucs1(data) => match str::from_utf8(data) { Ok(s) => Ok(Cow::Borrowed(s)), Err(e) => Err(PyUnicodeDecodeError::new_utf8(py, data, e)?.into()), }, Self::Ucs2(data) => match String::from_utf16(data) { Ok(s) => Ok(Cow::Owned(s)), Err(e) => { let mut message = e.to_string().as_bytes().to_vec(); message.push(0); Err(PyUnicodeDecodeError::new( py, ffi::c_str!("utf-16"), self.as_bytes(), 0..self.as_bytes().len(), CStr::from_bytes_with_nul(&message).unwrap(), )? .into()) } }, Self::Ucs4(data) => match data.iter().map(|&c| std::char::from_u32(c)).collect() { Some(s) => Ok(Cow::Owned(s)), None => Err(PyUnicodeDecodeError::new( py, ffi::c_str!("utf-32"), self.as_bytes(), 0..self.as_bytes().len(), ffi::c_str!("error converting utf-32"), )? .into()), }, } } /// Convert the raw data to a Rust string, possibly with data loss. /// /// Invalid code points will be replaced with `U+FFFD REPLACEMENT CHARACTER`. /// /// Returns a borrow into original data, when possible, or owned data otherwise. /// /// The return value of this function should only disagree with [Self::to_string] /// when that method would error. pub fn to_string_lossy(self) -> Cow<'a, str> { match self { Self::Ucs1(data) => String::from_utf8_lossy(data), Self::Ucs2(data) => Cow::Owned(String::from_utf16_lossy(data)), Self::Ucs4(data) => Cow::Owned( data.iter() .map(|&c| std::char::from_u32(c).unwrap_or('\u{FFFD}')) .collect(), ), } } } /// Represents a Python `string` (a Unicode string object). /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyString>`][crate::Py] or [`Bound<'py, PyString>`][Bound]. /// /// For APIs available on `str` objects, see the [`PyStringMethods`] trait which is implemented for /// [`Bound<'py, PyString>`][Bound]. /// /// # Equality /// /// For convenience, [`Bound<'py, PyString>`] implements [`PartialEq<str>`] to allow comparing the /// data in the Python string to a Rust UTF-8 string slice. /// /// This is not always the most appropriate way to compare Python strings, as Python string subclasses /// may have different equality semantics. In situations where subclasses overriding equality might be /// relevant, use [`PyAnyMethods::eq`], at cost of the additional overhead of a Python method call. /// /// ```rust /// # use pyo3::prelude::*; /// use pyo3::types::PyString; /// /// # Python::with_gil(|py| { /// let py_string = PyString::new(py, "foo"); /// // via PartialEq<str> /// assert_eq!(py_string, "foo"); /// /// // via Python equality /// assert!(py_string.as_any().eq("foo").unwrap()); /// # }); /// ``` #[repr(transparent)] pub struct PyString(PyAny); pyobject_native_type_core!(PyString, pyobject_native_static_type_object!(ffi::PyUnicode_Type), #checkfunction=ffi::PyUnicode_Check); impl PyString { /// Creates a new Python string object. /// /// Panics if out of memory. pub fn new<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString> { let ptr = s.as_ptr().cast(); let len = s.len() as ffi::Py_ssize_t; unsafe { ffi::PyUnicode_FromStringAndSize(ptr, len) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyString::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyString::new`")] #[inline] pub fn new_bound<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString> { Self::new(py, s) } /// Intern the given string /// /// This will return a reference to the same Python string object if called repeatedly with the same string. /// /// Note that while this is more memory efficient than [`PyString::new_bound`], it unconditionally allocates a /// temporary Python string object and is thereby slower than [`PyString::new_bound`]. /// /// Panics if out of memory. pub fn intern<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString> { let ptr = s.as_ptr().cast(); let len = s.len() as ffi::Py_ssize_t; unsafe { let mut ob = ffi::PyUnicode_FromStringAndSize(ptr, len); if !ob.is_null() { ffi::PyUnicode_InternInPlace(&mut ob); } ob.assume_owned(py).downcast_into_unchecked() } } /// Deprecated name for [`PyString::intern`]. #[deprecated(since = "0.23.0", note = "renamed to `PyString::intern`")] #[inline] pub fn intern_bound<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString> { Self::intern(py, s) } /// Attempts to create a Python string from a Python [bytes-like object]. /// /// [bytes-like object]: (https://docs.python.org/3/glossary.html#term-bytes-like-object). pub fn from_object<'py>( src: &Bound<'py, PyAny>, encoding: &str, errors: &str, ) -> PyResult<Bound<'py, PyString>> { unsafe { ffi::PyUnicode_FromEncodedObject( src.as_ptr(), encoding.as_ptr().cast(), errors.as_ptr().cast(), ) .assume_owned_or_err(src.py()) .downcast_into_unchecked() } } /// Deprecated name for [`PyString::from_object`]. #[deprecated(since = "0.23.0", note = "renamed to `PyString::from_object`")] #[inline] pub fn from_object_bound<'py>( src: &Bound<'py, PyAny>, encoding: &str, errors: &str, ) -> PyResult<Bound<'py, PyString>> { Self::from_object(src, encoding, errors) } } /// Implementation of functionality for [`PyString`]. /// /// These methods are defined for the `Bound<'py, PyString>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyString")] pub trait PyStringMethods<'py>: crate::sealed::Sealed { /// Gets the Python string as a Rust UTF-8 string slice. /// /// Returns a `UnicodeEncodeError` if the input is not valid unicode /// (containing unpaired surrogates). #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn to_str(&self) -> PyResult<&str>; /// Converts the `PyString` into a Rust string, avoiding copying when possible. /// /// Returns a `UnicodeEncodeError` if the input is not valid unicode /// (containing unpaired surrogates). fn to_cow(&self) -> PyResult<Cow<'_, str>>; /// Converts the `PyString` into a Rust string. /// /// Unpaired surrogates invalid UTF-8 sequences are /// replaced with `U+FFFD REPLACEMENT CHARACTER`. fn to_string_lossy(&self) -> Cow<'_, str>; /// Encodes this string as a Python `bytes` object, using UTF-8 encoding. fn encode_utf8(&self) -> PyResult<Bound<'py, PyBytes>>; /// Obtains the raw data backing the Python string. /// /// If the Python string object was created through legacy APIs, its internal storage format /// will be canonicalized before data is returned. /// /// # Safety /// /// This function implementation relies on manually decoding a C bitfield. In practice, this /// works well on common little-endian architectures such as x86_64, where the bitfield has a /// common representation (even if it is not part of the C spec). The PyO3 CI tests this API on /// x86_64 platforms. /// /// By using this API, you accept responsibility for testing that PyStringData behaves as /// expected on the targets where you plan to distribute your software. #[cfg(not(any(Py_LIMITED_API, GraalPy, PyPy)))] unsafe fn data(&self) -> PyResult<PyStringData<'_>>; } impl<'py> PyStringMethods<'py> for Bound<'py, PyString> { #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn to_str(&self) -> PyResult<&str> { self.as_borrowed().to_str() } fn to_cow(&self) -> PyResult<Cow<'_, str>> { self.as_borrowed().to_cow() } fn to_string_lossy(&self) -> Cow<'_, str> { self.as_borrowed().to_string_lossy() } fn encode_utf8(&self) -> PyResult<Bound<'py, PyBytes>> { unsafe { ffi::PyUnicode_AsUTF8String(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked::<PyBytes>() } } #[cfg(not(any(Py_LIMITED_API, GraalPy, PyPy)))] unsafe fn data(&self) -> PyResult<PyStringData<'_>> { self.as_borrowed().data() } } impl<'a> Borrowed<'a, '_, PyString> { #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] #[allow(clippy::wrong_self_convention)] pub(crate) fn to_str(self) -> PyResult<&'a str> { // PyUnicode_AsUTF8AndSize only available on limited API starting with 3.10. let mut size: ffi::Py_ssize_t = 0; let data: *const u8 = unsafe { ffi::PyUnicode_AsUTF8AndSize(self.as_ptr(), &mut size).cast() }; if data.is_null() { Err(crate::PyErr::fetch(self.py())) } else { Ok(unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(data, size as usize)) }) } } #[allow(clippy::wrong_self_convention)] pub(crate) fn to_cow(self) -> PyResult<Cow<'a, str>> { // TODO: this method can probably be deprecated once Python 3.9 support is dropped, // because all versions then support the more efficient `to_str`. #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] { self.to_str().map(Cow::Borrowed) } #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] { let bytes = self.encode_utf8()?; Ok(Cow::Owned( unsafe { str::from_utf8_unchecked(bytes.as_bytes()) }.to_owned(), )) } } #[allow(clippy::wrong_self_convention)] fn to_string_lossy(self) -> Cow<'a, str> { let ptr = self.as_ptr(); let py = self.py(); #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] if let Ok(s) = self.to_str() { return Cow::Borrowed(s); } let bytes = unsafe { ffi::PyUnicode_AsEncodedString( ptr, ffi::c_str!("utf-8").as_ptr(), ffi::c_str!("surrogatepass").as_ptr(), ) .assume_owned(py) .downcast_into_unchecked::<PyBytes>() }; Cow::Owned(String::from_utf8_lossy(bytes.as_bytes()).into_owned()) } #[cfg(not(any(Py_LIMITED_API, GraalPy, PyPy)))] unsafe fn data(self) -> PyResult<PyStringData<'a>> { let ptr = self.as_ptr(); #[cfg(not(Py_3_12))] #[allow(deprecated)] { let ready = ffi::PyUnicode_READY(ptr); if ready != 0 { // Exception was created on failure. return Err(crate::PyErr::fetch(self.py())); } } // The string should be in its canonical form after calling `PyUnicode_READY()`. // And non-canonical form not possible after Python 3.12. So it should be safe // to call these APIs. let length = ffi::PyUnicode_GET_LENGTH(ptr) as usize; let raw_data = ffi::PyUnicode_DATA(ptr); let kind = ffi::PyUnicode_KIND(ptr); match kind { ffi::PyUnicode_1BYTE_KIND => Ok(PyStringData::Ucs1(std::slice::from_raw_parts( raw_data as *const u8, length, ))), ffi::PyUnicode_2BYTE_KIND => Ok(PyStringData::Ucs2(std::slice::from_raw_parts( raw_data as *const u16, length, ))), ffi::PyUnicode_4BYTE_KIND => Ok(PyStringData::Ucs4(std::slice::from_raw_parts( raw_data as *const u32, length, ))), _ => unreachable!(), } } } impl Py<PyString> { /// Gets the Python string as a Rust UTF-8 string slice. /// /// Returns a `UnicodeEncodeError` if the input is not valid unicode /// (containing unpaired surrogates). /// /// Because `str` objects are immutable, the returned slice is independent of /// the GIL lifetime. #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] pub fn to_str<'a>(&'a self, py: Python<'_>) -> PyResult<&'a str> { self.bind_borrowed(py).to_str() } /// Converts the `PyString` into a Rust string, avoiding copying when possible. /// /// Returns a `UnicodeEncodeError` if the input is not valid unicode /// (containing unpaired surrogates). /// /// Because `str` objects are immutable, the returned slice is independent of /// the GIL lifetime. pub fn to_cow<'a>(&'a self, py: Python<'_>) -> PyResult<Cow<'a, str>> { self.bind_borrowed(py).to_cow() } /// Converts the `PyString` into a Rust string. /// /// Unpaired surrogates invalid UTF-8 sequences are /// replaced with `U+FFFD REPLACEMENT CHARACTER`. /// /// Because `str` objects are immutable, the returned slice is independent of /// the GIL lifetime. pub fn to_string_lossy<'a>(&'a self, py: Python<'_>) -> Cow<'a, str> { self.bind_borrowed(py).to_string_lossy() } } #[allow(deprecated)] impl IntoPy<Py<PyString>> for Bound<'_, PyString> { fn into_py(self, _py: Python<'_>) -> Py<PyString> { self.unbind() } } #[allow(deprecated)] impl IntoPy<Py<PyString>> for &Bound<'_, PyString> { fn into_py(self, _py: Python<'_>) -> Py<PyString> { self.clone().unbind() } } #[allow(deprecated)] impl IntoPy<Py<PyString>> for &'_ Py<PyString> { fn into_py(self, py: Python<'_>) -> Py<PyString> { self.clone_ref(py) } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<str> for Bound<'_, PyString> { #[inline] fn eq(&self, other: &str) -> bool { self.as_borrowed() == *other } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<&'_ str> for Bound<'_, PyString> { #[inline] fn eq(&self, other: &&str) -> bool { self.as_borrowed() == **other } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<Bound<'_, PyString>> for str { #[inline] fn eq(&self, other: &Bound<'_, PyString>) -> bool { *self == other.as_borrowed() } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<&'_ Bound<'_, PyString>> for str { #[inline] fn eq(&self, other: &&Bound<'_, PyString>) -> bool { *self == other.as_borrowed() } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<Bound<'_, PyString>> for &'_ str { #[inline] fn eq(&self, other: &Bound<'_, PyString>) -> bool { **self == other.as_borrowed() } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<str> for &'_ Bound<'_, PyString> { #[inline] fn eq(&self, other: &str) -> bool { self.as_borrowed() == other } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<str> for Borrowed<'_, '_, PyString> { #[inline] fn eq(&self, other: &str) -> bool { #[cfg(not(Py_3_13))] { self.to_cow().map_or(false, |s| s == other) } #[cfg(Py_3_13)] unsafe { ffi::PyUnicode_EqualToUTF8AndSize( self.as_ptr(), other.as_ptr().cast(), other.len() as _, ) == 1 } } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<&str> for Borrowed<'_, '_, PyString> { #[inline] fn eq(&self, other: &&str) -> bool { *self == **other } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<Borrowed<'_, '_, PyString>> for str { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyString>) -> bool { other == self } } /// Compares whether the data in the Python string is equal to the given UTF8. /// /// In some cases Python equality might be more appropriate; see the note on [`PyString`]. impl PartialEq<Borrowed<'_, '_, PyString>> for &'_ str { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyString>) -> bool { other == self } } #[cfg(test)] mod tests { use super::*; use crate::{IntoPyObject, PyObject}; #[test] fn test_to_cow_utf8() { Python::with_gil(|py| { let s = "ascii 🐈"; let py_string = PyString::new(py, s); assert_eq!(s, py_string.to_cow().unwrap()); }) } #[test] fn test_to_cow_surrogate() { Python::with_gil(|py| { let py_string = py .eval(ffi::c_str!(r"'\ud800'"), None, None) .unwrap() .downcast_into::<PyString>() .unwrap(); assert!(py_string.to_cow().is_err()); }) } #[test] fn test_to_cow_unicode() { Python::with_gil(|py| { let s = "哈哈🐈"; let py_string = PyString::new(py, s); assert_eq!(s, py_string.to_cow().unwrap()); }) } #[test] fn test_encode_utf8_unicode() { Python::with_gil(|py| { let s = "哈哈🐈"; let obj = PyString::new(py, s); assert_eq!(s.as_bytes(), obj.encode_utf8().unwrap().as_bytes()); }) } #[test] fn test_encode_utf8_surrogate() { Python::with_gil(|py| { let obj: PyObject = py .eval(ffi::c_str!(r"'\ud800'"), None, None) .unwrap() .into(); assert!(obj .bind(py) .downcast::<PyString>() .unwrap() .encode_utf8() .is_err()); }) } #[test] fn test_to_string_lossy() { Python::with_gil(|py| { let py_string = py .eval(ffi::c_str!(r"'🐈 Hello \ud800World'"), None, None) .unwrap() .downcast_into::<PyString>() .unwrap(); assert_eq!(py_string.to_string_lossy(), "🐈 Hello ���World"); }) } #[test] fn test_debug_string() { Python::with_gil(|py| { let s = "Hello\n".into_pyobject(py).unwrap(); assert_eq!(format!("{:?}", s), "'Hello\\n'"); }) } #[test] fn test_display_string() { Python::with_gil(|py| { let s = "Hello\n".into_pyobject(py).unwrap(); assert_eq!(format!("{}", s), "Hello\n"); }) } #[test] #[cfg(not(any(Py_LIMITED_API, PyPy)))] fn test_string_data_ucs1() { Python::with_gil(|py| { let s = PyString::new(py, "hello, world"); let data = unsafe { s.data().unwrap() }; assert_eq!(data, PyStringData::Ucs1(b"hello, world")); assert_eq!(data.to_string(py).unwrap(), Cow::Borrowed("hello, world")); assert_eq!(data.to_string_lossy(), Cow::Borrowed("hello, world")); }) } #[test] #[cfg(not(any(Py_LIMITED_API, PyPy)))] fn test_string_data_ucs1_invalid() { Python::with_gil(|py| { // 0xfe is not allowed in UTF-8. let buffer = b"f\xfe\0"; let ptr = unsafe { crate::ffi::PyUnicode_FromKindAndData( crate::ffi::PyUnicode_1BYTE_KIND as _, buffer.as_ptr().cast(), 2, ) }; assert!(!ptr.is_null()); let s = unsafe { ptr.assume_owned(py).downcast_into_unchecked::<PyString>() }; let data = unsafe { s.data().unwrap() }; assert_eq!(data, PyStringData::Ucs1(b"f\xfe")); let err = data.to_string(py).unwrap_err(); assert!(err.get_type(py).is(&py.get_type::<PyUnicodeDecodeError>())); assert!(err .to_string() .contains("'utf-8' codec can't decode byte 0xfe in position 1")); assert_eq!(data.to_string_lossy(), Cow::Borrowed("f�")); }); } #[test] #[cfg(not(any(Py_LIMITED_API, PyPy)))] fn test_string_data_ucs2() { Python::with_gil(|py| { let s = py.eval(ffi::c_str!("'foo\\ud800'"), None, None).unwrap(); let py_string = s.downcast::<PyString>().unwrap(); let data = unsafe { py_string.data().unwrap() }; assert_eq!(data, PyStringData::Ucs2(&[102, 111, 111, 0xd800])); assert_eq!( data.to_string_lossy(), Cow::Owned::<str>("foo�".to_string()) ); }) } #[test] #[cfg(all(not(any(Py_LIMITED_API, PyPy)), target_endian = "little"))] fn test_string_data_ucs2_invalid() { Python::with_gil(|py| { // U+FF22 (valid) & U+d800 (never valid) let buffer = b"\x22\xff\x00\xd8\x00\x00"; let ptr = unsafe { crate::ffi::PyUnicode_FromKindAndData( crate::ffi::PyUnicode_2BYTE_KIND as _, buffer.as_ptr().cast(), 2, ) }; assert!(!ptr.is_null()); let s = unsafe { ptr.assume_owned(py).downcast_into_unchecked::<PyString>() }; let data = unsafe { s.data().unwrap() }; assert_eq!(data, PyStringData::Ucs2(&[0xff22, 0xd800])); let err = data.to_string(py).unwrap_err(); assert!(err.get_type(py).is(&py.get_type::<PyUnicodeDecodeError>())); assert!(err .to_string() .contains("'utf-16' codec can't decode bytes in position 0-3")); assert_eq!(data.to_string_lossy(), Cow::Owned::<str>("B�".into())); }); } #[test] #[cfg(not(any(Py_LIMITED_API, PyPy)))] fn test_string_data_ucs4() { Python::with_gil(|py| { let s = "哈哈🐈"; let py_string = PyString::new(py, s); let data = unsafe { py_string.data().unwrap() }; assert_eq!(data, PyStringData::Ucs4(&[21704, 21704, 128008])); assert_eq!(data.to_string_lossy(), Cow::Owned::<str>(s.to_string())); }) } #[test] #[cfg(all(not(any(Py_LIMITED_API, PyPy)), target_endian = "little"))] fn test_string_data_ucs4_invalid() { Python::with_gil(|py| { // U+20000 (valid) & U+d800 (never valid) let buffer = b"\x00\x00\x02\x00\x00\xd8\x00\x00\x00\x00\x00\x00"; let ptr = unsafe { crate::ffi::PyUnicode_FromKindAndData( crate::ffi::PyUnicode_4BYTE_KIND as _, buffer.as_ptr().cast(), 2, ) }; assert!(!ptr.is_null()); let s = unsafe { ptr.assume_owned(py).downcast_into_unchecked::<PyString>() }; let data = unsafe { s.data().unwrap() }; assert_eq!(data, PyStringData::Ucs4(&[0x20000, 0xd800])); let err = data.to_string(py).unwrap_err(); assert!(err.get_type(py).is(&py.get_type::<PyUnicodeDecodeError>())); assert!(err .to_string() .contains("'utf-32' codec can't decode bytes in position 0-7")); assert_eq!(data.to_string_lossy(), Cow::Owned::<str>("𠀀�".into())); }); } #[test] fn test_intern_string() { Python::with_gil(|py| { let py_string1 = PyString::intern(py, "foo"); assert_eq!(py_string1, "foo"); let py_string2 = PyString::intern(py, "foo"); assert_eq!(py_string2, "foo"); assert_eq!(py_string1.as_ptr(), py_string2.as_ptr()); let py_string3 = PyString::intern(py, "bar"); assert_eq!(py_string3, "bar"); assert_ne!(py_string1.as_ptr(), py_string3.as_ptr()); }); } #[test] fn test_py_to_str_utf8() { Python::with_gil(|py| { let s = "ascii 🐈"; let py_string = PyString::new(py, s).unbind(); #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] assert_eq!(s, py_string.to_str(py).unwrap()); assert_eq!(s, py_string.to_cow(py).unwrap()); }) } #[test] fn test_py_to_str_surrogate() { Python::with_gil(|py| { let py_string: Py<PyString> = py .eval(ffi::c_str!(r"'\ud800'"), None, None) .unwrap() .extract() .unwrap(); #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] assert!(py_string.to_str(py).is_err()); assert!(py_string.to_cow(py).is_err()); }) } #[test] fn test_py_to_string_lossy() { Python::with_gil(|py| { let py_string: Py<PyString> = py .eval(ffi::c_str!(r"'🐈 Hello \ud800World'"), None, None) .unwrap() .extract() .unwrap(); assert_eq!(py_string.to_string_lossy(py), "🐈 Hello ���World"); }) } #[test] fn test_comparisons() { Python::with_gil(|py| { let s = "hello, world"; let py_string = PyString::new(py, s); assert_eq!(py_string, "hello, world"); assert_eq!(py_string, s); assert_eq!(&py_string, s); assert_eq!(s, py_string); assert_eq!(s, &py_string); assert_eq!(py_string, *s); assert_eq!(&py_string, *s); assert_eq!(*s, py_string); assert_eq!(*s, &py_string); let py_string = py_string.as_borrowed(); assert_eq!(py_string, s); assert_eq!(&py_string, s); assert_eq!(s, py_string); assert_eq!(s, &py_string); assert_eq!(py_string, *s); assert_eq!(*s, py_string); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/slice.rs
use crate::err::{PyErr, PyResult}; use crate::ffi; use crate::ffi_ptr_ext::FfiPtrExt; use crate::types::any::PyAnyMethods; #[allow(deprecated)] use crate::ToPyObject; use crate::{Bound, IntoPyObject, PyAny, PyObject, Python}; use std::convert::Infallible; /// Represents a Python `slice`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PySlice>`][crate::Py] or [`Bound<'py, PySlice>`][Bound]. /// /// For APIs available on `slice` objects, see the [`PySliceMethods`] trait which is implemented for /// [`Bound<'py, PySlice>`][Bound]. /// /// Only `isize` indices supported at the moment by the `PySlice` object. #[repr(transparent)] pub struct PySlice(PyAny); pyobject_native_type!( PySlice, ffi::PySliceObject, pyobject_native_static_type_object!(ffi::PySlice_Type), #checkfunction=ffi::PySlice_Check ); /// Return value from [`PySliceMethods::indices`]. #[derive(Debug, Eq, PartialEq)] pub struct PySliceIndices { /// Start of the slice /// /// It can be -1 when the step is negative, otherwise it's non-negative. pub start: isize, /// End of the slice /// /// It can be -1 when the step is negative, otherwise it's non-negative. pub stop: isize, /// Increment to use when iterating the slice from `start` to `stop`. pub step: isize, /// The length of the slice calculated from the original input sequence. pub slicelength: usize, } impl PySliceIndices { /// Creates a new `PySliceIndices`. pub fn new(start: isize, stop: isize, step: isize) -> PySliceIndices { PySliceIndices { start, stop, step, slicelength: 0, } } } impl PySlice { /// Constructs a new slice with the given elements. pub fn new(py: Python<'_>, start: isize, stop: isize, step: isize) -> Bound<'_, PySlice> { unsafe { ffi::PySlice_New( ffi::PyLong_FromSsize_t(start), ffi::PyLong_FromSsize_t(stop), ffi::PyLong_FromSsize_t(step), ) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PySlice::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PySlice::new`")] #[inline] pub fn new_bound(py: Python<'_>, start: isize, stop: isize, step: isize) -> Bound<'_, PySlice> { Self::new(py, start, stop, step) } /// Constructs a new full slice that is equivalent to `::`. pub fn full(py: Python<'_>) -> Bound<'_, PySlice> { unsafe { ffi::PySlice_New(ffi::Py_None(), ffi::Py_None(), ffi::Py_None()) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PySlice::full`]. #[deprecated(since = "0.23.0", note = "renamed to `PySlice::full`")] #[inline] pub fn full_bound(py: Python<'_>) -> Bound<'_, PySlice> { Self::full(py) } } /// Implementation of functionality for [`PySlice`]. /// /// These methods are defined for the `Bound<'py, PyTuple>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PySlice")] pub trait PySliceMethods<'py>: crate::sealed::Sealed { /// Retrieves the start, stop, and step indices from the slice object, /// assuming a sequence of length `length`, and stores the length of the /// slice in its `slicelength` member. fn indices(&self, length: isize) -> PyResult<PySliceIndices>; } impl<'py> PySliceMethods<'py> for Bound<'py, PySlice> { fn indices(&self, length: isize) -> PyResult<PySliceIndices> { unsafe { let mut slicelength: isize = 0; let mut start: isize = 0; let mut stop: isize = 0; let mut step: isize = 0; let r = ffi::PySlice_GetIndicesEx( self.as_ptr(), length, &mut start, &mut stop, &mut step, &mut slicelength, ); if r == 0 { Ok(PySliceIndices { start, stop, step, // non-negative isize should always fit into usize slicelength: slicelength as _, }) } else { Err(PyErr::fetch(self.py())) } } } } #[allow(deprecated)] impl ToPyObject for PySliceIndices { fn to_object(&self, py: Python<'_>) -> PyObject { PySlice::new(py, self.start, self.stop, self.step).into() } } impl<'py> IntoPyObject<'py> for PySliceIndices { type Target = PySlice; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PySlice::new(py, self.start, self.stop, self.step)) } } impl<'py> IntoPyObject<'py> for &PySliceIndices { type Target = PySlice; type Output = Bound<'py, Self::Target>; type Error = Infallible; fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(PySlice::new(py, self.start, self.stop, self.step)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_py_slice_new() { Python::with_gil(|py| { let slice = PySlice::new(py, isize::MIN, isize::MAX, 1); assert_eq!( slice.getattr("start").unwrap().extract::<isize>().unwrap(), isize::MIN ); assert_eq!( slice.getattr("stop").unwrap().extract::<isize>().unwrap(), isize::MAX ); assert_eq!( slice.getattr("step").unwrap().extract::<isize>().unwrap(), 1 ); }); } #[test] fn test_py_slice_full() { Python::with_gil(|py| { let slice = PySlice::full(py); assert!(slice.getattr("start").unwrap().is_none(),); assert!(slice.getattr("stop").unwrap().is_none(),); assert!(slice.getattr("step").unwrap().is_none(),); assert_eq!( slice.indices(0).unwrap(), PySliceIndices { start: 0, stop: 0, step: 1, slicelength: 0, }, ); assert_eq!( slice.indices(42).unwrap(), PySliceIndices { start: 0, stop: 42, step: 1, slicelength: 42, }, ); }); } #[test] fn test_py_slice_indices_new() { let start = 0; let stop = 0; let step = 0; assert_eq!( PySliceIndices::new(start, stop, step), PySliceIndices { start, stop, step, slicelength: 0 } ); let start = 0; let stop = 100; let step = 10; assert_eq!( PySliceIndices::new(start, stop, step), PySliceIndices { start, stop, step, slicelength: 0 } ); let start = 0; let stop = -10; let step = -1; assert_eq!( PySliceIndices::new(start, stop, step), PySliceIndices { start, stop, step, slicelength: 0 } ); let start = 0; let stop = -10; let step = 20; assert_eq!( PySliceIndices::new(start, stop, step), PySliceIndices { start, stop, step, slicelength: 0 } ); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/bytes.rs
use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::{Borrowed, Bound}; use crate::types::any::PyAnyMethods; use crate::{ffi, Py, PyAny, PyResult, Python}; use std::ops::Index; use std::slice::SliceIndex; use std::str; /// Represents a Python `bytes` object. /// /// This type is immutable. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyBytes>`][crate::Py] or [`Bound<'py, PyBytes>`][Bound]. /// /// For APIs available on `bytes` objects, see the [`PyBytesMethods`] trait which is implemented for /// [`Bound<'py, PyBytes>`][Bound]. /// /// # Equality /// /// For convenience, [`Bound<'py, PyBytes>`][Bound] implements [`PartialEq<[u8]>`][PartialEq] to allow comparing the /// data in the Python bytes to a Rust `[u8]` byte slice. /// /// This is not always the most appropriate way to compare Python bytes, as Python bytes subclasses /// may have different equality semantics. In situations where subclasses overriding equality might be /// relevant, use [`PyAnyMethods::eq`], at cost of the additional overhead of a Python method call. /// /// ```rust /// # use pyo3::prelude::*; /// use pyo3::types::PyBytes; /// /// # Python::with_gil(|py| { /// let py_bytes = PyBytes::new(py, b"foo".as_slice()); /// // via PartialEq<[u8]> /// assert_eq!(py_bytes, b"foo".as_slice()); /// /// // via Python equality /// let other = PyBytes::new(py, b"foo".as_slice()); /// assert!(py_bytes.as_any().eq(other).unwrap()); /// /// // Note that `eq` will convert its argument to Python using `IntoPyObject`. /// // Byte collections are specialized, so that the following slice will indeed /// // convert into a `bytes` object and not a `list`: /// assert!(py_bytes.as_any().eq(b"foo".as_slice()).unwrap()); /// # }); /// ``` #[repr(transparent)] pub struct PyBytes(PyAny); pyobject_native_type_core!(PyBytes, pyobject_native_static_type_object!(ffi::PyBytes_Type), #checkfunction=ffi::PyBytes_Check); impl PyBytes { /// Creates a new Python bytestring object. /// The bytestring is initialized by copying the data from the `&[u8]`. /// /// Panics if out of memory. pub fn new<'p>(py: Python<'p>, s: &[u8]) -> Bound<'p, PyBytes> { let ptr = s.as_ptr().cast(); let len = s.len() as ffi::Py_ssize_t; unsafe { ffi::PyBytes_FromStringAndSize(ptr, len) .assume_owned(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyBytes::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyBytes::new`")] #[inline] pub fn new_bound<'p>(py: Python<'p>, s: &[u8]) -> Bound<'p, PyBytes> { Self::new(py, s) } /// Creates a new Python `bytes` object with an `init` closure to write its contents. /// Before calling `init` the bytes' contents are zero-initialised. /// * If Python raises a MemoryError on the allocation, `new_with` will return /// it inside `Err`. /// * If `init` returns `Err(e)`, `new_with` will return `Err(e)`. /// * If `init` returns `Ok(())`, `new_with` will return `Ok(&PyBytes)`. /// /// # Examples /// /// ``` /// use pyo3::{prelude::*, types::PyBytes}; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let py_bytes = PyBytes::new_with(py, 10, |bytes: &mut [u8]| { /// bytes.copy_from_slice(b"Hello Rust"); /// Ok(()) /// })?; /// let bytes: &[u8] = py_bytes.extract()?; /// assert_eq!(bytes, b"Hello Rust"); /// Ok(()) /// }) /// # } /// ``` #[inline] pub fn new_with<F>(py: Python<'_>, len: usize, init: F) -> PyResult<Bound<'_, PyBytes>> where F: FnOnce(&mut [u8]) -> PyResult<()>, { unsafe { let pyptr = ffi::PyBytes_FromStringAndSize(std::ptr::null(), len as ffi::Py_ssize_t); // Check for an allocation error and return it let pybytes = pyptr.assume_owned_or_err(py)?.downcast_into_unchecked(); let buffer: *mut u8 = ffi::PyBytes_AsString(pyptr).cast(); debug_assert!(!buffer.is_null()); // Zero-initialise the uninitialised bytestring std::ptr::write_bytes(buffer, 0u8, len); // (Further) Initialise the bytestring in init // If init returns an Err, pypybytearray will automatically deallocate the buffer init(std::slice::from_raw_parts_mut(buffer, len)).map(|_| pybytes) } } /// Deprecated name for [`PyBytes::new_with`]. #[deprecated(since = "0.23.0", note = "renamed to `PyBytes::new_with`")] #[inline] pub fn new_bound_with<F>(py: Python<'_>, len: usize, init: F) -> PyResult<Bound<'_, PyBytes>> where F: FnOnce(&mut [u8]) -> PyResult<()>, { Self::new_with(py, len, init) } /// Creates a new Python byte string object from a raw pointer and length. /// /// Panics if out of memory. /// /// # Safety /// /// This function dereferences the raw pointer `ptr` as the /// leading pointer of a slice of length `len`. [As with /// `std::slice::from_raw_parts`, this is /// unsafe](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety). pub unsafe fn from_ptr(py: Python<'_>, ptr: *const u8, len: usize) -> Bound<'_, PyBytes> { ffi::PyBytes_FromStringAndSize(ptr.cast(), len as isize) .assume_owned(py) .downcast_into_unchecked() } /// Deprecated name for [`PyBytes::from_ptr`]. /// /// # Safety /// /// This function dereferences the raw pointer `ptr` as the /// leading pointer of a slice of length `len`. [As with /// `std::slice::from_raw_parts`, this is /// unsafe](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety). #[deprecated(since = "0.23.0", note = "renamed to `PyBytes::from_ptr`")] #[inline] pub unsafe fn bound_from_ptr(py: Python<'_>, ptr: *const u8, len: usize) -> Bound<'_, PyBytes> { Self::from_ptr(py, ptr, len) } } /// Implementation of functionality for [`PyBytes`]. /// /// These methods are defined for the `Bound<'py, PyBytes>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyBytes")] pub trait PyBytesMethods<'py>: crate::sealed::Sealed { /// Gets the Python string as a byte slice. fn as_bytes(&self) -> &[u8]; } impl<'py> PyBytesMethods<'py> for Bound<'py, PyBytes> { #[inline] fn as_bytes(&self) -> &[u8] { self.as_borrowed().as_bytes() } } impl<'a> Borrowed<'a, '_, PyBytes> { /// Gets the Python string as a byte slice. #[allow(clippy::wrong_self_convention)] pub(crate) fn as_bytes(self) -> &'a [u8] { unsafe { let buffer = ffi::PyBytes_AsString(self.as_ptr()) as *const u8; let length = ffi::PyBytes_Size(self.as_ptr()) as usize; debug_assert!(!buffer.is_null()); std::slice::from_raw_parts(buffer, length) } } } impl Py<PyBytes> { /// Gets the Python bytes as a byte slice. Because Python bytes are /// immutable, the result may be used for as long as the reference to /// `self` is held, including when the GIL is released. pub fn as_bytes<'a>(&'a self, py: Python<'_>) -> &'a [u8] { self.bind_borrowed(py).as_bytes() } } /// This is the same way [Vec] is indexed. impl<I: SliceIndex<[u8]>> Index<I> for Bound<'_, PyBytes> { type Output = I::Output; fn index(&self, index: I) -> &Self::Output { &self.as_bytes()[index] } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<[u8]> for Bound<'_, PyBytes> { #[inline] fn eq(&self, other: &[u8]) -> bool { self.as_borrowed() == *other } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<&'_ [u8]> for Bound<'_, PyBytes> { #[inline] fn eq(&self, other: &&[u8]) -> bool { self.as_borrowed() == **other } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<Bound<'_, PyBytes>> for [u8] { #[inline] fn eq(&self, other: &Bound<'_, PyBytes>) -> bool { *self == other.as_borrowed() } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<&'_ Bound<'_, PyBytes>> for [u8] { #[inline] fn eq(&self, other: &&Bound<'_, PyBytes>) -> bool { *self == other.as_borrowed() } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<Bound<'_, PyBytes>> for &'_ [u8] { #[inline] fn eq(&self, other: &Bound<'_, PyBytes>) -> bool { **self == other.as_borrowed() } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<[u8]> for &'_ Bound<'_, PyBytes> { #[inline] fn eq(&self, other: &[u8]) -> bool { self.as_borrowed() == other } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<[u8]> for Borrowed<'_, '_, PyBytes> { #[inline] fn eq(&self, other: &[u8]) -> bool { self.as_bytes() == other } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<&[u8]> for Borrowed<'_, '_, PyBytes> { #[inline] fn eq(&self, other: &&[u8]) -> bool { *self == **other } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<Borrowed<'_, '_, PyBytes>> for [u8] { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyBytes>) -> bool { other == self } } /// Compares whether the Python bytes object is equal to the [u8]. /// /// In some cases Python equality might be more appropriate; see the note on [`PyBytes`]. impl PartialEq<Borrowed<'_, '_, PyBytes>> for &'_ [u8] { #[inline] fn eq(&self, other: &Borrowed<'_, '_, PyBytes>) -> bool { other == self } } #[cfg(test)] mod tests { use super::*; #[test] fn test_bytes_index() { Python::with_gil(|py| { let bytes = PyBytes::new(py, b"Hello World"); assert_eq!(bytes[1], b'e'); }); } #[test] fn test_bound_bytes_index() { Python::with_gil(|py| { let bytes = PyBytes::new(py, b"Hello World"); assert_eq!(bytes[1], b'e'); let bytes = &bytes; assert_eq!(bytes[1], b'e'); }); } #[test] fn test_bytes_new_with() -> super::PyResult<()> { Python::with_gil(|py| -> super::PyResult<()> { let py_bytes = PyBytes::new_with(py, 10, |b: &mut [u8]| { b.copy_from_slice(b"Hello Rust"); Ok(()) })?; let bytes: &[u8] = py_bytes.extract()?; assert_eq!(bytes, b"Hello Rust"); Ok(()) }) } #[test] fn test_bytes_new_with_zero_initialised() -> super::PyResult<()> { Python::with_gil(|py| -> super::PyResult<()> { let py_bytes = PyBytes::new_with(py, 10, |_b: &mut [u8]| Ok(()))?; let bytes: &[u8] = py_bytes.extract()?; assert_eq!(bytes, &[0; 10]); Ok(()) }) } #[test] fn test_bytes_new_with_error() { use crate::exceptions::PyValueError; Python::with_gil(|py| { let py_bytes_result = PyBytes::new_with(py, 10, |_b: &mut [u8]| { Err(PyValueError::new_err("Hello Crustaceans!")) }); assert!(py_bytes_result.is_err()); assert!(py_bytes_result .err() .unwrap() .is_instance_of::<PyValueError>(py)); }); } #[test] fn test_comparisons() { Python::with_gil(|py| { let b = b"hello, world".as_slice(); let py_bytes = PyBytes::new(py, b); assert_eq!(py_bytes, b"hello, world".as_slice()); assert_eq!(py_bytes, b); assert_eq!(&py_bytes, b); assert_eq!(b, py_bytes); assert_eq!(b, &py_bytes); assert_eq!(py_bytes, *b); assert_eq!(&py_bytes, *b); assert_eq!(*b, py_bytes); assert_eq!(*b, &py_bytes); let py_string = py_bytes.as_borrowed(); assert_eq!(py_string, b); assert_eq!(&py_string, b); assert_eq!(b, py_string); assert_eq!(b, &py_string); assert_eq!(py_string, *b); assert_eq!(*b, py_string); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/capsule.rs
use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::{ffi, PyAny}; use crate::{Bound, Python}; use crate::{PyErr, PyResult}; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_int, c_void}; /// Represents a Python Capsule /// as described in [Capsules](https://docs.python.org/3/c-api/capsule.html#capsules): /// > This subtype of PyObject represents an opaque value, useful for C extension /// > modules who need to pass an opaque value (as a void* pointer) through Python /// > code to other C code. It is often used to make a C function pointer defined /// > in one module available to other modules, so the regular import mechanism can /// > be used to access C APIs defined in dynamically loaded modules. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyCapsule>`][crate::Py] or [`Bound<'py, PyCapsule>`][Bound]. /// /// For APIs available on capsule objects, see the [`PyCapsuleMethods`] trait which is implemented for /// [`Bound<'py, PyCapsule>`][Bound]. /// /// # Example /// ``` /// use pyo3::{prelude::*, types::PyCapsule}; /// use std::ffi::CString; /// /// #[repr(C)] /// struct Foo { /// pub val: u32, /// } /// /// let r = Python::with_gil(|py| -> PyResult<()> { /// let foo = Foo { val: 123 }; /// let name = CString::new("builtins.capsule").unwrap(); /// /// let capsule = PyCapsule::new(py, foo, Some(name.clone()))?; /// /// let module = PyModule::import(py, "builtins")?; /// module.add("capsule", capsule)?; /// /// let cap: &Foo = unsafe { PyCapsule::import(py, name.as_ref())? }; /// assert_eq!(cap.val, 123); /// Ok(()) /// }); /// assert!(r.is_ok()); /// ``` #[repr(transparent)] pub struct PyCapsule(PyAny); pyobject_native_type_core!(PyCapsule, pyobject_native_static_type_object!(ffi::PyCapsule_Type), #checkfunction=ffi::PyCapsule_CheckExact); impl PyCapsule { /// Constructs a new capsule whose contents are `value`, associated with `name`. /// `name` is the identifier for the capsule; if it is stored as an attribute of a module, /// the name should be in the format `"modulename.attribute"`. /// /// It is checked at compile time that the type T is not zero-sized. Rust function items /// need to be cast to a function pointer (`fn(args) -> result`) to be put into a capsule. /// /// # Example /// /// ``` /// use pyo3::{prelude::*, types::PyCapsule}; /// use std::ffi::CString; /// /// Python::with_gil(|py| { /// let name = CString::new("foo").unwrap(); /// let capsule = PyCapsule::new(py, 123_u32, Some(name)).unwrap(); /// let val = unsafe { capsule.reference::<u32>() }; /// assert_eq!(*val, 123); /// }); /// ``` /// /// However, attempting to construct a `PyCapsule` with a zero-sized type will not compile: /// /// ```compile_fail /// use pyo3::{prelude::*, types::PyCapsule}; /// use std::ffi::CString; /// /// Python::with_gil(|py| { /// let capsule = PyCapsule::new(py, (), None).unwrap(); // Oops! `()` is zero sized! /// }); /// ``` pub fn new<T: 'static + Send + AssertNotZeroSized>( py: Python<'_>, value: T, name: Option<CString>, ) -> PyResult<Bound<'_, Self>> { Self::new_with_destructor(py, value, name, |_, _| {}) } /// Deprecated name for [`PyCapsule::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyCapsule::new`")] #[inline] pub fn new_bound<T: 'static + Send + AssertNotZeroSized>( py: Python<'_>, value: T, name: Option<CString>, ) -> PyResult<Bound<'_, Self>> { Self::new(py, value, name) } /// Constructs a new capsule whose contents are `value`, associated with `name`. /// /// Also provides a destructor: when the `PyCapsule` is destroyed, it will be passed the original object, /// as well as a `*mut c_void` which will point to the capsule's context, if any. /// /// The `destructor` must be `Send`, because there is no guarantee which thread it will eventually /// be called from. pub fn new_with_destructor< T: 'static + Send + AssertNotZeroSized, F: FnOnce(T, *mut c_void) + Send, >( py: Python<'_>, value: T, name: Option<CString>, destructor: F, ) -> PyResult<Bound<'_, Self>> { AssertNotZeroSized::assert_not_zero_sized(&value); // Sanity check for capsule layout debug_assert_eq!(memoffset::offset_of!(CapsuleContents::<T, F>, value), 0); let name_ptr = name.as_ref().map_or(std::ptr::null(), |name| name.as_ptr()); let val = Box::new(CapsuleContents { value, destructor, name, }); unsafe { ffi::PyCapsule_New( Box::into_raw(val).cast(), name_ptr, Some(capsule_destructor::<T, F>), ) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyCapsule::new_with_destructor`]. #[deprecated(since = "0.23.0", note = "renamed to `PyCapsule::new_with_destructor`")] #[inline] pub fn new_bound_with_destructor< T: 'static + Send + AssertNotZeroSized, F: FnOnce(T, *mut c_void) + Send, >( py: Python<'_>, value: T, name: Option<CString>, destructor: F, ) -> PyResult<Bound<'_, Self>> { Self::new_with_destructor(py, value, name, destructor) } /// Imports an existing capsule. /// /// The `name` should match the path to the module attribute exactly in the form /// of `"module.attribute"`, which should be the same as the name within the capsule. /// /// # Safety /// /// It must be known that the capsule imported by `name` contains an item of type `T`. pub unsafe fn import<'py, T>(py: Python<'py>, name: &CStr) -> PyResult<&'py T> { let ptr = ffi::PyCapsule_Import(name.as_ptr(), false as c_int); if ptr.is_null() { Err(PyErr::fetch(py)) } else { Ok(&*ptr.cast::<T>()) } } } /// Implementation of functionality for [`PyCapsule`]. /// /// These methods are defined for the `Bound<'py, PyCapsule>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyCapsule")] pub trait PyCapsuleMethods<'py>: crate::sealed::Sealed { /// Sets the context pointer in the capsule. /// /// Returns an error if this capsule is not valid. /// /// # Notes /// /// The context is treated much like the value of the capsule, but should likely act as /// a place to store any state management when using the capsule. /// /// If you want to store a Rust value as the context, and drop it from the destructor, use /// `Box::into_raw` to convert it into a pointer, see the example. /// /// # Example /// /// ``` /// use std::os::raw::c_void; /// use std::sync::mpsc::{channel, Sender}; /// use pyo3::{prelude::*, types::PyCapsule}; /// /// let (tx, rx) = channel::<String>(); /// /// fn destructor(val: u32, context: *mut c_void) { /// let ctx = unsafe { *Box::from_raw(context.cast::<Sender<String>>()) }; /// ctx.send("Destructor called!".to_string()).unwrap(); /// } /// /// Python::with_gil(|py| { /// let capsule = /// PyCapsule::new_with_destructor(py, 123, None, destructor as fn(u32, *mut c_void)) /// .unwrap(); /// let context = Box::new(tx); // `Sender<String>` is our context, box it up and ship it! /// capsule.set_context(Box::into_raw(context).cast()).unwrap(); /// // This scope will end, causing our destructor to be called... /// }); /// /// assert_eq!(rx.recv(), Ok("Destructor called!".to_string())); /// ``` fn set_context(&self, context: *mut c_void) -> PyResult<()>; /// Gets the current context stored in the capsule. If there is no context, the pointer /// will be null. /// /// Returns an error if this capsule is not valid. fn context(&self) -> PyResult<*mut c_void>; /// Obtains a reference to the value of this capsule. /// /// # Safety /// /// It must be known that this capsule is valid and its pointer is to an item of type `T`. unsafe fn reference<T>(&self) -> &'py T; /// Gets the raw `c_void` pointer to the value in this capsule. /// /// Returns null if this capsule is not valid. fn pointer(&self) -> *mut c_void; /// Checks if this is a valid capsule. /// /// Returns true if the stored `pointer()` is non-null. fn is_valid(&self) -> bool; /// Retrieves the name of this capsule, if set. /// /// Returns an error if this capsule is not valid. fn name(&self) -> PyResult<Option<&'py CStr>>; } impl<'py> PyCapsuleMethods<'py> for Bound<'py, PyCapsule> { #[allow(clippy::not_unsafe_ptr_arg_deref)] fn set_context(&self, context: *mut c_void) -> PyResult<()> { let result = unsafe { ffi::PyCapsule_SetContext(self.as_ptr(), context) }; if result != 0 { Err(PyErr::fetch(self.py())) } else { Ok(()) } } fn context(&self) -> PyResult<*mut c_void> { let ctx = unsafe { ffi::PyCapsule_GetContext(self.as_ptr()) }; if ctx.is_null() { ensure_no_error(self.py())? } Ok(ctx) } unsafe fn reference<T>(&self) -> &'py T { &*self.pointer().cast() } fn pointer(&self) -> *mut c_void { unsafe { let ptr = ffi::PyCapsule_GetPointer(self.as_ptr(), name_ptr_ignore_error(self)); if ptr.is_null() { ffi::PyErr_Clear(); } ptr } } fn is_valid(&self) -> bool { // As well as if the stored pointer is null, PyCapsule_IsValid also returns false if // self.as_ptr() is null or not a ptr to a PyCapsule object. Both of these are guaranteed // to not be the case thanks to invariants of this PyCapsule struct. let r = unsafe { ffi::PyCapsule_IsValid(self.as_ptr(), name_ptr_ignore_error(self)) }; r != 0 } fn name(&self) -> PyResult<Option<&'py CStr>> { unsafe { let ptr = ffi::PyCapsule_GetName(self.as_ptr()); if ptr.is_null() { ensure_no_error(self.py())?; Ok(None) } else { Ok(Some(CStr::from_ptr(ptr))) } } } } // C layout, as PyCapsule::get_reference depends on `T` being first. #[repr(C)] struct CapsuleContents<T: 'static + Send, D: FnOnce(T, *mut c_void) + Send> { /// Value of the capsule value: T, /// Destructor to be used by the capsule destructor: D, /// Name used when creating the capsule name: Option<CString>, } // Wrapping ffi::PyCapsule_Destructor for a user supplied FnOnce(T) for capsule destructor unsafe extern "C" fn capsule_destructor<T: 'static + Send, F: FnOnce(T, *mut c_void) + Send>( capsule: *mut ffi::PyObject, ) { let ptr = ffi::PyCapsule_GetPointer(capsule, ffi::PyCapsule_GetName(capsule)); let ctx = ffi::PyCapsule_GetContext(capsule); let CapsuleContents { value, destructor, .. } = *Box::from_raw(ptr.cast::<CapsuleContents<T, F>>()); destructor(value, ctx) } /// Guarantee `T` is not zero sized at compile time. // credit: `<https://users.rust-lang.org/t/is-it-possible-to-assert-at-compile-time-that-foo-t-is-not-called-with-a-zst/67685>` #[doc(hidden)] pub trait AssertNotZeroSized: Sized { const _CONDITION: usize = (std::mem::size_of::<Self>() == 0) as usize; const _CHECK: &'static str = ["PyCapsule value type T must not be zero-sized!"][Self::_CONDITION]; #[allow(path_statements, clippy::no_effect)] fn assert_not_zero_sized(&self) { <Self as AssertNotZeroSized>::_CHECK; } } impl<T> AssertNotZeroSized for T {} fn ensure_no_error(py: Python<'_>) -> PyResult<()> { if let Some(err) = PyErr::take(py) { Err(err) } else { Ok(()) } } fn name_ptr_ignore_error(slf: &Bound<'_, PyCapsule>) -> *const c_char { let ptr = unsafe { ffi::PyCapsule_GetName(slf.as_ptr()) }; if ptr.is_null() { unsafe { ffi::PyErr_Clear() }; } ptr } #[cfg(test)] mod tests { use crate::prelude::PyModule; use crate::types::capsule::PyCapsuleMethods; use crate::types::module::PyModuleMethods; use crate::{types::PyCapsule, Py, PyResult, Python}; use std::ffi::CString; use std::os::raw::c_void; use std::sync::mpsc::{channel, Sender}; #[test] fn test_pycapsule_struct() -> PyResult<()> { #[repr(C)] struct Foo { pub val: u32, } impl Foo { fn get_val(&self) -> u32 { self.val } } Python::with_gil(|py| -> PyResult<()> { let foo = Foo { val: 123 }; let name = CString::new("foo").unwrap(); let cap = PyCapsule::new(py, foo, Some(name.clone()))?; assert!(cap.is_valid()); let foo_capi = unsafe { cap.reference::<Foo>() }; assert_eq!(foo_capi.val, 123); assert_eq!(foo_capi.get_val(), 123); assert_eq!(cap.name().unwrap(), Some(name.as_ref())); Ok(()) }) } #[test] fn test_pycapsule_func() { fn foo(x: u32) -> u32 { x } let cap: Py<PyCapsule> = Python::with_gil(|py| { let name = CString::new("foo").unwrap(); let cap = PyCapsule::new(py, foo as fn(u32) -> u32, Some(name)).unwrap(); cap.into() }); Python::with_gil(move |py| { let f = unsafe { cap.bind(py).reference::<fn(u32) -> u32>() }; assert_eq!(f(123), 123); }); } #[test] fn test_pycapsule_context() -> PyResult<()> { Python::with_gil(|py| { let name = CString::new("foo").unwrap(); let cap = PyCapsule::new(py, 0, Some(name))?; let c = cap.context()?; assert!(c.is_null()); let ctx = Box::new(123_u32); cap.set_context(Box::into_raw(ctx).cast())?; let ctx_ptr: *mut c_void = cap.context()?; let ctx = unsafe { *Box::from_raw(ctx_ptr.cast::<u32>()) }; assert_eq!(ctx, 123); Ok(()) }) } #[test] fn test_pycapsule_import() -> PyResult<()> { #[repr(C)] struct Foo { pub val: u32, } Python::with_gil(|py| -> PyResult<()> { let foo = Foo { val: 123 }; let name = CString::new("builtins.capsule").unwrap(); let capsule = PyCapsule::new(py, foo, Some(name.clone()))?; let module = PyModule::import(py, "builtins")?; module.add("capsule", capsule)?; // check error when wrong named passed for capsule. let wrong_name = CString::new("builtins.non_existant").unwrap(); let result: PyResult<&Foo> = unsafe { PyCapsule::import(py, wrong_name.as_ref()) }; assert!(result.is_err()); // corret name is okay. let cap: &Foo = unsafe { PyCapsule::import(py, name.as_ref())? }; assert_eq!(cap.val, 123); Ok(()) }) } #[test] fn test_vec_storage() { let cap: Py<PyCapsule> = Python::with_gil(|py| { let name = CString::new("foo").unwrap(); let stuff: Vec<u8> = vec![1, 2, 3, 4]; let cap = PyCapsule::new(py, stuff, Some(name)).unwrap(); cap.into() }); Python::with_gil(move |py| { let ctx: &Vec<u8> = unsafe { cap.bind(py).reference() }; assert_eq!(ctx, &[1, 2, 3, 4]); }) } #[test] fn test_vec_context() { let context: Vec<u8> = vec![1, 2, 3, 4]; let cap: Py<PyCapsule> = Python::with_gil(|py| { let name = CString::new("foo").unwrap(); let cap = PyCapsule::new(py, 0, Some(name)).unwrap(); cap.set_context(Box::into_raw(Box::new(&context)).cast()) .unwrap(); cap.into() }); Python::with_gil(move |py| { let ctx_ptr: *mut c_void = cap.bind(py).context().unwrap(); let ctx = unsafe { *Box::from_raw(ctx_ptr.cast::<&Vec<u8>>()) }; assert_eq!(ctx, &vec![1_u8, 2, 3, 4]); }) } #[test] fn test_pycapsule_destructor() { let (tx, rx) = channel::<bool>(); fn destructor(_val: u32, ctx: *mut c_void) { assert!(!ctx.is_null()); let context = unsafe { *Box::from_raw(ctx.cast::<Sender<bool>>()) }; context.send(true).unwrap(); } Python::with_gil(move |py| { let name = CString::new("foo").unwrap(); let cap = PyCapsule::new_with_destructor(py, 0, Some(name), destructor).unwrap(); cap.set_context(Box::into_raw(Box::new(tx)).cast()).unwrap(); }); // the destructor was called. assert_eq!(rx.recv(), Ok(true)); } #[test] fn test_pycapsule_no_name() { Python::with_gil(|py| { let cap = PyCapsule::new(py, 0usize, None).unwrap(); assert_eq!(unsafe { cap.reference::<usize>() }, &0usize); assert_eq!(cap.name().unwrap(), None); assert_eq!(cap.context().unwrap(), std::ptr::null_mut()); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/none.rs
use crate::ffi_ptr_ext::FfiPtrExt; use crate::{ffi, types::any::PyAnyMethods, Borrowed, Bound, PyAny, PyObject, PyTypeInfo, Python}; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; /// Represents the Python `None` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyNone>`][crate::Py] or [`Bound<'py, PyNone>`][Bound]. #[repr(transparent)] pub struct PyNone(PyAny); pyobject_native_type_named!(PyNone); impl PyNone { /// Returns the `None` object. #[inline] pub fn get(py: Python<'_>) -> Borrowed<'_, '_, PyNone> { unsafe { ffi::Py_None().assume_borrowed(py).downcast_unchecked() } } /// Deprecated name for [`PyNone::get`]. #[deprecated(since = "0.23.0", note = "renamed to `PyNone::get`")] #[inline] pub fn get_bound(py: Python<'_>) -> Borrowed<'_, '_, PyNone> { Self::get(py) } } unsafe impl PyTypeInfo for PyNone { const NAME: &'static str = "NoneType"; const MODULE: Option<&'static str> = None; fn type_object_raw(_py: Python<'_>) -> *mut ffi::PyTypeObject { unsafe { ffi::Py_TYPE(ffi::Py_None()) } } #[inline] fn is_type_of(object: &Bound<'_, PyAny>) -> bool { // NoneType is not usable as a base type Self::is_exact_type_of(object) } #[inline] fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool { object.is(&**Self::get(object.py())) } } /// `()` is converted to Python `None`. #[allow(deprecated)] impl ToPyObject for () { fn to_object(&self, py: Python<'_>) -> PyObject { PyNone::get(py).into_py(py) } } #[allow(deprecated)] impl IntoPy<PyObject> for () { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { PyNone::get(py).into_py(py) } } #[cfg(test)] mod tests { use crate::types::any::PyAnyMethods; use crate::types::{PyDict, PyNone}; use crate::{PyObject, PyTypeInfo, Python}; #[test] fn test_none_is_itself() { Python::with_gil(|py| { assert!(PyNone::get(py).is_instance_of::<PyNone>()); assert!(PyNone::get(py).is_exact_instance_of::<PyNone>()); }) } #[test] fn test_none_type_object_consistent() { Python::with_gil(|py| { assert!(PyNone::get(py).get_type().is(&PyNone::type_object(py))); }) } #[test] fn test_none_is_none() { Python::with_gil(|py| { assert!(PyNone::get(py).downcast::<PyNone>().unwrap().is_none()); }) } #[test] #[allow(deprecated)] fn test_unit_to_object_is_none() { use crate::ToPyObject; Python::with_gil(|py| { assert!(().to_object(py).downcast_bound::<PyNone>(py).is_ok()); }) } #[test] #[allow(deprecated)] fn test_unit_into_py_is_none() { use crate::IntoPy; Python::with_gil(|py| { let obj: PyObject = ().into_py(py); assert!(obj.downcast_bound::<PyNone>(py).is_ok()); }) } #[test] fn test_dict_is_not_none() { Python::with_gil(|py| { assert!(PyDict::new(py).downcast::<PyNone>().is_err()); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/typeobject.rs
use crate::err::{self, PyResult}; use crate::instance::Borrowed; #[cfg(not(Py_3_13))] use crate::pybacked::PyBackedStr; use crate::types::any::PyAnyMethods; use crate::types::PyTuple; use crate::{ffi, Bound, PyAny, PyTypeInfo, Python}; use super::PyString; /// Represents a reference to a Python `type` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyType>`][crate::Py] or [`Bound<'py, PyType>`][Bound]. /// /// For APIs available on `type` objects, see the [`PyTypeMethods`] trait which is implemented for /// [`Bound<'py, PyType>`][Bound]. #[repr(transparent)] pub struct PyType(PyAny); pyobject_native_type_core!(PyType, pyobject_native_static_type_object!(ffi::PyType_Type), #checkfunction=ffi::PyType_Check); impl PyType { /// Creates a new type object. #[inline] pub fn new<T: PyTypeInfo>(py: Python<'_>) -> Bound<'_, PyType> { T::type_object(py) } /// Deprecated name for [`PyType::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyType::new`")] #[inline] pub fn new_bound<T: PyTypeInfo>(py: Python<'_>) -> Bound<'_, PyType> { Self::new::<T>(py) } /// Converts the given FFI pointer into `Bound<PyType>`, to use in safe code. /// /// The function creates a new reference from the given pointer, and returns /// it as a `Bound<PyType>`. /// /// # Safety /// - The pointer must be a valid non-null reference to a `PyTypeObject` #[inline] pub unsafe fn from_borrowed_type_ptr( py: Python<'_>, p: *mut ffi::PyTypeObject, ) -> Bound<'_, PyType> { Borrowed::from_ptr_unchecked(py, p.cast()) .downcast_unchecked() .to_owned() } } /// Implementation of functionality for [`PyType`]. /// /// These methods are defined for the `Bound<'py, PyType>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyType")] pub trait PyTypeMethods<'py>: crate::sealed::Sealed { /// Retrieves the underlying FFI pointer associated with this Python object. fn as_type_ptr(&self) -> *mut ffi::PyTypeObject; /// Gets the name of the `PyType`. Equivalent to `self.__name__` in Python. fn name(&self) -> PyResult<Bound<'py, PyString>>; /// Gets the [qualified name](https://docs.python.org/3/glossary.html#term-qualified-name) of the `PyType`. /// Equivalent to `self.__qualname__` in Python. fn qualname(&self) -> PyResult<Bound<'py, PyString>>; /// Gets the name of the module defining the `PyType`. fn module(&self) -> PyResult<Bound<'py, PyString>>; /// Gets the [fully qualified name](https://peps.python.org/pep-0737/#add-pytype-getfullyqualifiedname-function) of the `PyType`. fn fully_qualified_name(&self) -> PyResult<Bound<'py, PyString>>; /// Checks whether `self` is a subclass of `other`. /// /// Equivalent to the Python expression `issubclass(self, other)`. fn is_subclass(&self, other: &Bound<'_, PyAny>) -> PyResult<bool>; /// Checks whether `self` is a subclass of type `T`. /// /// Equivalent to the Python expression `issubclass(self, T)`, if the type /// `T` is known at compile time. fn is_subclass_of<T>(&self) -> PyResult<bool> where T: PyTypeInfo; /// Return the method resolution order for this type. /// /// Equivalent to the Python expression `self.__mro__`. fn mro(&self) -> Bound<'py, PyTuple>; /// Return Python bases /// /// Equivalent to the Python expression `self.__bases__`. fn bases(&self) -> Bound<'py, PyTuple>; } impl<'py> PyTypeMethods<'py> for Bound<'py, PyType> { /// Retrieves the underlying FFI pointer associated with this Python object. #[inline] fn as_type_ptr(&self) -> *mut ffi::PyTypeObject { self.as_ptr() as *mut ffi::PyTypeObject } /// Gets the name of the `PyType`. fn name(&self) -> PyResult<Bound<'py, PyString>> { #[cfg(not(Py_3_11))] let name = self .getattr(intern!(self.py(), "__name__"))? .downcast_into()?; #[cfg(Py_3_11)] let name = unsafe { use crate::ffi_ptr_ext::FfiPtrExt; ffi::PyType_GetName(self.as_type_ptr()) .assume_owned_or_err(self.py())? // SAFETY: setting `__name__` from Python is required to be a `str` .downcast_into_unchecked() }; Ok(name) } /// Gets the [qualified name](https://docs.python.org/3/glossary.html#term-qualified-name) of the `PyType`. fn qualname(&self) -> PyResult<Bound<'py, PyString>> { #[cfg(not(Py_3_11))] let name = self .getattr(intern!(self.py(), "__qualname__"))? .downcast_into()?; #[cfg(Py_3_11)] let name = unsafe { use crate::ffi_ptr_ext::FfiPtrExt; ffi::PyType_GetQualName(self.as_type_ptr()) .assume_owned_or_err(self.py())? // SAFETY: setting `__qualname__` from Python is required to be a `str` .downcast_into_unchecked() }; Ok(name) } /// Gets the name of the module defining the `PyType`. fn module(&self) -> PyResult<Bound<'py, PyString>> { #[cfg(not(Py_3_13))] let name = self.getattr(intern!(self.py(), "__module__"))?; #[cfg(Py_3_13)] let name = unsafe { use crate::ffi_ptr_ext::FfiPtrExt; ffi::PyType_GetModuleName(self.as_type_ptr()).assume_owned_or_err(self.py())? }; // `__module__` is never guaranteed to be a `str` name.downcast_into().map_err(Into::into) } /// Gets the [fully qualified name](https://docs.python.org/3/glossary.html#term-qualified-name) of the `PyType`. fn fully_qualified_name(&self) -> PyResult<Bound<'py, PyString>> { #[cfg(not(Py_3_13))] let name = { let module = self.getattr(intern!(self.py(), "__module__"))?; let qualname = self.getattr(intern!(self.py(), "__qualname__"))?; let module_str = module.extract::<PyBackedStr>()?; if module_str == "builtins" || module_str == "__main__" { qualname.downcast_into()? } else { PyString::new(self.py(), &format!("{}.{}", module, qualname)) } }; #[cfg(Py_3_13)] let name = unsafe { use crate::ffi_ptr_ext::FfiPtrExt; ffi::PyType_GetFullyQualifiedName(self.as_type_ptr()) .assume_owned_or_err(self.py())? .downcast_into_unchecked() }; Ok(name) } /// Checks whether `self` is a subclass of `other`. /// /// Equivalent to the Python expression `issubclass(self, other)`. fn is_subclass(&self, other: &Bound<'_, PyAny>) -> PyResult<bool> { let result = unsafe { ffi::PyObject_IsSubclass(self.as_ptr(), other.as_ptr()) }; err::error_on_minusone(self.py(), result)?; Ok(result == 1) } /// Checks whether `self` is a subclass of type `T`. /// /// Equivalent to the Python expression `issubclass(self, T)`, if the type /// `T` is known at compile time. fn is_subclass_of<T>(&self) -> PyResult<bool> where T: PyTypeInfo, { self.is_subclass(&T::type_object(self.py())) } fn mro(&self) -> Bound<'py, PyTuple> { #[cfg(any(Py_LIMITED_API, PyPy))] let mro = self .getattr(intern!(self.py(), "__mro__")) .expect("Cannot get `__mro__` from object.") .extract() .expect("Unexpected type in `__mro__` attribute."); #[cfg(not(any(Py_LIMITED_API, PyPy)))] let mro = unsafe { use crate::ffi_ptr_ext::FfiPtrExt; (*self.as_type_ptr()) .tp_mro .assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked() }; mro } fn bases(&self) -> Bound<'py, PyTuple> { #[cfg(any(Py_LIMITED_API, PyPy))] let bases = self .getattr(intern!(self.py(), "__bases__")) .expect("Cannot get `__bases__` from object.") .extract() .expect("Unexpected type in `__bases__` attribute."); #[cfg(not(any(Py_LIMITED_API, PyPy)))] let bases = unsafe { use crate::ffi_ptr_ext::FfiPtrExt; (*self.as_type_ptr()) .tp_bases .assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked() }; bases } } #[cfg(test)] mod tests { use crate::tests::common::generate_unique_module_name; use crate::types::{PyAnyMethods, PyBool, PyInt, PyModule, PyTuple, PyType, PyTypeMethods}; use crate::PyAny; use crate::Python; use pyo3_ffi::c_str; #[test] fn test_type_is_subclass() { Python::with_gil(|py| { let bool_type = py.get_type::<PyBool>(); let long_type = py.get_type::<PyInt>(); assert!(bool_type.is_subclass(&long_type).unwrap()); }); } #[test] fn test_type_is_subclass_of() { Python::with_gil(|py| { assert!(py.get_type::<PyBool>().is_subclass_of::<PyInt>().unwrap()); }); } #[test] fn test_mro() { Python::with_gil(|py| { assert!(py .get_type::<PyBool>() .mro() .eq(PyTuple::new( py, [ py.get_type::<PyBool>(), py.get_type::<PyInt>(), py.get_type::<PyAny>() ] ) .unwrap()) .unwrap()); }); } #[test] fn test_bases_bool() { Python::with_gil(|py| { assert!(py .get_type::<PyBool>() .bases() .eq(PyTuple::new(py, [py.get_type::<PyInt>()]).unwrap()) .unwrap()); }); } #[test] fn test_bases_object() { Python::with_gil(|py| { assert!(py .get_type::<PyAny>() .bases() .eq(PyTuple::empty(py)) .unwrap()); }); } #[test] fn test_type_names_standard() { Python::with_gil(|py| { let module_name = generate_unique_module_name("test_module"); let module = PyModule::from_code( py, c_str!( r#" class MyClass: pass "# ), c_str!(file!()), &module_name, ) .expect("module create failed"); let my_class = module.getattr("MyClass").unwrap(); let my_class_type = my_class.downcast_into::<PyType>().unwrap(); assert_eq!(my_class_type.name().unwrap(), "MyClass"); assert_eq!(my_class_type.qualname().unwrap(), "MyClass"); let module_name = module_name.to_str().unwrap(); let qualname = format!("{module_name}.MyClass"); assert_eq!(my_class_type.module().unwrap(), module_name); assert_eq!( my_class_type.fully_qualified_name().unwrap(), qualname.as_str() ); }); } #[test] fn test_type_names_builtin() { Python::with_gil(|py| { let bool_type = py.get_type::<PyBool>(); assert_eq!(bool_type.name().unwrap(), "bool"); assert_eq!(bool_type.qualname().unwrap(), "bool"); assert_eq!(bool_type.module().unwrap(), "builtins"); assert_eq!(bool_type.fully_qualified_name().unwrap(), "bool"); }); } #[test] fn test_type_names_nested() { Python::with_gil(|py| { let module_name = generate_unique_module_name("test_module"); let module = PyModule::from_code( py, c_str!( r#" class OuterClass: class InnerClass: pass "# ), c_str!(file!()), &module_name, ) .expect("module create failed"); let outer_class = module.getattr("OuterClass").unwrap(); let inner_class = outer_class.getattr("InnerClass").unwrap(); let inner_class_type = inner_class.downcast_into::<PyType>().unwrap(); assert_eq!(inner_class_type.name().unwrap(), "InnerClass"); assert_eq!( inner_class_type.qualname().unwrap(), "OuterClass.InnerClass" ); let module_name = module_name.to_str().unwrap(); let qualname = format!("{module_name}.OuterClass.InnerClass"); assert_eq!(inner_class_type.module().unwrap(), module_name); assert_eq!( inner_class_type.fully_qualified_name().unwrap(), qualname.as_str() ); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/pysuper.rs
use crate::instance::Bound; use crate::types::any::PyAnyMethods; use crate::types::PyType; use crate::{ffi, PyTypeInfo}; use crate::{PyAny, PyResult}; /// Represents a Python `super` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PySuper>`][crate::Py] or [`Bound<'py, PySuper>`][Bound]. #[repr(transparent)] pub struct PySuper(PyAny); pyobject_native_type_core!( PySuper, pyobject_native_static_type_object!(ffi::PySuper_Type) ); impl PySuper { /// Constructs a new super object. More read about super object: [docs](https://docs.python.org/3/library/functions.html#super) /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pyclass(subclass)] /// struct BaseClass { /// val1: usize, /// } /// /// #[pymethods] /// impl BaseClass { /// #[new] /// fn new() -> Self { /// BaseClass { val1: 10 } /// } /// /// pub fn method(&self) -> usize { /// self.val1 /// } /// } /// /// #[pyclass(extends=BaseClass)] /// struct SubClass {} /// /// #[pymethods] /// impl SubClass { /// #[new] /// fn new() -> (Self, BaseClass) { /// (SubClass {}, BaseClass::new()) /// } /// /// fn method<'py>(self_: &Bound<'py, Self>) -> PyResult<Bound<'py, PyAny>> { /// let super_ = self_.py_super()?; /// super_.call_method("method", (), None) /// } /// } /// ``` pub fn new<'py>( ty: &Bound<'py, PyType>, obj: &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PySuper>> { PySuper::type_object(ty.py()).call1((ty, obj)).map(|any| { // Safety: super() always returns instance of super unsafe { any.downcast_into_unchecked() } }) } /// Deprecated name for [`PySuper::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PySuper::new`")] #[inline] pub fn new_bound<'py>( ty: &Bound<'py, PyType>, obj: &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PySuper>> { Self::new(ty, obj) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/num.rs
use super::any::PyAnyMethods; use crate::{ffi, instance::Bound, PyAny}; /// Represents a Python `int` object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyInt>`][crate::Py] or [`Bound<'py, PyInt>`][crate::Bound]. /// /// You can usually avoid directly working with this type /// by using [`ToPyObject`](crate::conversion::ToPyObject) /// and [`extract`](super::PyAnyMethods::extract) /// with the primitive Rust integer types. #[repr(transparent)] pub struct PyInt(PyAny); pyobject_native_type_core!(PyInt, pyobject_native_static_type_object!(ffi::PyLong_Type), #checkfunction=ffi::PyLong_Check); /// Deprecated alias for [`PyInt`]. #[deprecated(since = "0.23.0", note = "use `PyInt` instead")] pub type PyLong = PyInt; macro_rules! int_compare { ($rust_type: ty) => { impl PartialEq<$rust_type> for Bound<'_, PyInt> { #[inline] fn eq(&self, other: &$rust_type) -> bool { if let Ok(value) = self.extract::<$rust_type>() { value == *other } else { false } } } impl PartialEq<Bound<'_, PyInt>> for $rust_type { #[inline] fn eq(&self, other: &Bound<'_, PyInt>) -> bool { if let Ok(value) = other.extract::<$rust_type>() { value == *self } else { false } } } }; } int_compare!(i8); int_compare!(u8); int_compare!(i16); int_compare!(u16); int_compare!(i32); int_compare!(u32); int_compare!(i64); int_compare!(u64); int_compare!(i128); int_compare!(u128); int_compare!(isize); int_compare!(usize); #[cfg(test)] mod tests { use crate::{IntoPyObject, Python}; #[test] fn test_partial_eq() { Python::with_gil(|py| { let v_i8 = 123i8; let v_u8 = 123i8; let v_i16 = 123i16; let v_u16 = 123u16; let v_i32 = 123i32; let v_u32 = 123u32; let v_i64 = 123i64; let v_u64 = 123u64; let v_i128 = 123i128; let v_u128 = 123u128; let v_isize = 123isize; let v_usize = 123usize; let obj = 123_i64.into_pyobject(py).unwrap(); assert_eq!(v_i8, obj); assert_eq!(obj, v_i8); assert_eq!(v_u8, obj); assert_eq!(obj, v_u8); assert_eq!(v_i16, obj); assert_eq!(obj, v_i16); assert_eq!(v_u16, obj); assert_eq!(obj, v_u16); assert_eq!(v_i32, obj); assert_eq!(obj, v_i32); assert_eq!(v_u32, obj); assert_eq!(obj, v_u32); assert_eq!(v_i64, obj); assert_eq!(obj, v_i64); assert_eq!(v_u64, obj); assert_eq!(obj, v_u64); assert_eq!(v_i128, obj); assert_eq!(obj, v_i128); assert_eq!(v_u128, obj); assert_eq!(obj, v_u128); assert_eq!(v_isize, obj); assert_eq!(obj, v_isize); assert_eq!(v_usize, obj); assert_eq!(obj, v_usize); let big_num = (u8::MAX as u16) + 1; let big_obj = big_num.into_pyobject(py).unwrap(); for x in 0u8..=u8::MAX { assert_ne!(x, big_obj); assert_ne!(big_obj, x); } }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/iterator.rs
use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Borrowed; use crate::py_result_ext::PyResultExt; use crate::{ffi, Bound, PyAny, PyErr, PyResult, PyTypeCheck}; /// A Python iterator object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyIterator>`][crate::Py] or [`Bound<'py, PyIterator>`][Bound]. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::ffi::c_str; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let list = py.eval(c_str!("iter([1, 2, 3, 4])"), None, None)?; /// let numbers: PyResult<Vec<usize>> = list /// .try_iter()? /// .map(|i| i.and_then(|i|i.extract::<usize>())) /// .collect(); /// let sum: usize = numbers?.iter().sum(); /// assert_eq!(sum, 10); /// Ok(()) /// }) /// # } /// ``` #[repr(transparent)] pub struct PyIterator(PyAny); pyobject_native_type_named!(PyIterator); impl PyIterator { /// Builds an iterator for an iterable Python object; the equivalent of calling `iter(obj)` in Python. /// /// Usually it is more convenient to write [`obj.iter()`][crate::types::any::PyAnyMethods::iter], /// which is a more concise way of calling this function. pub fn from_object<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyIterator>> { unsafe { ffi::PyObject_GetIter(obj.as_ptr()) .assume_owned_or_err(obj.py()) .downcast_into_unchecked() } } /// Deprecated name for [`PyIterator::from_object`]. #[deprecated(since = "0.23.0", note = "renamed to `PyIterator::from_object`")] #[inline] pub fn from_bound_object<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyIterator>> { Self::from_object(obj) } } impl<'py> Iterator for Bound<'py, PyIterator> { type Item = PyResult<Bound<'py, PyAny>>; /// Retrieves the next item from an iterator. /// /// Returns `None` when the iterator is exhausted. /// If an exception occurs, returns `Some(Err(..))`. /// Further `next()` calls after an exception occurs are likely /// to repeatedly result in the same exception. #[inline] fn next(&mut self) -> Option<Self::Item> { Borrowed::from(&*self).next() } #[cfg(not(Py_LIMITED_API))] fn size_hint(&self) -> (usize, Option<usize>) { let hint = unsafe { ffi::PyObject_LengthHint(self.as_ptr(), 0) }; (hint.max(0) as usize, None) } } impl<'py> Borrowed<'_, 'py, PyIterator> { // TODO: this method is on Borrowed so that &'py PyIterator can use this; once that // implementation is deleted this method should be moved to the `Bound<'py, PyIterator> impl fn next(self) -> Option<PyResult<Bound<'py, PyAny>>> { let py = self.py(); match unsafe { ffi::PyIter_Next(self.as_ptr()).assume_owned_or_opt(py) } { Some(obj) => Some(Ok(obj)), None => PyErr::take(py).map(Err), } } } impl<'py> IntoIterator for &Bound<'py, PyIterator> { type Item = PyResult<Bound<'py, PyAny>>; type IntoIter = Bound<'py, PyIterator>; fn into_iter(self) -> Self::IntoIter { self.clone() } } impl PyTypeCheck for PyIterator { const NAME: &'static str = "Iterator"; fn type_check(object: &Bound<'_, PyAny>) -> bool { unsafe { ffi::PyIter_Check(object.as_ptr()) != 0 } } } #[cfg(test)] mod tests { use super::PyIterator; use crate::exceptions::PyTypeError; use crate::types::{PyAnyMethods, PyDict, PyList, PyListMethods}; use crate::{ffi, IntoPyObject, Python}; #[test] fn vec_iter() { Python::with_gil(|py| { let inst = vec![10, 20].into_pyobject(py).unwrap(); let mut it = inst.try_iter().unwrap(); assert_eq!( 10_i32, it.next().unwrap().unwrap().extract::<'_, i32>().unwrap() ); assert_eq!( 20_i32, it.next().unwrap().unwrap().extract::<'_, i32>().unwrap() ); assert!(it.next().is_none()); }); } #[test] fn iter_refcnt() { let (obj, count) = Python::with_gil(|py| { let obj = vec![10, 20].into_pyobject(py).unwrap(); let count = obj.get_refcnt(); (obj.unbind(), count) }); Python::with_gil(|py| { let inst = obj.bind(py); let mut it = inst.try_iter().unwrap(); assert_eq!( 10_i32, it.next().unwrap().unwrap().extract::<'_, i32>().unwrap() ); }); Python::with_gil(move |py| { assert_eq!(count, obj.get_refcnt(py)); }); } #[test] fn iter_item_refcnt() { Python::with_gil(|py| { let count; let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap(); let list = { let list = PyList::empty(py); list.append(10).unwrap(); list.append(&obj).unwrap(); count = obj.get_refcnt(); list }; { let mut it = list.iter(); assert_eq!(10_i32, it.next().unwrap().extract::<'_, i32>().unwrap()); assert!(it.next().unwrap().is(&obj)); assert!(it.next().is_none()); } assert_eq!(count, obj.get_refcnt()); }); } #[test] fn fibonacci_generator() { let fibonacci_generator = ffi::c_str!( r#" def fibonacci(target): a = 1 b = 1 for _ in range(target): yield a a, b = b, a + b "# ); Python::with_gil(|py| { let context = PyDict::new(py); py.run(fibonacci_generator, None, Some(&context)).unwrap(); let generator = py .eval(ffi::c_str!("fibonacci(5)"), None, Some(&context)) .unwrap(); for (actual, expected) in generator.try_iter().unwrap().zip(&[1, 1, 2, 3, 5]) { let actual = actual.unwrap().extract::<usize>().unwrap(); assert_eq!(actual, *expected) } }); } #[test] fn fibonacci_generator_bound() { use crate::types::any::PyAnyMethods; use crate::Bound; let fibonacci_generator = ffi::c_str!( r#" def fibonacci(target): a = 1 b = 1 for _ in range(target): yield a a, b = b, a + b "# ); Python::with_gil(|py| { let context = PyDict::new(py); py.run(fibonacci_generator, None, Some(&context)).unwrap(); let generator: Bound<'_, PyIterator> = py .eval(ffi::c_str!("fibonacci(5)"), None, Some(&context)) .unwrap() .downcast_into() .unwrap(); let mut items = vec![]; for actual in &generator { let actual = actual.unwrap().extract::<usize>().unwrap(); items.push(actual); } assert_eq!(items, [1, 1, 2, 3, 5]); }); } #[test] fn int_not_iterable() { Python::with_gil(|py| { let x = 5i32.into_pyobject(py).unwrap(); let err = PyIterator::from_object(&x).unwrap_err(); assert!(err.is_instance_of::<PyTypeError>(py)); }); } #[test] #[cfg(feature = "macros")] fn python_class_not_iterator() { use crate::PyErr; #[crate::pyclass(crate = "crate")] struct Downcaster { failed: Option<PyErr>, } #[crate::pymethods(crate = "crate")] impl Downcaster { fn downcast_iterator(&mut self, obj: &crate::Bound<'_, crate::PyAny>) { self.failed = Some(obj.downcast::<PyIterator>().unwrap_err().into()); } } // Regression test for 2913 Python::with_gil(|py| { let downcaster = crate::Py::new(py, Downcaster { failed: None }).unwrap(); crate::py_run!( py, downcaster, r#" from collections.abc import Sequence class MySequence(Sequence): def __init__(self): self._data = [1, 2, 3] def __getitem__(self, index): return self._data[index] def __len__(self): return len(self._data) downcaster.downcast_iterator(MySequence()) "# ); assert_eq!( downcaster.borrow_mut(py).failed.take().unwrap().to_string(), "TypeError: 'MySequence' object cannot be converted to 'Iterator'" ); }); } #[test] #[cfg(feature = "macros")] fn python_class_iterator() { #[crate::pyfunction(crate = "crate")] fn assert_iterator(obj: &crate::Bound<'_, crate::PyAny>) { assert!(obj.downcast::<PyIterator>().is_ok()) } // Regression test for 2913 Python::with_gil(|py| { let assert_iterator = crate::wrap_pyfunction!(assert_iterator, py).unwrap(); crate::py_run!( py, assert_iterator, r#" class MyIter: def __next__(self): raise StopIteration assert_iterator(MyIter()) "# ); }); } #[test] #[cfg(not(Py_LIMITED_API))] fn length_hint_becomes_size_hint_lower_bound() { Python::with_gil(|py| { let list = py.eval(ffi::c_str!("[1, 2, 3]"), None, None).unwrap(); let iter = list.try_iter().unwrap(); let hint = iter.size_hint(); assert_eq!(hint, (3, None)); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/mapping.rs
use crate::conversion::IntoPyObject; use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Bound; use crate::py_result_ext::PyResultExt; use crate::sync::GILOnceCell; use crate::type_object::PyTypeInfo; use crate::types::any::PyAnyMethods; use crate::types::{PyAny, PyDict, PyList, PyType}; use crate::{ffi, Py, PyTypeCheck, Python}; /// Represents a reference to a Python object supporting the mapping protocol. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyMapping>`][crate::Py] or [`Bound<'py, PyMapping>`][Bound]. /// /// For APIs available on mapping objects, see the [`PyMappingMethods`] trait which is implemented for /// [`Bound<'py, PyMapping>`][Bound]. #[repr(transparent)] pub struct PyMapping(PyAny); pyobject_native_type_named!(PyMapping); impl PyMapping { /// Register a pyclass as a subclass of `collections.abc.Mapping` (from the Python standard /// library). This is equivalent to `collections.abc.Mapping.register(T)` in Python. /// This registration is required for a pyclass to be downcastable from `PyAny` to `PyMapping`. pub fn register<T: PyTypeInfo>(py: Python<'_>) -> PyResult<()> { let ty = T::type_object(py); get_mapping_abc(py)?.call_method1("register", (ty,))?; Ok(()) } } /// Implementation of functionality for [`PyMapping`]. /// /// These methods are defined for the `Bound<'py, PyMapping>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyMapping")] pub trait PyMappingMethods<'py>: crate::sealed::Sealed { /// Returns the number of objects in the mapping. /// /// This is equivalent to the Python expression `len(self)`. fn len(&self) -> PyResult<usize>; /// Returns whether the mapping is empty. fn is_empty(&self) -> PyResult<bool>; /// Determines if the mapping contains the specified key. /// /// This is equivalent to the Python expression `key in self`. fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>; /// Gets the item in self with key `key`. /// /// Returns an `Err` if the item with specified key is not found, usually `KeyError`. /// /// This is equivalent to the Python expression `self[key]`. fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>> where K: IntoPyObject<'py>; /// Sets the item in self with key `key`. /// /// This is equivalent to the Python expression `self[key] = value`. fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()> where K: IntoPyObject<'py>, V: IntoPyObject<'py>; /// Deletes the item with key `key`. /// /// This is equivalent to the Python statement `del self[key]`. fn del_item<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>; /// Returns a list containing all keys in the mapping. fn keys(&self) -> PyResult<Bound<'py, PyList>>; /// Returns a list containing all values in the mapping. fn values(&self) -> PyResult<Bound<'py, PyList>>; /// Returns a list of all (key, value) pairs in the mapping. fn items(&self) -> PyResult<Bound<'py, PyList>>; } impl<'py> PyMappingMethods<'py> for Bound<'py, PyMapping> { #[inline] fn len(&self) -> PyResult<usize> { let v = unsafe { ffi::PyMapping_Size(self.as_ptr()) }; crate::err::error_on_minusone(self.py(), v)?; Ok(v as usize) } #[inline] fn is_empty(&self) -> PyResult<bool> { self.len().map(|l| l == 0) } fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>, { PyAnyMethods::contains(&**self, key) } #[inline] fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>> where K: IntoPyObject<'py>, { PyAnyMethods::get_item(&**self, key) } #[inline] fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()> where K: IntoPyObject<'py>, V: IntoPyObject<'py>, { PyAnyMethods::set_item(&**self, key, value) } #[inline] fn del_item<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>, { PyAnyMethods::del_item(&**self, key) } #[inline] fn keys(&self) -> PyResult<Bound<'py, PyList>> { unsafe { ffi::PyMapping_Keys(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn values(&self) -> PyResult<Bound<'py, PyList>> { unsafe { ffi::PyMapping_Values(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[inline] fn items(&self) -> PyResult<Bound<'py, PyList>> { unsafe { ffi::PyMapping_Items(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } } fn get_mapping_abc(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> { static MAPPING_ABC: GILOnceCell<Py<PyType>> = GILOnceCell::new(); MAPPING_ABC.import(py, "collections.abc", "Mapping") } impl PyTypeCheck for PyMapping { const NAME: &'static str = "Mapping"; #[inline] fn type_check(object: &Bound<'_, PyAny>) -> bool { // Using `is_instance` for `collections.abc.Mapping` is slow, so provide // optimized case dict as a well-known mapping PyDict::is_type_of(object) || get_mapping_abc(object.py()) .and_then(|abc| object.is_instance(abc)) .unwrap_or_else(|err| { err.write_unraisable(object.py(), Some(object)); false }) } } #[cfg(test)] mod tests { use std::collections::HashMap; use crate::{exceptions::PyKeyError, types::PyTuple}; use super::*; use crate::conversion::IntoPyObject; #[test] fn test_len() { Python::with_gil(|py| { let mut v = HashMap::<i32, i32>::new(); let ob = (&v).into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); assert_eq!(0, mapping.len().unwrap()); assert!(mapping.is_empty().unwrap()); v.insert(7, 32); let ob = v.into_pyobject(py).unwrap(); let mapping2 = ob.downcast::<PyMapping>().unwrap(); assert_eq!(1, mapping2.len().unwrap()); assert!(!mapping2.is_empty().unwrap()); }); } #[test] fn test_contains() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert("key0", 1234); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); mapping.set_item("key1", "foo").unwrap(); assert!(mapping.contains("key0").unwrap()); assert!(mapping.contains("key1").unwrap()); assert!(!mapping.contains("key2").unwrap()); }); } #[test] fn test_get_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); assert_eq!( 32, mapping.get_item(7i32).unwrap().extract::<i32>().unwrap() ); assert!(mapping .get_item(8i32) .unwrap_err() .is_instance_of::<PyKeyError>(py)); }); } #[test] fn test_set_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); assert!(mapping.set_item(7i32, 42i32).is_ok()); // change assert!(mapping.set_item(8i32, 123i32).is_ok()); // insert assert_eq!( 42i32, mapping.get_item(7i32).unwrap().extract::<i32>().unwrap() ); assert_eq!( 123i32, mapping.get_item(8i32).unwrap().extract::<i32>().unwrap() ); }); } #[test] fn test_del_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); assert!(mapping.del_item(7i32).is_ok()); assert_eq!(0, mapping.len().unwrap()); assert!(mapping .get_item(7i32) .unwrap_err() .is_instance_of::<PyKeyError>(py)); }); } #[test] fn test_items() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; let mut value_sum = 0; for el in mapping.items().unwrap().try_iter().unwrap() { let tuple = el.unwrap().downcast_into::<PyTuple>().unwrap(); key_sum += tuple.get_item(0).unwrap().extract::<i32>().unwrap(); value_sum += tuple.get_item(1).unwrap().extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_keys() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; for el in mapping.keys().unwrap().try_iter().unwrap() { key_sum += el.unwrap().extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); }); } #[test] fn test_values() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let ob = v.into_pyobject(py).unwrap(); let mapping = ob.downcast::<PyMapping>().unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0; for el in mapping.values().unwrap().try_iter().unwrap() { values_sum += el.unwrap().extract::<i32>().unwrap(); } assert_eq!(32 + 42 + 123, values_sum); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/dict.rs
use crate::err::{self, PyErr, PyResult}; use crate::ffi::Py_ssize_t; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::{Borrowed, Bound}; use crate::py_result_ext::PyResultExt; use crate::types::{PyAny, PyAnyMethods, PyList, PyMapping}; use crate::{ffi, BoundObject, IntoPyObject, Python}; /// Represents a Python `dict`. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyDict>`][crate::Py] or [`Bound<'py, PyDict>`][Bound]. /// /// For APIs available on `dict` objects, see the [`PyDictMethods`] trait which is implemented for /// [`Bound<'py, PyDict>`][Bound]. #[repr(transparent)] pub struct PyDict(PyAny); pyobject_subclassable_native_type!(PyDict, crate::ffi::PyDictObject); pyobject_native_type!( PyDict, ffi::PyDictObject, pyobject_native_static_type_object!(ffi::PyDict_Type), #checkfunction=ffi::PyDict_Check ); /// Represents a Python `dict_keys`. #[cfg(not(any(PyPy, GraalPy)))] #[repr(transparent)] pub struct PyDictKeys(PyAny); #[cfg(not(any(PyPy, GraalPy)))] pyobject_native_type_core!( PyDictKeys, pyobject_native_static_type_object!(ffi::PyDictKeys_Type), #checkfunction=ffi::PyDictKeys_Check ); /// Represents a Python `dict_values`. #[cfg(not(any(PyPy, GraalPy)))] #[repr(transparent)] pub struct PyDictValues(PyAny); #[cfg(not(any(PyPy, GraalPy)))] pyobject_native_type_core!( PyDictValues, pyobject_native_static_type_object!(ffi::PyDictValues_Type), #checkfunction=ffi::PyDictValues_Check ); /// Represents a Python `dict_items`. #[cfg(not(any(PyPy, GraalPy)))] #[repr(transparent)] pub struct PyDictItems(PyAny); #[cfg(not(any(PyPy, GraalPy)))] pyobject_native_type_core!( PyDictItems, pyobject_native_static_type_object!(ffi::PyDictItems_Type), #checkfunction=ffi::PyDictItems_Check ); impl PyDict { /// Creates a new empty dictionary. pub fn new(py: Python<'_>) -> Bound<'_, PyDict> { unsafe { ffi::PyDict_New().assume_owned(py).downcast_into_unchecked() } } /// Deprecated name for [`PyDict::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyDict::new`")] #[inline] pub fn new_bound(py: Python<'_>) -> Bound<'_, PyDict> { Self::new(py) } /// Creates a new dictionary from the sequence given. /// /// The sequence must consist of `(PyObject, PyObject)`. This is /// equivalent to `dict([("a", 1), ("b", 2)])`. /// /// Returns an error on invalid input. In the case of key collisions, /// this keeps the last entry seen. #[cfg(not(any(PyPy, GraalPy)))] pub fn from_sequence<'py>(seq: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyDict>> { let py = seq.py(); let dict = Self::new(py); err::error_on_minusone(py, unsafe { ffi::PyDict_MergeFromSeq2(dict.as_ptr(), seq.as_ptr(), 1) })?; Ok(dict) } /// Deprecated name for [`PyDict::from_sequence`]. #[cfg(not(any(PyPy, GraalPy)))] #[deprecated(since = "0.23.0", note = "renamed to `PyDict::from_sequence`")] #[inline] pub fn from_sequence_bound<'py>(seq: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyDict>> { Self::from_sequence(seq) } } /// Implementation of functionality for [`PyDict`]. /// /// These methods are defined for the `Bound<'py, PyDict>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyDict")] pub trait PyDictMethods<'py>: crate::sealed::Sealed { /// Returns a new dictionary that contains the same key-value pairs as self. /// /// This is equivalent to the Python expression `self.copy()`. fn copy(&self) -> PyResult<Bound<'py, PyDict>>; /// Empties an existing dictionary of all key-value pairs. fn clear(&self); /// Return the number of items in the dictionary. /// /// This is equivalent to the Python expression `len(self)`. fn len(&self) -> usize; /// Checks if the dict is empty, i.e. `len(self) == 0`. fn is_empty(&self) -> bool; /// Determines if the dictionary contains the specified key. /// /// This is equivalent to the Python expression `key in self`. fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>; /// Gets an item from the dictionary. /// /// Returns `None` if the item is not present, or if an error occurs. /// /// To get a `KeyError` for non-existing keys, use `PyAny::get_item`. fn get_item<K>(&self, key: K) -> PyResult<Option<Bound<'py, PyAny>>> where K: IntoPyObject<'py>; /// Sets an item value. /// /// This is equivalent to the Python statement `self[key] = value`. fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()> where K: IntoPyObject<'py>, V: IntoPyObject<'py>; /// Deletes an item. /// /// This is equivalent to the Python statement `del self[key]`. fn del_item<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>; /// Returns a list of dict keys. /// /// This is equivalent to the Python expression `list(dict.keys())`. fn keys(&self) -> Bound<'py, PyList>; /// Returns a list of dict values. /// /// This is equivalent to the Python expression `list(dict.values())`. fn values(&self) -> Bound<'py, PyList>; /// Returns a list of dict items. /// /// This is equivalent to the Python expression `list(dict.items())`. fn items(&self) -> Bound<'py, PyList>; /// Returns an iterator of `(key, value)` pairs in this dictionary. /// /// # Panics /// /// If PyO3 detects that the dictionary is mutated during iteration, it will panic. /// It is allowed to modify values as you iterate over the dictionary, but only /// so long as the set of keys does not change. fn iter(&self) -> BoundDictIterator<'py>; /// Iterates over the contents of this dictionary while holding a critical section on the dict. /// This is useful when the GIL is disabled and the dictionary is shared between threads. /// It is not guaranteed that the dictionary will not be modified during iteration when the /// closure calls arbitrary Python code that releases the current critical section. /// /// This method is a small performance optimization over `.iter().try_for_each()` when the /// nightly feature is not enabled because we cannot implement an optimised version of /// `iter().try_fold()` on stable yet. If your iteration is infallible then this method has the /// same performance as `.iter().for_each()`. fn locked_for_each<F>(&self, closure: F) -> PyResult<()> where F: Fn(Bound<'py, PyAny>, Bound<'py, PyAny>) -> PyResult<()>; /// Returns `self` cast as a `PyMapping`. fn as_mapping(&self) -> &Bound<'py, PyMapping>; /// Returns `self` cast as a `PyMapping`. fn into_mapping(self) -> Bound<'py, PyMapping>; /// Update this dictionary with the key/value pairs from another. /// /// This is equivalent to the Python expression `self.update(other)`. If `other` is a `PyDict`, you may want /// to use `self.update(other.as_mapping())`, note: `PyDict::as_mapping` is a zero-cost conversion. fn update(&self, other: &Bound<'_, PyMapping>) -> PyResult<()>; /// Add key/value pairs from another dictionary to this one only when they do not exist in this. /// /// This is equivalent to the Python expression `self.update({k: v for k, v in other.items() if k not in self})`. /// If `other` is a `PyDict`, you may want to use `self.update_if_missing(other.as_mapping())`, /// note: `PyDict::as_mapping` is a zero-cost conversion. /// /// This method uses [`PyDict_Merge`](https://docs.python.org/3/c-api/dict.html#c.PyDict_Merge) internally, /// so should have the same performance as `update`. fn update_if_missing(&self, other: &Bound<'_, PyMapping>) -> PyResult<()>; } impl<'py> PyDictMethods<'py> for Bound<'py, PyDict> { fn copy(&self) -> PyResult<Bound<'py, PyDict>> { unsafe { ffi::PyDict_Copy(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } fn clear(&self) { unsafe { ffi::PyDict_Clear(self.as_ptr()) } } fn len(&self) -> usize { dict_len(self) as usize } fn is_empty(&self) -> bool { self.len() == 0 } fn contains<K>(&self, key: K) -> PyResult<bool> where K: IntoPyObject<'py>, { fn inner(dict: &Bound<'_, PyDict>, key: &Bound<'_, PyAny>) -> PyResult<bool> { match unsafe { ffi::PyDict_Contains(dict.as_ptr(), key.as_ptr()) } { 1 => Ok(true), 0 => Ok(false), _ => Err(PyErr::fetch(dict.py())), } } let py = self.py(); inner( self, &key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn get_item<K>(&self, key: K) -> PyResult<Option<Bound<'py, PyAny>>> where K: IntoPyObject<'py>, { fn inner<'py>( dict: &Bound<'py, PyDict>, key: &Bound<'_, PyAny>, ) -> PyResult<Option<Bound<'py, PyAny>>> { let py = dict.py(); let mut result: *mut ffi::PyObject = std::ptr::null_mut(); match unsafe { ffi::compat::PyDict_GetItemRef(dict.as_ptr(), key.as_ptr(), &mut result) } { std::os::raw::c_int::MIN..=-1 => Err(PyErr::fetch(py)), 0 => Ok(None), 1..=std::os::raw::c_int::MAX => { // Safety: PyDict_GetItemRef positive return value means the result is a valid // owned reference Ok(Some(unsafe { result.assume_owned_unchecked(py) })) } } } let py = self.py(); inner( self, &key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()> where K: IntoPyObject<'py>, V: IntoPyObject<'py>, { fn inner( dict: &Bound<'_, PyDict>, key: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>, ) -> PyResult<()> { err::error_on_minusone(dict.py(), unsafe { ffi::PyDict_SetItem(dict.as_ptr(), key.as_ptr(), value.as_ptr()) }) } let py = self.py(); inner( self, &key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), &value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn del_item<K>(&self, key: K) -> PyResult<()> where K: IntoPyObject<'py>, { fn inner(dict: &Bound<'_, PyDict>, key: &Bound<'_, PyAny>) -> PyResult<()> { err::error_on_minusone(dict.py(), unsafe { ffi::PyDict_DelItem(dict.as_ptr(), key.as_ptr()) }) } let py = self.py(); inner( self, &key.into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn keys(&self) -> Bound<'py, PyList> { unsafe { ffi::PyDict_Keys(self.as_ptr()) .assume_owned(self.py()) .downcast_into_unchecked() } } fn values(&self) -> Bound<'py, PyList> { unsafe { ffi::PyDict_Values(self.as_ptr()) .assume_owned(self.py()) .downcast_into_unchecked() } } fn items(&self) -> Bound<'py, PyList> { unsafe { ffi::PyDict_Items(self.as_ptr()) .assume_owned(self.py()) .downcast_into_unchecked() } } fn iter(&self) -> BoundDictIterator<'py> { BoundDictIterator::new(self.clone()) } fn locked_for_each<F>(&self, f: F) -> PyResult<()> where F: Fn(Bound<'py, PyAny>, Bound<'py, PyAny>) -> PyResult<()>, { #[cfg(feature = "nightly")] { // We don't need a critical section when the nightly feature is enabled because // try_for_each is locked by the implementation of try_fold. self.iter().try_for_each(|(key, value)| f(key, value)) } #[cfg(not(feature = "nightly"))] { crate::sync::with_critical_section(self, || { self.iter().try_for_each(|(key, value)| f(key, value)) }) } } fn as_mapping(&self) -> &Bound<'py, PyMapping> { unsafe { self.downcast_unchecked() } } fn into_mapping(self) -> Bound<'py, PyMapping> { unsafe { self.into_any().downcast_into_unchecked() } } fn update(&self, other: &Bound<'_, PyMapping>) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PyDict_Update(self.as_ptr(), other.as_ptr()) }) } fn update_if_missing(&self, other: &Bound<'_, PyMapping>) -> PyResult<()> { err::error_on_minusone(self.py(), unsafe { ffi::PyDict_Merge(self.as_ptr(), other.as_ptr(), 0) }) } } impl<'a, 'py> Borrowed<'a, 'py, PyDict> { /// Iterates over the contents of this dictionary without incrementing reference counts. /// /// # Safety /// It must be known that this dictionary will not be modified during iteration. pub(crate) unsafe fn iter_borrowed(self) -> BorrowedDictIter<'a, 'py> { BorrowedDictIter::new(self) } } fn dict_len(dict: &Bound<'_, PyDict>) -> Py_ssize_t { #[cfg(any(not(Py_3_8), PyPy, GraalPy, Py_LIMITED_API))] unsafe { ffi::PyDict_Size(dict.as_ptr()) } #[cfg(all(Py_3_8, not(PyPy), not(GraalPy), not(Py_LIMITED_API)))] unsafe { (*dict.as_ptr().cast::<ffi::PyDictObject>()).ma_used } } /// PyO3 implementation of an iterator for a Python `dict` object. pub struct BoundDictIterator<'py> { dict: Bound<'py, PyDict>, inner: DictIterImpl, } enum DictIterImpl { DictIter { ppos: ffi::Py_ssize_t, di_used: ffi::Py_ssize_t, remaining: ffi::Py_ssize_t, }, } impl DictIterImpl { #[inline] fn next<'py>( &mut self, dict: &Bound<'py, PyDict>, ) -> Option<(Bound<'py, PyAny>, Bound<'py, PyAny>)> { match self { Self::DictIter { di_used, remaining, ppos, .. } => crate::sync::with_critical_section(dict, || { let ma_used = dict_len(dict); // These checks are similar to what CPython does. // // If the dimension of the dict changes e.g. key-value pairs are removed // or added during iteration, this will panic next time when `next` is called if *di_used != ma_used { *di_used = -1; panic!("dictionary changed size during iteration"); }; // If the dict is changed in such a way that the length remains constant // then this will panic at the end of iteration - similar to this: // // d = {"a":1, "b":2, "c": 3} // // for k, v in d.items(): // d[f"{k}_"] = 4 // del d[k] // print(k) // if *remaining == -1 { *di_used = -1; panic!("dictionary keys changed during iteration"); }; let mut key: *mut ffi::PyObject = std::ptr::null_mut(); let mut value: *mut ffi::PyObject = std::ptr::null_mut(); if unsafe { ffi::PyDict_Next(dict.as_ptr(), ppos, &mut key, &mut value) } != 0 { *remaining -= 1; let py = dict.py(); // Safety: // - PyDict_Next returns borrowed values // - we have already checked that `PyDict_Next` succeeded, so we can assume these to be non-null Some(( unsafe { key.assume_borrowed_unchecked(py) }.to_owned(), unsafe { value.assume_borrowed_unchecked(py) }.to_owned(), )) } else { None } }), } } #[cfg(Py_GIL_DISABLED)] #[inline] fn with_critical_section<F, R>(&mut self, dict: &Bound<'_, PyDict>, f: F) -> R where F: FnOnce(&mut Self) -> R, { match self { Self::DictIter { .. } => crate::sync::with_critical_section(dict, || f(self)), } } } impl<'py> Iterator for BoundDictIterator<'py> { type Item = (Bound<'py, PyAny>, Bound<'py, PyAny>); #[inline] fn next(&mut self) -> Option<Self::Item> { self.inner.next(&self.dict) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } #[inline] #[cfg(Py_GIL_DISABLED)] fn fold<B, F>(mut self, init: B, mut f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { self.inner.with_critical_section(&self.dict, |inner| { let mut accum = init; while let Some(x) = inner.next(&self.dict) { accum = f(accum, x); } accum }) } #[inline] #[cfg(all(Py_GIL_DISABLED, feature = "nightly"))] fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: std::ops::Try<Output = B>, { self.inner.with_critical_section(&self.dict, |inner| { let mut accum = init; while let Some(x) = inner.next(&self.dict) { accum = f(accum, x)? } R::from_output(accum) }) } #[inline] #[cfg(all(Py_GIL_DISABLED, not(feature = "nightly")))] fn all<F>(&mut self, mut f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool, { self.inner.with_critical_section(&self.dict, |inner| { while let Some(x) = inner.next(&self.dict) { if !f(x) { return false; } } true }) } #[inline] #[cfg(all(Py_GIL_DISABLED, not(feature = "nightly")))] fn any<F>(&mut self, mut f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool, { self.inner.with_critical_section(&self.dict, |inner| { while let Some(x) = inner.next(&self.dict) { if f(x) { return true; } } false }) } #[inline] #[cfg(all(Py_GIL_DISABLED, not(feature = "nightly")))] fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where Self: Sized, P: FnMut(&Self::Item) -> bool, { self.inner.with_critical_section(&self.dict, |inner| { while let Some(x) = inner.next(&self.dict) { if predicate(&x) { return Some(x); } } None }) } #[inline] #[cfg(all(Py_GIL_DISABLED, not(feature = "nightly")))] fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where Self: Sized, F: FnMut(Self::Item) -> Option<B>, { self.inner.with_critical_section(&self.dict, |inner| { while let Some(x) = inner.next(&self.dict) { if let found @ Some(_) = f(x) { return found; } } None }) } #[inline] #[cfg(all(Py_GIL_DISABLED, not(feature = "nightly")))] fn position<P>(&mut self, mut predicate: P) -> Option<usize> where Self: Sized, P: FnMut(Self::Item) -> bool, { self.inner.with_critical_section(&self.dict, |inner| { let mut acc = 0; while let Some(x) = inner.next(&self.dict) { if predicate(x) { return Some(acc); } acc += 1; } None }) } } impl ExactSizeIterator for BoundDictIterator<'_> { fn len(&self) -> usize { match self.inner { DictIterImpl::DictIter { remaining, .. } => remaining as usize, } } } impl<'py> BoundDictIterator<'py> { fn new(dict: Bound<'py, PyDict>) -> Self { let remaining = dict_len(&dict); Self { dict, inner: DictIterImpl::DictIter { ppos: 0, di_used: remaining, remaining, }, } } } impl<'py> IntoIterator for Bound<'py, PyDict> { type Item = (Bound<'py, PyAny>, Bound<'py, PyAny>); type IntoIter = BoundDictIterator<'py>; fn into_iter(self) -> Self::IntoIter { BoundDictIterator::new(self) } } impl<'py> IntoIterator for &Bound<'py, PyDict> { type Item = (Bound<'py, PyAny>, Bound<'py, PyAny>); type IntoIter = BoundDictIterator<'py>; fn into_iter(self) -> Self::IntoIter { self.iter() } } mod borrowed_iter { use super::*; /// Variant of the above which is used to iterate the items of the dictionary /// without incrementing reference counts. This is only safe if it's known /// that the dictionary will not be modified during iteration. pub struct BorrowedDictIter<'a, 'py> { dict: Borrowed<'a, 'py, PyDict>, ppos: ffi::Py_ssize_t, len: ffi::Py_ssize_t, } impl<'a, 'py> Iterator for BorrowedDictIter<'a, 'py> { type Item = (Borrowed<'a, 'py, PyAny>, Borrowed<'a, 'py, PyAny>); #[inline] fn next(&mut self) -> Option<Self::Item> { let mut key: *mut ffi::PyObject = std::ptr::null_mut(); let mut value: *mut ffi::PyObject = std::ptr::null_mut(); // Safety: self.dict lives sufficiently long that the pointer is not dangling if unsafe { ffi::PyDict_Next(self.dict.as_ptr(), &mut self.ppos, &mut key, &mut value) } != 0 { let py = self.dict.py(); self.len -= 1; // Safety: // - PyDict_Next returns borrowed values // - we have already checked that `PyDict_Next` succeeded, so we can assume these to be non-null Some(unsafe { (key.assume_borrowed(py), value.assume_borrowed(py)) }) } else { None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } } impl ExactSizeIterator for BorrowedDictIter<'_, '_> { fn len(&self) -> usize { self.len as usize } } impl<'a, 'py> BorrowedDictIter<'a, 'py> { pub(super) fn new(dict: Borrowed<'a, 'py, PyDict>) -> Self { let len = dict_len(&dict); BorrowedDictIter { dict, ppos: 0, len } } } } pub(crate) use borrowed_iter::BorrowedDictIter; /// Conversion trait that allows a sequence of tuples to be converted into `PyDict` /// Primary use case for this trait is `call` and `call_method` methods as keywords argument. pub trait IntoPyDict<'py>: Sized { /// Converts self into a `PyDict` object pointer. Whether pointer owned or borrowed /// depends on implementation. fn into_py_dict(self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>>; /// Deprecated name for [`IntoPyDict::into_py_dict`]. #[deprecated(since = "0.23.0", note = "renamed to `IntoPyDict::into_py_dict`")] #[inline] fn into_py_dict_bound(self, py: Python<'py>) -> Bound<'py, PyDict> { self.into_py_dict(py).unwrap() } } impl<'py, T, I> IntoPyDict<'py> for I where T: PyDictItem<'py>, I: IntoIterator<Item = T>, { fn into_py_dict(self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> { let dict = PyDict::new(py); self.into_iter().try_for_each(|item| { let (key, value) = item.unpack(); dict.set_item(key, value) })?; Ok(dict) } } /// Represents a tuple which can be used as a PyDict item. trait PyDictItem<'py> { type K: IntoPyObject<'py>; type V: IntoPyObject<'py>; fn unpack(self) -> (Self::K, Self::V); } impl<'py, K, V> PyDictItem<'py> for (K, V) where K: IntoPyObject<'py>, V: IntoPyObject<'py>, { type K = K; type V = V; fn unpack(self) -> (Self::K, Self::V) { (self.0, self.1) } } impl<'a, 'py, K, V> PyDictItem<'py> for &'a (K, V) where &'a K: IntoPyObject<'py>, &'a V: IntoPyObject<'py>, { type K = &'a K; type V = &'a V; fn unpack(self) -> (Self::K, Self::V) { (&self.0, &self.1) } } #[cfg(test)] mod tests { use super::*; use crate::types::PyTuple; use std::collections::{BTreeMap, HashMap}; #[test] fn test_new() { Python::with_gil(|py| { let dict = [(7, 32)].into_py_dict(py).unwrap(); assert_eq!( 32, dict.get_item(7i32) .unwrap() .unwrap() .extract::<i32>() .unwrap() ); assert!(dict.get_item(8i32).unwrap().is_none()); let map: HashMap<i32, i32> = [(7, 32)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap()); let map: BTreeMap<i32, i32> = [(7, 32)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap()); }); } #[test] #[cfg(not(any(PyPy, GraalPy)))] fn test_from_sequence() { Python::with_gil(|py| { let items = PyList::new(py, vec![("a", 1), ("b", 2)]).unwrap(); let dict = PyDict::from_sequence(&items).unwrap(); assert_eq!( 1, dict.get_item("a") .unwrap() .unwrap() .extract::<i32>() .unwrap() ); assert_eq!( 2, dict.get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap() ); let map: HashMap<String, i32> = [("a".into(), 1), ("b".into(), 2)].into_iter().collect(); assert_eq!(map, dict.extract().unwrap()); let map: BTreeMap<String, i32> = [("a".into(), 1), ("b".into(), 2)].into_iter().collect(); assert_eq!(map, dict.extract().unwrap()); }); } #[test] #[cfg(not(any(PyPy, GraalPy)))] fn test_from_sequence_err() { Python::with_gil(|py| { let items = PyList::new(py, vec!["a", "b"]).unwrap(); assert!(PyDict::from_sequence(&items).is_err()); }); } #[test] fn test_copy() { Python::with_gil(|py| { let dict = [(7, 32)].into_py_dict(py).unwrap(); let ndict = dict.copy().unwrap(); assert_eq!( 32, ndict .get_item(7i32) .unwrap() .unwrap() .extract::<i32>() .unwrap() ); assert!(ndict.get_item(8i32).unwrap().is_none()); }); } #[test] fn test_len() { Python::with_gil(|py| { let mut v = HashMap::<i32, i32>::new(); let dict = (&v).into_pyobject(py).unwrap(); assert_eq!(0, dict.len()); v.insert(7, 32); let dict2 = v.into_pyobject(py).unwrap(); assert_eq!(1, dict2.len()); }); } #[test] fn test_contains() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = v.into_pyobject(py).unwrap(); assert!(dict.contains(7i32).unwrap()); assert!(!dict.contains(8i32).unwrap()); }); } #[test] fn test_get_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = v.into_pyobject(py).unwrap(); assert_eq!( 32, dict.get_item(7i32) .unwrap() .unwrap() .extract::<i32>() .unwrap() ); assert!(dict.get_item(8i32).unwrap().is_none()); }); } #[cfg(feature = "macros")] #[test] fn test_get_item_error_path() { use crate::exceptions::PyTypeError; #[crate::pyclass(crate = "crate")] struct HashErrors; #[crate::pymethods(crate = "crate")] impl HashErrors { #[new] fn new() -> Self { HashErrors {} } fn __hash__(&self) -> PyResult<isize> { Err(PyTypeError::new_err("Error from __hash__")) } } Python::with_gil(|py| { let class = py.get_type::<HashErrors>(); let instance = class.call0().unwrap(); let d = PyDict::new(py); match d.get_item(instance) { Ok(_) => { panic!("this get_item call should always error") } Err(err) => { assert!(err.is_instance_of::<PyTypeError>(py)); assert_eq!(err.value(py).to_string(), "Error from __hash__") } } }) } #[test] fn test_set_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = v.into_pyobject(py).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!( 42i32, dict.get_item(7i32) .unwrap() .unwrap() .extract::<i32>() .unwrap() ); assert_eq!( 123i32, dict.get_item(8i32) .unwrap() .unwrap() .extract::<i32>() .unwrap() ); }); } #[test] fn test_set_item_refcnt() { Python::with_gil(|py| { let cnt; let obj = py.eval(ffi::c_str!("object()"), None, None).unwrap(); { cnt = obj.get_refcnt(); let _dict = [(10, &obj)].into_py_dict(py); } { assert_eq!(cnt, obj.get_refcnt()); } }); } #[test] fn test_set_item_does_not_update_original_object() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = (&v).into_pyobject(py).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!(32i32, v[&7i32]); // not updated! assert_eq!(None, v.get(&8i32)); }); } #[test] fn test_del_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = v.into_pyobject(py).unwrap(); assert!(dict.del_item(7i32).is_ok()); assert_eq!(0, dict.len()); assert!(dict.get_item(7i32).unwrap().is_none()); }); } #[test] fn test_del_item_does_not_update_original_object() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = (&v).into_pyobject(py).unwrap(); assert!(dict.del_item(7i32).is_ok()); // change assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated! }); } #[test] fn test_items() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_pyobject(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; let mut value_sum = 0; for el in dict.items() { let tuple = el.downcast::<PyTuple>().unwrap(); key_sum += tuple.get_item(0).unwrap().extract::<i32>().unwrap(); value_sum += tuple.get_item(1).unwrap().extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_keys() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_pyobject(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; for el in dict.keys() { key_sum += el.extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); }); } #[test] fn test_values() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_pyobject(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0; for el in dict.values() { values_sum += el.extract::<i32>().unwrap(); } assert_eq!(32 + 42 + 123, values_sum); }); } #[test] fn test_iter() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_pyobject(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { key_sum += key.extract::<i32>().unwrap(); value_sum += value.extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_iter_bound() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_pyobject(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { key_sum += key.extract::<i32>().unwrap(); value_sum += value.extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_iter_value_mutated() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = (&v).into_pyobject(py).unwrap(); for (key, value) in &dict { dict.set_item(key, value.extract::<i32>().unwrap() + 7) .unwrap(); } }); } #[test] #[should_panic] fn test_iter_key_mutated() { Python::with_gil(|py| { let mut v = HashMap::new(); for i in 0..10 { v.insert(i * 2, i * 2); } let dict = v.into_pyobject(py).unwrap(); for (i, (key, value)) in dict.iter().enumerate() { let key = key.extract::<i32>().unwrap(); let value = value.extract::<i32>().unwrap(); dict.set_item(key + 1, value + 1).unwrap(); if i > 1000 { // avoid this test just running out of memory if it fails break; }; } }); } #[test] #[should_panic] fn test_iter_key_mutated_constant_len() { Python::with_gil(|py| { let mut v = HashMap::new(); for i in 0..10 { v.insert(i * 2, i * 2); } let dict = v.into_pyobject(py).unwrap(); for (i, (key, value)) in dict.iter().enumerate() { let key = key.extract::<i32>().unwrap(); let value = value.extract::<i32>().unwrap(); dict.del_item(key).unwrap(); dict.set_item(key + 1, value + 1).unwrap(); if i > 1000 { // avoid this test just running out of memory if it fails break; }; } }); } #[test] fn test_iter_size_hint() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = (&v).into_pyobject(py).unwrap(); let mut iter = dict.iter(); assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); iter.next(); assert_eq!(iter.size_hint(), (v.len() - 1, Some(v.len() - 1))); // Exhaust iterator. for _ in &mut iter {} assert_eq!(iter.size_hint(), (0, Some(0))); assert!(iter.next().is_none()); assert_eq!(iter.size_hint(), (0, Some(0))); }); } #[test] fn test_into_iter() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_pyobject(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { key_sum += key.extract::<i32>().unwrap(); value_sum += value.extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_hashmap_into_dict() { Python::with_gil(|py| { let mut map = 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_btreemap_into_dict() { Python::with_gil(|py| { let mut map = BTreeMap::<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_vec_into_dict() { Python::with_gil(|py| { let vec = vec![("a", 1), ("b", 2), ("c", 3)]; let py_map = vec.into_py_dict(py).unwrap(); assert_eq!(py_map.len(), 3); assert_eq!( py_map .get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 2 ); }); } #[test] fn test_slice_into_dict() { Python::with_gil(|py| { let arr = [("a", 1), ("b", 2), ("c", 3)]; let py_map = arr.into_py_dict(py).unwrap(); assert_eq!(py_map.len(), 3); assert_eq!( py_map .get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 2 ); }); } #[test] fn dict_as_mapping() { Python::with_gil(|py| { let mut map = HashMap::<i32, i32>::new(); map.insert(1, 1); let py_map = map.into_py_dict(py).unwrap(); assert_eq!(py_map.as_mapping().len().unwrap(), 1); assert_eq!( py_map .as_mapping() .get_item(1) .unwrap() .extract::<i32>() .unwrap(), 1 ); }); } #[test] fn dict_into_mapping() { Python::with_gil(|py| { let mut map = HashMap::<i32, i32>::new(); map.insert(1, 1); let py_map = map.into_py_dict(py).unwrap(); let py_mapping = py_map.into_mapping(); assert_eq!(py_mapping.len().unwrap(), 1); assert_eq!(py_mapping.get_item(1).unwrap().extract::<i32>().unwrap(), 1); }); } #[cfg(not(any(PyPy, GraalPy)))] fn abc_dict(py: Python<'_>) -> Bound<'_, PyDict> { let mut map = HashMap::<&'static str, i32>::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); map.into_py_dict(py).unwrap() } #[test] #[cfg(not(any(PyPy, GraalPy)))] fn dict_keys_view() { Python::with_gil(|py| { let dict = abc_dict(py); let keys = dict.call_method0("keys").unwrap(); assert!(keys.is_instance(&py.get_type::<PyDictKeys>()).unwrap()); }) } #[test] #[cfg(not(any(PyPy, GraalPy)))] fn dict_values_view() { Python::with_gil(|py| { let dict = abc_dict(py); let values = dict.call_method0("values").unwrap(); assert!(values.is_instance(&py.get_type::<PyDictValues>()).unwrap()); }) } #[test] #[cfg(not(any(PyPy, GraalPy)))] fn dict_items_view() { Python::with_gil(|py| { let dict = abc_dict(py); let items = dict.call_method0("items").unwrap(); assert!(items.is_instance(&py.get_type::<PyDictItems>()).unwrap()); }) } #[test] fn dict_update() { Python::with_gil(|py| { let dict = [("a", 1), ("b", 2), ("c", 3)].into_py_dict(py).unwrap(); let other = [("b", 4), ("c", 5), ("d", 6)].into_py_dict(py).unwrap(); dict.update(other.as_mapping()).unwrap(); assert_eq!(dict.len(), 4); assert_eq!( dict.get_item("a") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 1 ); assert_eq!( dict.get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 4 ); assert_eq!( dict.get_item("c") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 5 ); assert_eq!( dict.get_item("d") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 6 ); assert_eq!(other.len(), 3); assert_eq!( other .get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 4 ); assert_eq!( other .get_item("c") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 5 ); assert_eq!( other .get_item("d") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 6 ); }) } #[test] fn dict_update_if_missing() { Python::with_gil(|py| { let dict = [("a", 1), ("b", 2), ("c", 3)].into_py_dict(py).unwrap(); let other = [("b", 4), ("c", 5), ("d", 6)].into_py_dict(py).unwrap(); dict.update_if_missing(other.as_mapping()).unwrap(); assert_eq!(dict.len(), 4); assert_eq!( dict.get_item("a") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 1 ); assert_eq!( dict.get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 2 ); assert_eq!( dict.get_item("c") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 3 ); assert_eq!( dict.get_item("d") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 6 ); assert_eq!(other.len(), 3); assert_eq!( other .get_item("b") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 4 ); assert_eq!( other .get_item("c") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 5 ); assert_eq!( other .get_item("d") .unwrap() .unwrap() .extract::<i32>() .unwrap(), 6 ); }) } #[test] fn test_iter_all() { Python::with_gil(|py| { let dict = [(1, true), (2, true), (3, true)].into_py_dict(py).unwrap(); assert!(dict.iter().all(|(_, v)| v.extract::<bool>().unwrap())); let dict = [(1, true), (2, false), (3, true)].into_py_dict(py).unwrap(); assert!(!dict.iter().all(|(_, v)| v.extract::<bool>().unwrap())); }); } #[test] fn test_iter_any() { Python::with_gil(|py| { let dict = [(1, true), (2, false), (3, false)] .into_py_dict(py) .unwrap(); assert!(dict.iter().any(|(_, v)| v.extract::<bool>().unwrap())); let dict = [(1, false), (2, false), (3, false)] .into_py_dict(py) .unwrap(); assert!(!dict.iter().any(|(_, v)| v.extract::<bool>().unwrap())); }); } #[test] #[allow(clippy::search_is_some)] fn test_iter_find() { Python::with_gil(|py| { let dict = [(1, false), (2, true), (3, false)] .into_py_dict(py) .unwrap(); assert_eq!( Some((2, true)), dict.iter() .find(|(_, v)| v.extract::<bool>().unwrap()) .map(|(k, v)| (k.extract().unwrap(), v.extract().unwrap())) ); let dict = [(1, false), (2, false), (3, false)] .into_py_dict(py) .unwrap(); assert!(dict .iter() .find(|(_, v)| v.extract::<bool>().unwrap()) .is_none()); }); } #[test] #[allow(clippy::search_is_some)] fn test_iter_position() { Python::with_gil(|py| { let dict = [(1, false), (2, false), (3, true)] .into_py_dict(py) .unwrap(); assert_eq!( Some(2), dict.iter().position(|(_, v)| v.extract::<bool>().unwrap()) ); let dict = [(1, false), (2, false), (3, false)] .into_py_dict(py) .unwrap(); assert!(dict .iter() .position(|(_, v)| v.extract::<bool>().unwrap()) .is_none()); }); } #[test] fn test_iter_fold() { Python::with_gil(|py| { let dict = [(1, 1), (2, 2), (3, 3)].into_py_dict(py).unwrap(); let sum = dict .iter() .fold(0, |acc, (_, v)| acc + v.extract::<i32>().unwrap()); assert_eq!(sum, 6); }); } #[test] fn test_iter_try_fold() { Python::with_gil(|py| { let dict = [(1, 1), (2, 2), (3, 3)].into_py_dict(py).unwrap(); let sum = dict .iter() .try_fold(0, |acc, (_, v)| PyResult::Ok(acc + v.extract::<i32>()?)) .unwrap(); assert_eq!(sum, 6); let dict = [(1, "foo"), (2, "bar")].into_py_dict(py).unwrap(); assert!(dict .iter() .try_fold(0, |acc, (_, v)| PyResult::Ok(acc + v.extract::<i32>()?)) .is_err()); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/mappingproxy.rs
// Copyright (c) 2017-present PyO3 Project and Contributors use super::PyMapping; use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Bound; use crate::types::any::PyAnyMethods; use crate::types::{PyAny, PyIterator, PyList}; use crate::{ffi, Python}; use std::os::raw::c_int; /// Represents a Python `mappingproxy`. #[repr(transparent)] pub struct PyMappingProxy(PyAny); #[inline] unsafe fn dict_proxy_check(op: *mut ffi::PyObject) -> c_int { ffi::Py_IS_TYPE(op, std::ptr::addr_of_mut!(ffi::PyDictProxy_Type)) } pyobject_native_type_core!( PyMappingProxy, pyobject_native_static_type_object!(ffi::PyDictProxy_Type), #checkfunction=dict_proxy_check ); impl PyMappingProxy { /// Creates a mappingproxy from an object. pub fn new<'py>( py: Python<'py>, elements: &Bound<'py, PyMapping>, ) -> Bound<'py, PyMappingProxy> { unsafe { ffi::PyDictProxy_New(elements.as_ptr()) .assume_owned(py) .downcast_into_unchecked() } } } /// Implementation of functionality for [`PyMappingProxy`]. /// /// These methods are defined for the `Bound<'py, PyMappingProxy>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyMappingProxy")] pub trait PyMappingProxyMethods<'py, 'a>: crate::sealed::Sealed { /// Checks if the mappingproxy is empty, i.e. `len(self) == 0`. fn is_empty(&self) -> PyResult<bool>; /// Returns a list containing all keys in the mapping. fn keys(&self) -> PyResult<Bound<'py, PyList>>; /// Returns a list containing all values in the mapping. fn values(&self) -> PyResult<Bound<'py, PyList>>; /// Returns a list of tuples of all (key, value) pairs in the mapping. fn items(&self) -> PyResult<Bound<'py, PyList>>; /// Returns `self` cast as a `PyMapping`. fn as_mapping(&self) -> &Bound<'py, PyMapping>; /// Takes an object and returns an iterator for it. Returns an error if the object is not /// iterable. fn try_iter(&'a self) -> PyResult<BoundMappingProxyIterator<'py, 'a>>; } impl<'py, 'a> PyMappingProxyMethods<'py, 'a> for Bound<'py, PyMappingProxy> { fn is_empty(&self) -> PyResult<bool> { Ok(self.len()? == 0) } #[inline] fn keys(&self) -> PyResult<Bound<'py, PyList>> { unsafe { Ok(ffi::PyMapping_Keys(self.as_ptr()) .assume_owned_or_err(self.py())? .downcast_into_unchecked()) } } #[inline] fn values(&self) -> PyResult<Bound<'py, PyList>> { unsafe { Ok(ffi::PyMapping_Values(self.as_ptr()) .assume_owned_or_err(self.py())? .downcast_into_unchecked()) } } #[inline] fn items(&self) -> PyResult<Bound<'py, PyList>> { unsafe { Ok(ffi::PyMapping_Items(self.as_ptr()) .assume_owned_or_err(self.py())? .downcast_into_unchecked()) } } fn as_mapping(&self) -> &Bound<'py, PyMapping> { unsafe { self.downcast_unchecked() } } fn try_iter(&'a self) -> PyResult<BoundMappingProxyIterator<'py, 'a>> { Ok(BoundMappingProxyIterator { iterator: PyIterator::from_object(self)?, mappingproxy: self, }) } } pub struct BoundMappingProxyIterator<'py, 'a> { iterator: Bound<'py, PyIterator>, mappingproxy: &'a Bound<'py, PyMappingProxy>, } impl<'py> Iterator for BoundMappingProxyIterator<'py, '_> { type Item = PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)>; #[inline] fn next(&mut self) -> Option<Self::Item> { self.iterator.next().map(|key| match key { Ok(key) => match self.mappingproxy.get_item(&key) { Ok(value) => Ok((key, value)), Err(e) => Err(e), }, Err(e) => Err(e), }) } } #[cfg(test)] mod tests { use super::*; use crate::types::dict::*; use crate::Python; use crate::{ exceptions::PyKeyError, types::{PyInt, PyTuple}, }; use std::collections::{BTreeMap, HashMap}; #[test] fn test_new() { Python::with_gil(|py| { let pydict = [(7, 32)].into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, pydict.as_mapping()); mappingproxy.get_item(7i32).unwrap(); assert_eq!( 32, mappingproxy .get_item(7i32) .unwrap() .extract::<i32>() .unwrap() ); assert!(mappingproxy .get_item(8i32) .unwrap_err() .is_instance_of::<PyKeyError>(py)); }); } #[test] fn test_len() { Python::with_gil(|py| { let mut v = HashMap::new(); let dict = v.clone().into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(mappingproxy.len().unwrap(), 0); v.insert(7, 32); let dict2 = v.clone().into_py_dict(py).unwrap(); let mp2 = PyMappingProxy::new(py, dict2.as_mapping()); assert_eq!(mp2.len().unwrap(), 1); }); } #[test] fn test_contains() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = v.clone().into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); assert!(mappingproxy.contains(7i32).unwrap()); assert!(!mappingproxy.contains(8i32).unwrap()); }); } #[test] fn test_get_item() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); let dict = v.clone().into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!( 32, mappingproxy .get_item(7i32) .unwrap() .extract::<i32>() .unwrap() ); assert!(mappingproxy .get_item(8i32) .unwrap_err() .is_instance_of::<PyKeyError>(py)); }); } #[test] fn test_set_item_refcnt() { Python::with_gil(|py| { let cnt; { let none = py.None(); cnt = none.get_refcnt(py); let dict = [(10, none)].into_py_dict(py).unwrap(); let _mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); } { assert_eq!(cnt, py.None().get_refcnt(py)); } }); } #[test] fn test_isempty() { Python::with_gil(|py| { let map: HashMap<usize, usize> = HashMap::new(); let dict = map.into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); assert!(mappingproxy.is_empty().unwrap()); }); } #[test] fn test_keys() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; for el in mappingproxy.keys().unwrap().try_iter().unwrap() { key_sum += el.unwrap().extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); }); } #[test] fn test_values() { Python::with_gil(|py| { let mut v: HashMap<i32, i32> = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0; for el in mappingproxy.values().unwrap().try_iter().unwrap() { values_sum += el.unwrap().extract::<i32>().unwrap(); } assert_eq!(32 + 42 + 123, values_sum); }); } #[test] fn test_items() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; let mut value_sum = 0; for res in mappingproxy.items().unwrap().try_iter().unwrap() { let el = res.unwrap(); let tuple = el.downcast::<PyTuple>().unwrap(); key_sum += tuple.get_item(0).unwrap().extract::<i32>().unwrap(); value_sum += tuple.get_item(1).unwrap().extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_iter() { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); let mut key_sum = 0; let mut value_sum = 0; for res in mappingproxy.try_iter().unwrap() { let (key, value) = res.unwrap(); key_sum += key.extract::<i32>().unwrap(); value_sum += value.extract::<i32>().unwrap(); } assert_eq!(7 + 8 + 9, key_sum); assert_eq!(32 + 42 + 123, value_sum); }); } #[test] fn test_hashmap_into_python() { Python::with_gil(|py| { let mut map = HashMap::<i32, i32>::new(); map.insert(1, 1); let dict = map.clone().into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.len().unwrap(), 1); assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1); }); } #[test] fn test_hashmap_into_mappingproxy() { Python::with_gil(|py| { let mut map = HashMap::<i32, i32>::new(); map.insert(1, 1); let dict = map.clone().into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.len().unwrap(), 1); assert_eq!(py_map.get_item(1).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 dict = map.clone().into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.len().unwrap(), 1); assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1); }); } #[test] fn test_btreemap_into_mappingproxy() { Python::with_gil(|py| { let mut map = BTreeMap::<i32, i32>::new(); map.insert(1, 1); let dict = map.clone().into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.len().unwrap(), 1); assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1); }); } #[test] fn test_vec_into_mappingproxy() { Python::with_gil(|py| { let vec = vec![("a", 1), ("b", 2), ("c", 3)]; let dict = vec.clone().into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.len().unwrap(), 3); assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2); }); } #[test] fn test_slice_into_mappingproxy() { Python::with_gil(|py| { let arr = [("a", 1), ("b", 2), ("c", 3)]; let dict = arr.into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.len().unwrap(), 3); assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2); }); } #[test] fn mappingproxy_as_mapping() { Python::with_gil(|py| { let mut map = HashMap::<i32, i32>::new(); map.insert(1, 1); let dict = map.clone().into_py_dict(py).unwrap(); let py_map = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!(py_map.as_mapping().len().unwrap(), 1); assert_eq!( py_map .as_mapping() .get_item(1) .unwrap() .extract::<i32>() .unwrap(), 1 ); }); } #[cfg(not(PyPy))] fn abc_mappingproxy(py: Python<'_>) -> Bound<'_, PyMappingProxy> { let mut map = HashMap::<&'static str, i32>::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); let dict = map.clone().into_py_dict(py).unwrap(); PyMappingProxy::new(py, dict.as_mapping()) } #[test] #[cfg(not(PyPy))] fn mappingproxy_keys_view() { Python::with_gil(|py| { let mappingproxy = abc_mappingproxy(py); let keys = mappingproxy.call_method0("keys").unwrap(); assert!(keys.is_instance(&py.get_type::<PyDictKeys>()).unwrap()); }) } #[test] #[cfg(not(PyPy))] fn mappingproxy_values_view() { Python::with_gil(|py| { let mappingproxy = abc_mappingproxy(py); let values = mappingproxy.call_method0("values").unwrap(); assert!(values.is_instance(&py.get_type::<PyDictValues>()).unwrap()); }) } #[test] #[cfg(not(PyPy))] fn mappingproxy_items_view() { Python::with_gil(|py| { let mappingproxy = abc_mappingproxy(py); let items = mappingproxy.call_method0("items").unwrap(); assert!(items.is_instance(&py.get_type::<PyDictItems>()).unwrap()); }) } #[test] fn get_value_from_mappingproxy_of_strings() { Python::with_gil(|py: Python<'_>| { let mut map = HashMap::new(); map.insert("first key".to_string(), "first value".to_string()); map.insert("second key".to_string(), "second value".to_string()); map.insert("third key".to_string(), "third value".to_string()); let dict = map.clone().into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!( map.into_iter().collect::<Vec<(String, String)>>(), mappingproxy .try_iter() .unwrap() .map(|object| { let tuple = object.unwrap(); ( tuple.0.extract::<String>().unwrap(), tuple.1.extract::<String>().unwrap(), ) }) .collect::<Vec<(String, String)>>() ); }) } #[test] fn get_value_from_mappingproxy_of_integers() { Python::with_gil(|py: Python<'_>| { const LEN: usize = 10_000; let items: Vec<(usize, usize)> = (1..LEN).map(|i| (i, i - 1)).collect(); let dict = items.clone().into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); assert_eq!( items, mappingproxy .clone() .try_iter() .unwrap() .map(|object| { let tuple = object.unwrap(); ( tuple .0 .downcast::<PyInt>() .unwrap() .extract::<usize>() .unwrap(), tuple .1 .downcast::<PyInt>() .unwrap() .extract::<usize>() .unwrap(), ) }) .collect::<Vec<(usize, usize)>>() ); for index in 1..LEN { assert_eq!( mappingproxy .clone() .get_item(index) .unwrap() .extract::<usize>() .unwrap(), index - 1 ); } }) } #[test] fn iter_mappingproxy_nosegv() { Python::with_gil(|py| { const LEN: usize = 10_000_000; let items = (0..LEN as u64).map(|i| (i, i * 2)); let dict = items.clone().into_py_dict(py).unwrap(); let mappingproxy = PyMappingProxy::new(py, dict.as_mapping()); let mut sum = 0; for result in mappingproxy.try_iter().unwrap() { let (k, _v) = result.unwrap(); let i: u64 = k.extract().unwrap(); sum += i; } assert_eq!(sum, 49_999_995_000_000); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/mod.rs
//! Various types defined by the Python interpreter such as `int`, `str` and `tuple`. pub use self::any::{PyAny, PyAnyMethods}; pub use self::boolobject::{PyBool, PyBoolMethods}; pub use self::bytearray::{PyByteArray, PyByteArrayMethods}; pub use self::bytes::{PyBytes, PyBytesMethods}; pub use self::capsule::{PyCapsule, PyCapsuleMethods}; #[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))] pub use self::code::PyCode; pub use self::complex::{PyComplex, PyComplexMethods}; #[cfg(not(Py_LIMITED_API))] #[allow(deprecated)] pub use self::datetime::{ timezone_utc, timezone_utc_bound, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyTime, PyTimeAccess, PyTzInfo, PyTzInfoAccess, }; pub use self::dict::{IntoPyDict, PyDict, PyDictMethods}; #[cfg(not(any(PyPy, GraalPy)))] pub use self::dict::{PyDictItems, PyDictKeys, PyDictValues}; pub use self::ellipsis::PyEllipsis; pub use self::float::{PyFloat, PyFloatMethods}; #[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))] pub use self::frame::PyFrame; pub use self::frozenset::{PyFrozenSet, PyFrozenSetBuilder, PyFrozenSetMethods}; pub use self::function::PyCFunction; #[cfg(all(not(Py_LIMITED_API), not(all(PyPy, not(Py_3_8))), not(GraalPy)))] pub use self::function::PyFunction; pub use self::iterator::PyIterator; pub use self::list::{PyList, PyListMethods}; pub use self::mapping::{PyMapping, PyMappingMethods}; pub use self::mappingproxy::PyMappingProxy; pub use self::memoryview::PyMemoryView; pub use self::module::{PyModule, PyModuleMethods}; pub use self::none::PyNone; pub use self::notimplemented::PyNotImplemented; #[allow(deprecated)] pub use self::num::{PyInt, PyLong}; #[cfg(not(any(PyPy, GraalPy)))] pub use self::pysuper::PySuper; pub use self::sequence::{PySequence, PySequenceMethods}; pub use self::set::{PySet, PySetMethods}; pub use self::slice::{PySlice, PySliceIndices, PySliceMethods}; #[cfg(not(Py_LIMITED_API))] pub use self::string::PyStringData; #[allow(deprecated)] pub use self::string::{PyString, PyStringMethods, PyUnicode}; pub use self::traceback::{PyTraceback, PyTracebackMethods}; pub use self::tuple::{PyTuple, PyTupleMethods}; pub use self::typeobject::{PyType, PyTypeMethods}; pub use self::weakref::{PyWeakref, PyWeakrefMethods, PyWeakrefProxy, PyWeakrefReference}; /// Iteration over Python collections. /// /// When working with a Python collection, one approach is to convert it to a Rust collection such /// as `Vec` or `HashMap`. However this is a relatively expensive operation. If you just want to /// visit all their items, consider iterating over the collections directly: /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// use pyo3::ffi::c_str; /// /// # pub fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let dict = py.eval(c_str!("{'a':'b', 'c':'d'}"), None, None)?.downcast_into::<PyDict>()?; /// /// for (key, value) in &dict { /// println!("key: {}, value: {}", key, value); /// } /// /// Ok(()) /// }) /// # } /// ``` /// /// If PyO3 detects that the collection is mutated during iteration, it will panic. /// /// These iterators use Python's C-API directly. However in certain cases, like when compiling for /// the Limited API and PyPy, the underlying structures are opaque and that may not be possible. /// In these cases the iterators are implemented by forwarding to [`PyIterator`]. pub mod iter { pub use super::dict::BoundDictIterator; pub use super::frozenset::BoundFrozenSetIterator; pub use super::list::BoundListIterator; pub use super::set::BoundSetIterator; pub use super::tuple::{BorrowedTupleIterator, BoundTupleIterator}; } /// Python objects that have a base type. /// /// This marks types that can be upcast into a [`PyAny`] and used in its place. /// This essentially includes every Python object except [`PyAny`] itself. /// /// This is used to provide the [`Deref<Target = Bound<'_, PyAny>>`](std::ops::Deref) /// implementations for [`Bound<'_, T>`](crate::Bound). /// /// Users should not need to implement this trait directly. It's implementation /// is provided by the [`#[pyclass]`](macro@crate::pyclass) attribute. /// /// ## Note /// This is needed because the compiler currently tries to figure out all the /// types in a deref-chain before starting to look for applicable method calls. /// So we need to prevent [`Bound<'_, PyAny`](crate::Bound) dereferencing to /// itself in order to avoid running into the recursion limit. This trait is /// used to exclude this from our blanket implementation. See [this Rust /// issue][1] for more details. If the compiler limitation gets resolved, this /// trait will be removed. /// /// [1]: https://github.com/rust-lang/rust/issues/19509 pub trait DerefToPyAny { // Empty. } // Implementations core to all native types except for PyAny (because they don't // make sense on PyAny / have different implementations). #[doc(hidden)] #[macro_export] macro_rules! pyobject_native_type_named ( ($name:ty $(;$generics:ident)*) => { impl<$($generics,)*> ::std::convert::AsRef<$crate::PyAny> for $name { #[inline] fn as_ref(&self) -> &$crate::PyAny { &self.0 } } impl<$($generics,)*> ::std::ops::Deref for $name { type Target = $crate::PyAny; #[inline] fn deref(&self) -> &$crate::PyAny { &self.0 } } impl $crate::types::DerefToPyAny for $name {} }; ); #[doc(hidden)] #[macro_export] macro_rules! pyobject_native_static_type_object( ($typeobject:expr) => { |_py| { #[allow(unused_unsafe)] // https://github.com/rust-lang/rust/pull/125834 unsafe { ::std::ptr::addr_of_mut!($typeobject) } } }; ); #[doc(hidden)] #[macro_export] macro_rules! pyobject_native_type_info( ($name:ty, $typeobject:expr, $module:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => { unsafe impl<$($generics,)*> $crate::type_object::PyTypeInfo for $name { const NAME: &'static str = stringify!($name); const MODULE: ::std::option::Option<&'static str> = $module; #[inline] #[allow(clippy::redundant_closure_call)] fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject { $typeobject(py) } $( #[inline] fn is_type_of_bound(obj: &$crate::Bound<'_, $crate::PyAny>) -> bool { #[allow(unused_unsafe)] unsafe { $checkfunction(obj.as_ptr()) > 0 } } )? } impl $name { #[doc(hidden)] pub const _PYO3_DEF: $crate::impl_::pymodule::AddTypeToModule<Self> = $crate::impl_::pymodule::AddTypeToModule::new(); } }; ); /// Declares all of the boilerplate for Python types. #[doc(hidden)] #[macro_export] macro_rules! pyobject_native_type_core { ($name:ty, $typeobject:expr, #module=$module:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => { $crate::pyobject_native_type_named!($name $(;$generics)*); $crate::pyobject_native_type_info!($name, $typeobject, $module $(, #checkfunction=$checkfunction)? $(;$generics)*); }; ($name:ty, $typeobject:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => { $crate::pyobject_native_type_core!($name, $typeobject, #module=::std::option::Option::Some("builtins") $(, #checkfunction=$checkfunction)? $(;$generics)*); }; } #[doc(hidden)] #[macro_export] macro_rules! pyobject_subclassable_native_type { ($name:ty, $layout:path $(;$generics:ident)*) => { #[cfg(not(Py_LIMITED_API))] impl<$($generics,)*> $crate::impl_::pyclass::PyClassBaseType for $name { type LayoutAsBase = $crate::impl_::pycell::PyClassObjectBase<$layout>; type BaseNativeType = $name; type Initializer = $crate::impl_::pyclass_init::PyNativeTypeInitializer<Self>; type PyClassMutability = $crate::pycell::impl_::ImmutableClass; } } } #[doc(hidden)] #[macro_export] macro_rules! pyobject_native_type_sized { ($name:ty, $layout:path $(;$generics:ident)*) => { unsafe impl $crate::type_object::PyLayout<$name> for $layout {} impl $crate::type_object::PySizedLayout<$name> for $layout {} }; } /// Declares all of the boilerplate for Python types which can be inherited from (because the exact /// Python layout is known). #[doc(hidden)] #[macro_export] macro_rules! pyobject_native_type { ($name:ty, $layout:path, $typeobject:expr $(, #module=$module:expr)? $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => { $crate::pyobject_native_type_core!($name, $typeobject $(, #module=$module)? $(, #checkfunction=$checkfunction)? $(;$generics)*); // To prevent inheriting native types with ABI3 #[cfg(not(Py_LIMITED_API))] $crate::pyobject_native_type_sized!($name, $layout $(;$generics)*); }; } pub(crate) mod any; pub(crate) mod boolobject; pub(crate) mod bytearray; pub(crate) mod bytes; pub(crate) mod capsule; #[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))] mod code; pub(crate) mod complex; #[cfg(not(Py_LIMITED_API))] pub(crate) mod datetime; pub(crate) mod dict; mod ellipsis; pub(crate) mod float; #[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))] mod frame; pub(crate) mod frozenset; mod function; pub(crate) mod iterator; pub(crate) mod list; pub(crate) mod mapping; pub(crate) mod mappingproxy; mod memoryview; pub(crate) mod module; mod none; mod notimplemented; mod num; #[cfg(not(any(PyPy, GraalPy)))] mod pysuper; pub(crate) mod sequence; pub(crate) mod set; pub(crate) mod slice; pub(crate) mod string; pub(crate) mod traceback; pub(crate) mod tuple; pub(crate) mod typeobject; pub(crate) mod weakref;
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/module.rs
use crate::conversion::IntoPyObject; use crate::err::{PyErr, PyResult}; use crate::ffi_ptr_ext::FfiPtrExt; use crate::impl_::callback::IntoPyCallbackOutput; use crate::py_result_ext::PyResultExt; use crate::pyclass::PyClass; use crate::types::{ any::PyAnyMethods, list::PyListMethods, PyAny, PyCFunction, PyDict, PyList, PyString, }; use crate::{exceptions, ffi, Borrowed, Bound, BoundObject, Py, PyObject, Python}; use std::ffi::{CStr, CString}; #[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))] use std::os::raw::c_int; use std::str; /// Represents a Python [`module`][1] object. /// /// Values of this type are accessed via PyO3's smart pointers, e.g. as /// [`Py<PyModule>`][crate::Py] or [`Bound<'py, PyModule>`][Bound]. /// /// For APIs available on `module` objects, see the [`PyModuleMethods`] trait which is implemented for /// [`Bound<'py, PyModule>`][Bound]. /// /// As with all other Python objects, modules are first class citizens. /// This means they can be passed to or returned from functions, /// created dynamically, assigned to variables and so forth. /// /// [1]: https://docs.python.org/3/tutorial/modules.html #[repr(transparent)] pub struct PyModule(PyAny); pyobject_native_type_core!(PyModule, pyobject_native_static_type_object!(ffi::PyModule_Type), #checkfunction=ffi::PyModule_Check); impl PyModule { /// Creates a new module object with the `__name__` attribute set to `name`. /// /// # Examples /// /// ``` rust /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { /// let module = PyModule::new(py, "my_module")?; /// /// assert_eq!(module.name()?, "my_module"); /// Ok(()) /// })?; /// # Ok(())} /// ``` pub fn new<'py>(py: Python<'py>, name: &str) -> PyResult<Bound<'py, PyModule>> { let name = PyString::new(py, name); unsafe { ffi::PyModule_NewObject(name.as_ptr()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyModule::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyModule::new`")] #[inline] pub fn new_bound<'py>(py: Python<'py>, name: &str) -> PyResult<Bound<'py, PyModule>> { Self::new(py, name) } /// Imports the Python module with the specified name. /// /// # Examples /// /// ```no_run /// # fn main() { /// use pyo3::prelude::*; /// /// Python::with_gil(|py| { /// let module = PyModule::import(py, "antigravity").expect("No flying for you."); /// }); /// # } /// ``` /// /// This is equivalent to the following Python expression: /// ```python /// import antigravity /// ``` /// /// If you want to import a class, you can store a reference to it with /// [`GILOnceCell::import`][crate::sync::GILOnceCell#method.import]. pub fn import<'py, N>(py: Python<'py>, name: N) -> PyResult<Bound<'py, PyModule>> where N: IntoPyObject<'py, Target = PyString>, { let name = name.into_pyobject(py).map_err(Into::into)?; unsafe { ffi::PyImport_Import(name.as_ptr()) .assume_owned_or_err(py) .downcast_into_unchecked() } } /// Deprecated name for [`PyModule::import`]. #[deprecated(since = "0.23.0", note = "renamed to `PyModule::import`")] #[allow(deprecated)] #[inline] pub fn import_bound<N>(py: Python<'_>, name: N) -> PyResult<Bound<'_, PyModule>> where N: crate::IntoPy<Py<PyString>>, { Self::import(py, name.into_py(py)) } /// Creates and loads a module named `module_name`, /// containing the Python code passed to `code` /// and pretending to live at `file_name`. /// /// <div class="information"> /// <div class="tooltip compile_fail" style="">&#x26a0; &#xfe0f;</div> /// </div><div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;"> // /// <strong>Warning</strong>: This will compile and execute code. <strong>Never</strong> pass untrusted code to this function! /// /// </pre></div> /// /// # Errors /// /// Returns `PyErr` if: /// - `code` is not syntactically correct Python. /// - Any Python exceptions are raised while initializing the module. /// - Any of the arguments cannot be converted to [`CString`]s. /// /// # Example: bundle in a file at compile time with [`include_str!`][std::include_str]: /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::ffi::c_str; /// /// # fn main() -> PyResult<()> { /// // This path is resolved relative to this file. /// let code = c_str!(include_str!("../../assets/script.py")); /// /// Python::with_gil(|py| -> PyResult<()> { /// PyModule::from_code(py, code, c_str!("example.py"), c_str!("example"))?; /// Ok(()) /// })?; /// # Ok(()) /// # } /// ``` /// /// # Example: Load a file at runtime with [`std::fs::read_to_string`]. /// /// ```rust /// use pyo3::prelude::*; /// use pyo3::ffi::c_str; /// use std::ffi::CString; /// /// # fn main() -> PyResult<()> { /// // This path is resolved by however the platform resolves paths, /// // which also makes this less portable. Consider using `include_str` /// // if you just want to bundle a script with your module. /// let code = std::fs::read_to_string("assets/script.py")?; /// /// Python::with_gil(|py| -> PyResult<()> { /// PyModule::from_code(py, CString::new(code)?.as_c_str(), c_str!("example.py"), c_str!("example"))?; /// Ok(()) /// })?; /// Ok(()) /// # } /// ``` pub fn from_code<'py>( py: Python<'py>, code: &CStr, file_name: &CStr, module_name: &CStr, ) -> PyResult<Bound<'py, PyModule>> { unsafe { let code = ffi::Py_CompileString(code.as_ptr(), file_name.as_ptr(), ffi::Py_file_input) .assume_owned_or_err(py)?; ffi::PyImport_ExecCodeModuleEx(module_name.as_ptr(), code.as_ptr(), file_name.as_ptr()) .assume_owned_or_err(py) .downcast_into() } } /// Deprecated name for [`PyModule::from_code`]. #[deprecated(since = "0.23.0", note = "renamed to `PyModule::from_code`")] #[inline] pub fn from_code_bound<'py>( py: Python<'py>, code: &str, file_name: &str, module_name: &str, ) -> PyResult<Bound<'py, PyModule>> { let data = CString::new(code)?; let filename = CString::new(file_name)?; let module = CString::new(module_name)?; Self::from_code(py, data.as_c_str(), filename.as_c_str(), module.as_c_str()) } } /// Implementation of functionality for [`PyModule`]. /// /// These methods are defined for the `Bound<'py, PyModule>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyModule")] pub trait PyModuleMethods<'py>: crate::sealed::Sealed { /// Returns the module's `__dict__` attribute, which contains the module's symbol table. fn dict(&self) -> Bound<'py, PyDict>; /// Returns the index (the `__all__` attribute) of the module, /// creating one if needed. /// /// `__all__` declares the items that will be imported with `from my_module import *`. fn index(&self) -> PyResult<Bound<'py, PyList>>; /// Returns the name (the `__name__` attribute) of the module. /// /// May fail if the module does not have a `__name__` attribute. fn name(&self) -> PyResult<Bound<'py, PyString>>; /// Returns the filename (the `__file__` attribute) of the module. /// /// May fail if the module does not have a `__file__` attribute. fn filename(&self) -> PyResult<Bound<'py, PyString>>; /// Adds an attribute to the module. /// /// For adding classes, functions or modules, prefer to use [`PyModuleMethods::add_class`], /// [`PyModuleMethods::add_function`] or [`PyModuleMethods::add_submodule`] instead, /// respectively. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pymodule] /// fn my_module(module: &Bound<'_, PyModule>) -> PyResult<()> { /// module.add("c", 299_792_458)?; /// Ok(()) /// } /// ``` /// /// Python code can then do the following: /// /// ```python /// from my_module import c /// /// print("c is", c) /// ``` /// /// This will result in the following output: /// /// ```text /// c is 299792458 /// ``` fn add<N, V>(&self, name: N, value: V) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>, V: IntoPyObject<'py>; /// Adds a new class to the module. /// /// Notice that this method does not take an argument. /// Instead, this method is *generic*, and requires us to use the /// "turbofish" syntax to specify the class we want to add. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pyclass] /// struct Foo { /* fields omitted */ } /// /// #[pymodule] /// fn my_module(module: &Bound<'_, PyModule>) -> PyResult<()> { /// module.add_class::<Foo>()?; /// Ok(()) /// } /// ``` /// /// Python code can see this class as such: /// ```python /// from my_module import Foo /// /// print("Foo is", Foo) /// ``` /// /// This will result in the following output: /// ```text /// Foo is <class 'builtins.Foo'> /// ``` /// /// Note that as we haven't defined a [constructor][1], Python code can't actually /// make an *instance* of `Foo` (or *get* one for that matter, as we haven't exported /// anything that can return instances of `Foo`). /// #[doc = concat!("[1]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/class.html#constructor")] fn add_class<T>(&self) -> PyResult<()> where T: PyClass; /// Adds a function or a (sub)module to a module, using the functions name as name. /// /// Prefer to use [`PyModuleMethods::add_function`] and/or [`PyModuleMethods::add_submodule`] /// instead. fn add_wrapped<T>(&self, wrapper: &impl Fn(Python<'py>) -> T) -> PyResult<()> where T: IntoPyCallbackOutput<'py, PyObject>; /// Adds a submodule to a module. /// /// This is especially useful for creating module hierarchies. /// /// Note that this doesn't define a *package*, so this won't allow Python code /// to directly import submodules by using /// <span style="white-space: pre">`from my_module import submodule`</span>. /// For more information, see [#759][1] and [#1517][2]. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pymodule] /// fn my_module(py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> { /// let submodule = PyModule::new(py, "submodule")?; /// submodule.add("super_useful_constant", "important")?; /// /// module.add_submodule(&submodule)?; /// Ok(()) /// } /// ``` /// /// Python code can then do the following: /// /// ```python /// import my_module /// /// print("super_useful_constant is", my_module.submodule.super_useful_constant) /// ``` /// /// This will result in the following output: /// /// ```text /// super_useful_constant is important /// ``` /// /// [1]: https://github.com/PyO3/pyo3/issues/759 /// [2]: https://github.com/PyO3/pyo3/issues/1517#issuecomment-808664021 fn add_submodule(&self, module: &Bound<'_, PyModule>) -> PyResult<()>; /// Add a function to a module. /// /// Note that this also requires the [`wrap_pyfunction!`][2] macro /// to wrap a function annotated with [`#[pyfunction]`][1]. /// /// ```rust /// use pyo3::prelude::*; /// /// #[pyfunction] /// fn say_hello() { /// println!("Hello world!") /// } /// #[pymodule] /// fn my_module(module: &Bound<'_, PyModule>) -> PyResult<()> { /// module.add_function(wrap_pyfunction!(say_hello, module)?) /// } /// ``` /// /// Python code can then do the following: /// /// ```python /// from my_module import say_hello /// /// say_hello() /// ``` /// /// This will result in the following output: /// /// ```text /// Hello world! /// ``` /// /// [1]: crate::prelude::pyfunction /// [2]: crate::wrap_pyfunction fn add_function(&self, fun: Bound<'_, PyCFunction>) -> PyResult<()>; /// Declare whether or not this module supports running with the GIL disabled /// /// If the module does not rely on the GIL for thread safety, you can pass /// `false` to this function to indicate the module does not rely on the GIL /// for thread-safety. /// /// This function sets the [`Py_MOD_GIL` /// slot](https://docs.python.org/3/c-api/module.html#c.Py_mod_gil) on the /// module object. The default is `Py_MOD_GIL_USED`, so passing `true` to /// this function is a no-op unless you have already set `Py_MOD_GIL` to /// `Py_MOD_GIL_NOT_USED` elsewhere. /// /// # Examples /// /// ```rust /// use pyo3::prelude::*; /// /// #[pymodule(gil_used = false)] /// fn my_module(py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> { /// let submodule = PyModule::new(py, "submodule")?; /// submodule.gil_used(false)?; /// module.add_submodule(&submodule)?; /// Ok(()) /// } /// ``` /// /// The resulting module will not print a `RuntimeWarning` and re-enable the /// GIL when Python imports it on the free-threaded build, since all module /// objects defined in the extension have `Py_MOD_GIL` set to /// `Py_MOD_GIL_NOT_USED`. /// /// This is a no-op on the GIL-enabled build. fn gil_used(&self, gil_used: bool) -> PyResult<()>; } impl<'py> PyModuleMethods<'py> for Bound<'py, PyModule> { fn dict(&self) -> Bound<'py, PyDict> { unsafe { // PyModule_GetDict returns borrowed ptr; must make owned for safety (see #890). ffi::PyModule_GetDict(self.as_ptr()) .assume_borrowed(self.py()) .to_owned() .downcast_into_unchecked() } } fn index(&self) -> PyResult<Bound<'py, PyList>> { let __all__ = __all__(self.py()); match self.getattr(__all__) { Ok(idx) => idx.downcast_into().map_err(PyErr::from), Err(err) => { if err.is_instance_of::<exceptions::PyAttributeError>(self.py()) { let l = PyList::empty(self.py()); self.setattr(__all__, &l).map_err(PyErr::from)?; Ok(l) } else { Err(err) } } } } fn name(&self) -> PyResult<Bound<'py, PyString>> { #[cfg(not(PyPy))] { unsafe { ffi::PyModule_GetNameObject(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } } #[cfg(PyPy)] { self.dict() .get_item("__name__") .map_err(|_| exceptions::PyAttributeError::new_err("__name__"))? .downcast_into() .map_err(PyErr::from) } } fn filename(&self) -> PyResult<Bound<'py, PyString>> { #[cfg(not(PyPy))] unsafe { ffi::PyModule_GetFilenameObject(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } #[cfg(PyPy)] { self.dict() .get_item("__file__") .map_err(|_| exceptions::PyAttributeError::new_err("__file__"))? .downcast_into() .map_err(PyErr::from) } } fn add<N, V>(&self, name: N, value: V) -> PyResult<()> where N: IntoPyObject<'py, Target = PyString>, V: IntoPyObject<'py>, { fn inner( module: &Bound<'_, PyModule>, name: Borrowed<'_, '_, PyString>, value: Borrowed<'_, '_, PyAny>, ) -> PyResult<()> { module .index()? .append(name) .expect("could not append __name__ to __all__"); module.setattr(name, value) } let py = self.py(); inner( self, name.into_pyobject(py).map_err(Into::into)?.as_borrowed(), value .into_pyobject(py) .map_err(Into::into)? .into_any() .as_borrowed(), ) } fn add_class<T>(&self) -> PyResult<()> where T: PyClass, { let py = self.py(); self.add(T::NAME, T::lazy_type_object().get_or_try_init(py)?) } fn add_wrapped<T>(&self, wrapper: &impl Fn(Python<'py>) -> T) -> PyResult<()> where T: IntoPyCallbackOutput<'py, PyObject>, { fn inner(module: &Bound<'_, PyModule>, object: Bound<'_, PyAny>) -> PyResult<()> { let name = object.getattr(__name__(module.py()))?; module.add(name.downcast_into::<PyString>()?, object) } let py = self.py(); inner(self, wrapper(py).convert(py)?.into_bound(py)) } fn add_submodule(&self, module: &Bound<'_, PyModule>) -> PyResult<()> { let name = module.name()?; self.add(name, module) } fn add_function(&self, fun: Bound<'_, PyCFunction>) -> PyResult<()> { let name = fun.getattr(__name__(self.py()))?; self.add(name.downcast_into::<PyString>()?, fun) } #[cfg_attr(any(Py_LIMITED_API, not(Py_GIL_DISABLED)), allow(unused_variables))] fn gil_used(&self, gil_used: bool) -> PyResult<()> { #[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))] { let gil_used = match gil_used { true => ffi::Py_MOD_GIL_USED, false => ffi::Py_MOD_GIL_NOT_USED, }; match unsafe { ffi::PyUnstable_Module_SetGIL(self.as_ptr(), gil_used) } { c_int::MIN..=-1 => Err(PyErr::fetch(self.py())), 0..=c_int::MAX => Ok(()), } } #[cfg(any(Py_LIMITED_API, not(Py_GIL_DISABLED)))] Ok(()) } } fn __all__(py: Python<'_>) -> &Bound<'_, PyString> { intern!(py, "__all__") } fn __name__(py: Python<'_>) -> &Bound<'_, PyString> { intern!(py, "__name__") } #[cfg(test)] mod tests { use crate::{ types::{module::PyModuleMethods, PyModule}, Python, }; #[test] fn module_import_and_name() { Python::with_gil(|py| { let builtins = PyModule::import(py, "builtins").unwrap(); assert_eq!(builtins.name().unwrap(), "builtins"); }) } #[test] fn module_filename() { use crate::types::string::PyStringMethods; Python::with_gil(|py| { let site = PyModule::import(py, "site").unwrap(); assert!(site .filename() .unwrap() .to_cow() .unwrap() .ends_with("site.py")); }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/weakref/anyref.rs
use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; use crate::type_object::{PyTypeCheck, PyTypeInfo}; use crate::types::{ any::{PyAny, PyAnyMethods}, PyNone, }; use crate::{ffi, Bound, Python}; /// Represents any Python `weakref` reference. /// /// In Python this is created by calling `weakref.ref` or `weakref.proxy`. #[repr(transparent)] pub struct PyWeakref(PyAny); pyobject_native_type_named!(PyWeakref); // TODO: We known the layout but this cannot be implemented, due to the lack of public typeobject pointers // #[cfg(not(Py_LIMITED_API))] // pyobject_native_type_sized!(PyWeakref, ffi::PyWeakReference); impl PyTypeCheck for PyWeakref { const NAME: &'static str = "weakref"; fn type_check(object: &Bound<'_, PyAny>) -> bool { unsafe { ffi::PyWeakref_Check(object.as_ptr()) > 0 } } } /// Implementation of functionality for [`PyWeakref`]. /// /// These methods are defined for the `Bound<'py, PyWeakref>` smart pointer, so to use method call /// syntax these methods are separated into a trait, because stable Rust does not yet support /// `arbitrary_self_types`. #[doc(alias = "PyWeakref")] pub trait PyWeakrefMethods<'py>: crate::sealed::Sealed { /// Upgrade the weakref to a direct Bound object reference. /// /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). /// In Python it would be equivalent to [`PyWeakref_GetRef`]. /// /// # Example #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// #[pymethods] /// impl Foo { /// fn get_data(&self) -> (&str, u32) { /// ("Dave", 10) /// } /// } /// /// fn parse_data(reference: Borrowed<'_, '_, PyWeakrefReference>) -> PyResult<String> { /// if let Some(data_src) = reference.upgrade_as::<Foo>()? { /// let data = data_src.borrow(); /// let (name, score) = data.get_data(); /// Ok(format!("Processing '{}': score = {}", name, score)) /// } else { /// Ok("The supplied data reference is nolonger relavent.".to_owned()) /// } /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let data = Bound::new(py, Foo{})?; /// let reference = PyWeakrefReference::new(&data)?; /// /// assert_eq!( /// parse_data(reference.as_borrowed())?, /// "Processing 'Dave': score = 10" /// ); /// /// drop(data); /// /// assert_eq!( /// parse_data(reference.as_borrowed())?, /// "The supplied data reference is nolonger relavent." /// ); /// /// Ok(()) /// }) /// # } /// ``` /// /// # Panics /// This function panics is the current object is invalid. /// If used propperly this is never the case. (NonNull and actually a weakref type) /// /// [`PyWeakref_GetRef`]: https://docs.python.org/3/c-api/weakref.html#c.PyWeakref_GetRef /// [`weakref.ReferenceType`]: https://docs.python.org/3/library/weakref.html#weakref.ReferenceType /// [`weakref.ref`]: https://docs.python.org/3/library/weakref.html#weakref.ref fn upgrade_as<T>(&self) -> PyResult<Option<Bound<'py, T>>> where T: PyTypeCheck, { self.upgrade() .map(Bound::downcast_into::<T>) .transpose() .map_err(Into::into) } /// Upgrade the weakref to a direct Bound object reference unchecked. The type of the recovered object is not checked before downcasting, this could lead to unexpected behavior. Use only when absolutely certain the type can be guaranteed. The `weakref` may still return `None`. /// /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). /// In Python it would be equivalent to [`PyWeakref_GetRef`]. /// /// # Safety /// Callers must ensure that the type is valid or risk type confusion. /// The `weakref` is still allowed to be `None`, if the referenced object has been cleaned up. /// /// # Example #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// #[pymethods] /// impl Foo { /// fn get_data(&self) -> (&str, u32) { /// ("Dave", 10) /// } /// } /// /// fn parse_data(reference: Borrowed<'_, '_, PyWeakrefReference>) -> String { /// if let Some(data_src) = unsafe { reference.upgrade_as_unchecked::<Foo>() } { /// let data = data_src.borrow(); /// let (name, score) = data.get_data(); /// format!("Processing '{}': score = {}", name, score) /// } else { /// "The supplied data reference is nolonger relavent.".to_owned() /// } /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let data = Bound::new(py, Foo{})?; /// let reference = PyWeakrefReference::new(&data)?; /// /// assert_eq!( /// parse_data(reference.as_borrowed()), /// "Processing 'Dave': score = 10" /// ); /// /// drop(data); /// /// assert_eq!( /// parse_data(reference.as_borrowed()), /// "The supplied data reference is nolonger relavent." /// ); /// /// Ok(()) /// }) /// # } /// ``` /// /// # Panics /// This function panics is the current object is invalid. /// If used propperly this is never the case. (NonNull and actually a weakref type) /// /// [`PyWeakref_GetRef`]: https://docs.python.org/3/c-api/weakref.html#c.PyWeakref_GetRef /// [`weakref.ReferenceType`]: https://docs.python.org/3/library/weakref.html#weakref.ReferenceType /// [`weakref.ref`]: https://docs.python.org/3/library/weakref.html#weakref.ref unsafe fn upgrade_as_unchecked<T>(&self) -> Option<Bound<'py, T>> { Some(self.upgrade()?.downcast_into_unchecked()) } /// Upgrade the weakref to a exact direct Bound object reference. /// /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). /// In Python it would be equivalent to [`PyWeakref_GetRef`]. /// /// # Example #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// #[pymethods] /// impl Foo { /// fn get_data(&self) -> (&str, u32) { /// ("Dave", 10) /// } /// } /// /// fn parse_data(reference: Borrowed<'_, '_, PyWeakrefReference>) -> PyResult<String> { /// if let Some(data_src) = reference.upgrade_as_exact::<Foo>()? { /// let data = data_src.borrow(); /// let (name, score) = data.get_data(); /// Ok(format!("Processing '{}': score = {}", name, score)) /// } else { /// Ok("The supplied data reference is nolonger relavent.".to_owned()) /// } /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let data = Bound::new(py, Foo{})?; /// let reference = PyWeakrefReference::new(&data)?; /// /// assert_eq!( /// parse_data(reference.as_borrowed())?, /// "Processing 'Dave': score = 10" /// ); /// /// drop(data); /// /// assert_eq!( /// parse_data(reference.as_borrowed())?, /// "The supplied data reference is nolonger relavent." /// ); /// /// Ok(()) /// }) /// # } /// ``` /// /// # Panics /// This function panics is the current object is invalid. /// If used propperly this is never the case. (NonNull and actually a weakref type) /// /// [`PyWeakref_GetRef`]: https://docs.python.org/3/c-api/weakref.html#c.PyWeakref_GetRef /// [`weakref.ReferenceType`]: https://docs.python.org/3/library/weakref.html#weakref.ReferenceType /// [`weakref.ref`]: https://docs.python.org/3/library/weakref.html#weakref.ref fn upgrade_as_exact<T>(&self) -> PyResult<Option<Bound<'py, T>>> where T: PyTypeInfo, { self.upgrade() .map(Bound::downcast_into_exact) .transpose() .map_err(Into::into) } /// Upgrade the weakref to a Bound [`PyAny`] reference to the target object if possible. /// /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). /// This function returns `Some(Bound<'py, PyAny>)` if the reference still exists, otherwise `None` will be returned. /// /// This function gets the optional target of this [`weakref.ReferenceType`] (result of calling [`weakref.ref`]). /// It produces similar results to using [`PyWeakref_GetRef`] in the C api. /// /// # Example #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// fn parse_data(reference: Borrowed<'_, '_, PyWeakrefReference>) -> PyResult<String> { /// if let Some(object) = reference.upgrade() { /// Ok(format!("The object '{}' refered by this reference still exists.", object.getattr("__class__")?.getattr("__qualname__")?)) /// } else { /// Ok("The object, which this reference refered to, no longer exists".to_owned()) /// } /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let data = Bound::new(py, Foo{})?; /// let reference = PyWeakrefReference::new(&data)?; /// /// assert_eq!( /// parse_data(reference.as_borrowed())?, /// "The object 'Foo' refered by this reference still exists." /// ); /// /// drop(data); /// /// assert_eq!( /// parse_data(reference.as_borrowed())?, /// "The object, which this reference refered to, no longer exists" /// ); /// /// Ok(()) /// }) /// # } /// ``` /// /// # Panics /// This function panics is the current object is invalid. /// If used properly this is never the case. (NonNull and actually a weakref type) /// /// [`PyWeakref_GetRef`]: https://docs.python.org/3/c-api/weakref.html#c.PyWeakref_GetRef /// [`weakref.ReferenceType`]: https://docs.python.org/3/library/weakref.html#weakref.ReferenceType /// [`weakref.ref`]: https://docs.python.org/3/library/weakref.html#weakref.ref fn upgrade(&self) -> Option<Bound<'py, PyAny>>; /// Retrieve to a Bound object pointed to by the weakref. /// /// This function returns `Bound<'py, PyAny>`, which is either the object if it still exists, otherwise it will refer to [`PyNone`](crate::types::PyNone). /// /// This function gets the optional target of this [`weakref.ReferenceType`] (result of calling [`weakref.ref`]). /// It produces similar results to using [`PyWeakref_GetRef`] in the C api. /// /// # Example #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// #![allow(deprecated)] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// fn get_class(reference: Borrowed<'_, '_, PyWeakrefReference>) -> PyResult<String> { /// reference /// .get_object() /// .getattr("__class__")? /// .repr() /// .map(|repr| repr.to_string()) /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let object = Bound::new(py, Foo{})?; /// let reference = PyWeakrefReference::new(&object)?; /// /// assert_eq!( /// get_class(reference.as_borrowed())?, /// "<class 'builtins.Foo'>" /// ); /// /// drop(object); /// /// assert_eq!(get_class(reference.as_borrowed())?, "<class 'NoneType'>"); /// /// Ok(()) /// }) /// # } /// ``` /// /// # Panics /// This function panics is the current object is invalid. /// If used propperly this is never the case. (NonNull and actually a weakref type) /// /// [`PyWeakref_GetRef`]: https://docs.python.org/3/c-api/weakref.html#c.PyWeakref_GetRef /// [`weakref.ReferenceType`]: https://docs.python.org/3/library/weakref.html#weakref.ReferenceType /// [`weakref.ref`]: https://docs.python.org/3/library/weakref.html#weakref.ref #[deprecated(since = "0.23.0", note = "Use `upgrade` instead")] fn get_object(&self) -> Bound<'py, PyAny> { self.upgrade().unwrap_or_else(|| { // Safety: upgrade() returns `Bound<'py, PyAny>` with a lifetime `'py` if it exists, we // can safely assume the same lifetime here. PyNone::get(unsafe { Python::assume_gil_acquired() }) .to_owned() .into_any() }) } } impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakref> { fn upgrade(&self) -> Option<Bound<'py, PyAny>> { let mut obj: *mut ffi::PyObject = std::ptr::null_mut(); match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } { std::os::raw::c_int::MIN..=-1 => panic!("The 'weakref' weak reference instance should be valid (non-null and actually a weakref reference)"), 0 => None, 1..=std::os::raw::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), } } } #[cfg(test)] mod tests { use crate::types::any::{PyAny, PyAnyMethods}; use crate::types::weakref::{PyWeakref, PyWeakrefMethods, PyWeakrefProxy, PyWeakrefReference}; use crate::{Bound, PyResult, Python}; fn new_reference<'py>(object: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyWeakref>> { let reference = PyWeakrefReference::new(object)?; reference.into_any().downcast_into().map_err(Into::into) } fn new_proxy<'py>(object: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyWeakref>> { let reference = PyWeakrefProxy::new(object)?; reference.into_any().downcast_into().map_err(Into::into) } mod python_class { use super::*; use crate::ffi; use crate::{py_result_ext::PyResultExt, types::PyType}; fn get_type(py: Python<'_>) -> PyResult<Bound<'_, PyType>> { py.run(ffi::c_str!("class A:\n pass\n"), None, None)?; py.eval(ffi::c_str!("A"), None, None) .downcast_into::<PyType>() } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, ) -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = create_reference(&object)?; { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } inner(new_reference)?; inner(new_proxy) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, ) -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = create_reference(&object)?; { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_none()); } Ok(()) }) } inner(new_reference)?; inner(new_proxy) } #[test] fn test_weakref_upgrade() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, call_retrievable: bool, ) -> PyResult<()> { let not_call_retrievable = !call_retrievable; Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = create_reference(&object)?; assert!(not_call_retrievable || reference.call0()?.is(&object)); assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(not_call_retrievable || reference.call0()?.is_none()); assert!(reference.upgrade().is_none()); Ok(()) }) } inner(new_reference, true)?; inner(new_proxy, false) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, call_retrievable: bool, ) -> PyResult<()> { let not_call_retrievable = !call_retrievable; Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = create_reference(&object)?; assert!(not_call_retrievable || reference.call0()?.is(&object)); assert!(reference.get_object().is(&object)); drop(object); assert!(not_call_retrievable || reference.call0()?.is(&reference.get_object())); assert!(not_call_retrievable || reference.call0()?.is_none()); assert!(reference.get_object().is_none()); Ok(()) }) } inner(new_reference, true)?; inner(new_proxy, false) } } // under 'abi3-py37' and 'abi3-py38' PyClass cannot be weakreferencable. #[cfg(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))))] mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} #[test] fn test_weakref_upgrade_as() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, ) -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = create_reference(object.bind(py))?; { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } inner(new_reference)?; inner(new_proxy) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, ) -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = create_reference(object.bind(py))?; { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_none()); } Ok(()) }) } inner(new_reference)?; inner(new_proxy) } #[test] fn test_weakref_upgrade() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, call_retrievable: bool, ) -> PyResult<()> { let not_call_retrievable = !call_retrievable; Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = create_reference(object.bind(py))?; assert!(not_call_retrievable || reference.call0()?.is(&object)); assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(not_call_retrievable || reference.call0()?.is_none()); assert!(reference.upgrade().is_none()); Ok(()) }) } inner(new_reference, true)?; inner(new_proxy, false) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { fn inner( create_reference: impl for<'py> FnOnce( &Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakref>>, call_retrievable: bool, ) -> PyResult<()> { let not_call_retrievable = !call_retrievable; Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = create_reference(object.bind(py))?; assert!(not_call_retrievable || reference.call0()?.is(&object)); assert!(reference.get_object().is(&object)); drop(object); assert!(not_call_retrievable || reference.call0()?.is(&reference.get_object())); assert!(not_call_retrievable || reference.call0()?.is_none()); assert!(reference.get_object().is_none()); Ok(()) }) } inner(new_reference, true)?; inner(new_proxy, false) } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/weakref/reference.rs
use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::types::any::PyAny; use crate::{ffi, Bound, BoundObject, IntoPyObject}; #[cfg(any(PyPy, GraalPy, Py_LIMITED_API))] use crate::type_object::PyTypeCheck; use super::PyWeakrefMethods; /// Represents a Python `weakref.ReferenceType`. /// /// In Python this is created by calling `weakref.ref`. #[repr(transparent)] pub struct PyWeakrefReference(PyAny); #[cfg(not(any(PyPy, GraalPy, Py_LIMITED_API)))] pyobject_subclassable_native_type!(PyWeakrefReference, crate::ffi::PyWeakReference); #[cfg(not(any(PyPy, GraalPy, Py_LIMITED_API)))] pyobject_native_type!( PyWeakrefReference, ffi::PyWeakReference, pyobject_native_static_type_object!(ffi::_PyWeakref_RefType), #module=Some("weakref"), #checkfunction=ffi::PyWeakref_CheckRefExact ); // When targetting alternative or multiple interpreters, it is better to not use the internal API. #[cfg(any(PyPy, GraalPy, Py_LIMITED_API))] pyobject_native_type_named!(PyWeakrefReference); #[cfg(any(PyPy, GraalPy, Py_LIMITED_API))] impl PyTypeCheck for PyWeakrefReference { const NAME: &'static str = "weakref.ReferenceType"; fn type_check(object: &Bound<'_, PyAny>) -> bool { unsafe { ffi::PyWeakref_CheckRef(object.as_ptr()) > 0 } } } impl PyWeakrefReference { /// Constructs a new Weak Reference (`weakref.ref`/`weakref.ReferenceType`) for the given object. /// /// Returns a `TypeError` if `object` is not weak referenceable (Most native types and PyClasses without `weakref` flag). /// /// # Examples #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let foo = Bound::new(py, Foo {})?; /// let weakref = PyWeakrefReference::new(&foo)?; /// assert!( /// // In normal situations where a direct `Bound<'py, Foo>` is required use `upgrade::<Foo>` /// weakref.upgrade() /// .map_or(false, |obj| obj.is(&foo)) /// ); /// /// let weakref2 = PyWeakrefReference::new(&foo)?; /// assert!(weakref.is(&weakref2)); /// /// drop(foo); /// /// assert!(weakref.upgrade().is_none()); /// Ok(()) /// }) /// # } /// ``` pub fn new<'py>(object: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyWeakrefReference>> { unsafe { Bound::from_owned_ptr_or_err( object.py(), ffi::PyWeakref_NewRef(object.as_ptr(), ffi::Py_None()), ) .downcast_into_unchecked() } } /// Deprecated name for [`PyWeakrefReference::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyWeakrefReference::new`")] #[inline] pub fn new_bound<'py>(object: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyWeakrefReference>> { Self::new(object) } /// Constructs a new Weak Reference (`weakref.ref`/`weakref.ReferenceType`) for the given object with a callback. /// /// Returns a `TypeError` if `object` is not weak referenceable (Most native types and PyClasses without `weakref` flag) or if the `callback` is not callable or None. /// /// # Examples #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefReference; /// use pyo3::ffi::c_str; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// #[pyfunction] /// fn callback(wref: Bound<'_, PyWeakrefReference>) -> PyResult<()> { /// let py = wref.py(); /// assert!(wref.upgrade_as::<Foo>()?.is_none()); /// py.run(c_str!("counter = 1"), None, None) /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// py.run(c_str!("counter = 0"), None, None)?; /// assert_eq!(py.eval(c_str!("counter"), None, None)?.extract::<u32>()?, 0); /// let foo = Bound::new(py, Foo{})?; /// /// // This is fine. /// let weakref = PyWeakrefReference::new_with(&foo, py.None())?; /// assert!(weakref.upgrade_as::<Foo>()?.is_some()); /// assert!( /// // In normal situations where a direct `Bound<'py, Foo>` is required use `upgrade::<Foo>` /// weakref.upgrade() /// .map_or(false, |obj| obj.is(&foo)) /// ); /// assert_eq!(py.eval(c_str!("counter"), None, None)?.extract::<u32>()?, 0); /// /// let weakref2 = PyWeakrefReference::new_with(&foo, wrap_pyfunction!(callback, py)?)?; /// assert!(!weakref.is(&weakref2)); // Not the same weakref /// assert!(weakref.eq(&weakref2)?); // But Equal, since they point to the same object /// /// drop(foo); /// /// assert!(weakref.upgrade_as::<Foo>()?.is_none()); /// assert_eq!(py.eval(c_str!("counter"), None, None)?.extract::<u32>()?, 1); /// Ok(()) /// }) /// # } /// ``` pub fn new_with<'py, C>( object: &Bound<'py, PyAny>, callback: C, ) -> PyResult<Bound<'py, PyWeakrefReference>> where C: IntoPyObject<'py>, { fn inner<'py>( object: &Bound<'py, PyAny>, callback: Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakrefReference>> { unsafe { Bound::from_owned_ptr_or_err( object.py(), ffi::PyWeakref_NewRef(object.as_ptr(), callback.as_ptr()), ) .downcast_into_unchecked() } } let py = object.py(); inner( object, callback .into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::into_bound) .map_err(Into::into)?, ) } /// Deprecated name for [`PyWeakrefReference::new_with`]. #[deprecated(since = "0.23.0", note = "renamed to `PyWeakrefReference::new_with`")] #[allow(deprecated)] #[inline] pub fn new_bound_with<'py, C>( object: &Bound<'py, PyAny>, callback: C, ) -> PyResult<Bound<'py, PyWeakrefReference>> where C: crate::ToPyObject, { Self::new_with(object, callback.to_object(object.py())) } } impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakrefReference> { fn upgrade(&self) -> Option<Bound<'py, PyAny>> { let mut obj: *mut ffi::PyObject = std::ptr::null_mut(); match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } { std::os::raw::c_int::MIN..=-1 => panic!("The 'weakref.ReferenceType' instance should be valid (non-null and actually a weakref reference)"), 0 => None, 1..=std::os::raw::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), } } } #[cfg(test)] mod tests { use crate::types::any::{PyAny, PyAnyMethods}; use crate::types::weakref::{PyWeakrefMethods, PyWeakrefReference}; use crate::{Bound, PyResult, Python}; #[cfg(all(not(Py_LIMITED_API), Py_3_10))] const CLASS_NAME: &str = "<class 'weakref.ReferenceType'>"; #[cfg(all(not(Py_LIMITED_API), not(Py_3_10)))] const CLASS_NAME: &str = "<class 'weakref'>"; fn check_repr( reference: &Bound<'_, PyWeakrefReference>, object: Option<(&Bound<'_, PyAny>, &str)>, ) -> PyResult<()> { let repr = reference.repr()?.to_string(); let (first_part, second_part) = repr.split_once("; ").unwrap(); { let (msg, addr) = first_part.split_once("0x").unwrap(); assert_eq!(msg, "<weakref at "); assert!(addr .to_lowercase() .contains(format!("{:x?}", reference.as_ptr()).split_at(2).1)); } match object { Some((object, class)) => { let (msg, addr) = second_part.split_once("0x").unwrap(); // Avoid testing on reprs directly since they the quoting and full path vs class name tends to be changedi undocumented. assert!(msg.starts_with("to '")); assert!(msg.contains(class)); assert!(msg.ends_with("' at ")); assert!(addr .to_lowercase() .contains(format!("{:x?}", object.as_ptr()).split_at(2).1)); } None => { assert_eq!(second_part, "dead>") } } Ok(()) } mod python_class { use super::*; use crate::ffi; use crate::{py_result_ext::PyResultExt, types::PyType}; fn get_type(py: Python<'_>) -> PyResult<Bound<'_, PyType>> { py.run(ffi::c_str!("class A:\n pass\n"), None, None)?; py.eval(ffi::c_str!("A"), None, None) .downcast_into::<PyType>() } #[test] fn test_weakref_reference_behavior() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefReference::new(&object)?; assert!(!reference.is(&object)); assert!(reference.upgrade().unwrap().is(&object)); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.get_type().to_string(), CLASS_NAME); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.getattr("__class__")?.to_string(), CLASS_NAME); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, Some((object.as_any(), "A")))?; assert!(reference .getattr("__callback__") .map_or(false, |result| result.is_none())); assert!(reference.call0()?.is(&object)); drop(object); assert!(reference.upgrade().is_none()); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.getattr("__class__")?.to_string(), CLASS_NAME); check_repr(&reference, None)?; assert!(reference .getattr("__callback__") .map_or(false, |result| result.is_none())); assert!(reference.call0()?.is_none()); Ok(()) }) } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefReference::new(&object)?; { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefReference::new(&object)?; { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefReference::new(&object)?; assert!(reference.call0()?.is(&object)); assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(reference.call0()?.is_none()); assert!(reference.upgrade().is_none()); Ok(()) }) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefReference::new(&object)?; assert!(reference.call0()?.is(&object)); assert!(reference.get_object().is(&object)); drop(object); assert!(reference.call0()?.is(&reference.get_object())); assert!(reference.call0()?.is_none()); assert!(reference.get_object().is_none()); Ok(()) }) } } // under 'abi3-py37' and 'abi3-py38' PyClass cannot be weakreferencable. #[cfg(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))))] mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} #[test] fn test_weakref_reference_behavior() -> PyResult<()> { Python::with_gil(|py| { let object: Bound<'_, WeakrefablePyClass> = Bound::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefReference::new(&object)?; assert!(!reference.is(&object)); assert!(reference.upgrade().unwrap().is(&object)); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.get_type().to_string(), CLASS_NAME); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.getattr("__class__")?.to_string(), CLASS_NAME); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, Some((object.as_any(), "WeakrefablePyClass")))?; assert!(reference .getattr("__callback__") .map_or(false, |result| result.is_none())); assert!(reference.call0()?.is(&object)); drop(object); assert!(reference.upgrade().is_none()); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.getattr("__class__")?.to_string(), CLASS_NAME); check_repr(&reference, None)?; assert!(reference .getattr("__callback__") .map_or(false, |result| result.is_none())); assert!(reference.call0()?.is_none()); Ok(()) }) } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefReference::new(object.bind(py))?; { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefReference::new(object.bind(py))?; { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefReference::new(object.bind(py))?; assert!(reference.call0()?.is(&object)); assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(reference.call0()?.is_none()); assert!(reference.upgrade().is_none()); Ok(()) }) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefReference::new(object.bind(py))?; assert!(reference.call0()?.is(&object)); assert!(reference.get_object().is(&object)); drop(object); assert!(reference.call0()?.is(&reference.get_object())); assert!(reference.call0()?.is_none()); assert!(reference.get_object().is_none()); Ok(()) }) } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/weakref/proxy.rs
use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; use crate::py_result_ext::PyResultExt; use crate::type_object::PyTypeCheck; use crate::types::any::PyAny; use crate::{ffi, Bound, BoundObject, IntoPyObject}; use super::PyWeakrefMethods; /// Represents any Python `weakref` Proxy type. /// /// In Python this is created by calling `weakref.proxy`. /// This is either a `weakref.ProxyType` or a `weakref.CallableProxyType` (`weakref.ProxyTypes`). #[repr(transparent)] pub struct PyWeakrefProxy(PyAny); pyobject_native_type_named!(PyWeakrefProxy); // TODO: We known the layout but this cannot be implemented, due to the lack of public typeobject pointers. And it is 2 distinct types // #[cfg(not(Py_LIMITED_API))] // pyobject_native_type_sized!(PyWeakrefProxy, ffi::PyWeakReference); impl PyTypeCheck for PyWeakrefProxy { const NAME: &'static str = "weakref.ProxyTypes"; fn type_check(object: &Bound<'_, PyAny>) -> bool { unsafe { ffi::PyWeakref_CheckProxy(object.as_ptr()) > 0 } } } /// TODO: UPDATE DOCS impl PyWeakrefProxy { /// Constructs a new Weak Reference (`weakref.proxy`/`weakref.ProxyType`/`weakref.CallableProxyType`) for the given object. /// /// Returns a `TypeError` if `object` is not weak referenceable (Most native types and PyClasses without `weakref` flag). /// /// # Examples #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefProxy; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let foo = Bound::new(py, Foo {})?; /// let weakref = PyWeakrefProxy::new(&foo)?; /// assert!( /// // In normal situations where a direct `Bound<'py, Foo>` is required use `upgrade::<Foo>` /// weakref.upgrade() /// .map_or(false, |obj| obj.is(&foo)) /// ); /// /// let weakref2 = PyWeakrefProxy::new(&foo)?; /// assert!(weakref.is(&weakref2)); /// /// drop(foo); /// /// assert!(weakref.upgrade().is_none()); /// Ok(()) /// }) /// # } /// ``` #[inline] pub fn new<'py>(object: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyWeakrefProxy>> { unsafe { Bound::from_owned_ptr_or_err( object.py(), ffi::PyWeakref_NewProxy(object.as_ptr(), ffi::Py_None()), ) .downcast_into_unchecked() } } /// Deprecated name for [`PyWeakrefProxy::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyWeakrefProxy::new`")] #[inline] pub fn new_bound<'py>(object: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyWeakrefProxy>> { Self::new(object) } /// Constructs a new Weak Reference (`weakref.proxy`/`weakref.ProxyType`/`weakref.CallableProxyType`) for the given object with a callback. /// /// Returns a `TypeError` if `object` is not weak referenceable (Most native types and PyClasses without `weakref` flag) or if the `callback` is not callable or None. /// /// # Examples #[cfg_attr( not(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9))))), doc = "```rust,ignore" )] #[cfg_attr( all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))), doc = "```rust" )] /// use pyo3::prelude::*; /// use pyo3::types::PyWeakrefProxy; /// use pyo3::ffi::c_str; /// /// #[pyclass(weakref)] /// struct Foo { /* fields omitted */ } /// /// #[pyfunction] /// fn callback(wref: Bound<'_, PyWeakrefProxy>) -> PyResult<()> { /// let py = wref.py(); /// assert!(wref.upgrade_as::<Foo>()?.is_none()); /// py.run(c_str!("counter = 1"), None, None) /// } /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// py.run(c_str!("counter = 0"), None, None)?; /// assert_eq!(py.eval(c_str!("counter"), None, None)?.extract::<u32>()?, 0); /// let foo = Bound::new(py, Foo{})?; /// /// // This is fine. /// let weakref = PyWeakrefProxy::new_with(&foo, py.None())?; /// assert!(weakref.upgrade_as::<Foo>()?.is_some()); /// assert!( /// // In normal situations where a direct `Bound<'py, Foo>` is required use `upgrade::<Foo>` /// weakref.upgrade() /// .map_or(false, |obj| obj.is(&foo)) /// ); /// assert_eq!(py.eval(c_str!("counter"), None, None)?.extract::<u32>()?, 0); /// /// let weakref2 = PyWeakrefProxy::new_with(&foo, wrap_pyfunction!(callback, py)?)?; /// assert!(!weakref.is(&weakref2)); // Not the same weakref /// assert!(weakref.eq(&weakref2)?); // But Equal, since they point to the same object /// /// drop(foo); /// /// assert!(weakref.upgrade_as::<Foo>()?.is_none()); /// assert_eq!(py.eval(c_str!("counter"), None, None)?.extract::<u32>()?, 1); /// Ok(()) /// }) /// # } /// ``` #[inline] pub fn new_with<'py, C>( object: &Bound<'py, PyAny>, callback: C, ) -> PyResult<Bound<'py, PyWeakrefProxy>> where C: IntoPyObject<'py>, { fn inner<'py>( object: &Bound<'py, PyAny>, callback: Bound<'py, PyAny>, ) -> PyResult<Bound<'py, PyWeakrefProxy>> { unsafe { Bound::from_owned_ptr_or_err( object.py(), ffi::PyWeakref_NewProxy(object.as_ptr(), callback.as_ptr()), ) .downcast_into_unchecked() } } let py = object.py(); inner( object, callback .into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::into_bound) .map_err(Into::into)?, ) } /// Deprecated name for [`PyWeakrefProxy::new_with`]. #[deprecated(since = "0.23.0", note = "renamed to `PyWeakrefProxy::new_with`")] #[allow(deprecated)] #[inline] pub fn new_bound_with<'py, C>( object: &Bound<'py, PyAny>, callback: C, ) -> PyResult<Bound<'py, PyWeakrefProxy>> where C: crate::ToPyObject, { Self::new_with(object, callback.to_object(object.py())) } } impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakrefProxy> { fn upgrade(&self) -> Option<Bound<'py, PyAny>> { let mut obj: *mut ffi::PyObject = std::ptr::null_mut(); match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } { std::os::raw::c_int::MIN..=-1 => panic!("The 'weakref.ProxyType' (or `weakref.CallableProxyType`) instance should be valid (non-null and actually a weakref reference)"), 0 => None, 1..=std::os::raw::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), } } } #[cfg(test)] mod tests { use crate::exceptions::{PyAttributeError, PyReferenceError, PyTypeError}; use crate::types::any::{PyAny, PyAnyMethods}; use crate::types::weakref::{PyWeakrefMethods, PyWeakrefProxy}; use crate::{Bound, PyResult, Python}; #[cfg(all(Py_3_13, not(Py_LIMITED_API)))] const DEADREF_FIX: Option<&str> = None; #[cfg(all(not(Py_3_13), not(Py_LIMITED_API)))] const DEADREF_FIX: Option<&str> = Some("NoneType"); #[cfg(not(Py_LIMITED_API))] fn check_repr( reference: &Bound<'_, PyWeakrefProxy>, object: &Bound<'_, PyAny>, class: Option<&str>, ) -> PyResult<()> { let repr = reference.repr()?.to_string(); #[cfg(Py_3_13)] let (first_part, second_part) = repr.split_once(';').unwrap(); #[cfg(not(Py_3_13))] let (first_part, second_part) = repr.split_once(" to ").unwrap(); { let (msg, addr) = first_part.split_once("0x").unwrap(); assert_eq!(msg, "<weakproxy at "); assert!(addr .to_lowercase() .contains(format!("{:x?}", reference.as_ptr()).split_at(2).1)); } if let Some(class) = class.or(DEADREF_FIX) { let (msg, addr) = second_part.split_once("0x").unwrap(); // Avoids not succeeding at unreliable quotation (Python 3.13-dev adds ' around classname without documenting) #[cfg(Py_3_13)] assert!(msg.starts_with(" to '")); assert!(msg.contains(class)); assert!(msg.ends_with(" at ")); assert!(addr .to_lowercase() .contains(format!("{:x?}", object.as_ptr()).split_at(2).1)); } else { assert!(second_part.contains("dead")); } Ok(()) } mod proxy { use super::*; #[cfg(all(not(Py_LIMITED_API), Py_3_10))] const CLASS_NAME: &str = "'weakref.ProxyType'"; #[cfg(all(not(Py_LIMITED_API), not(Py_3_10)))] const CLASS_NAME: &str = "'weakproxy'"; mod python_class { use super::*; use crate::ffi; use crate::{py_result_ext::PyResultExt, types::PyDict, types::PyType}; fn get_type(py: Python<'_>) -> PyResult<Bound<'_, PyType>> { let globals = PyDict::new(py); py.run(ffi::c_str!("class A:\n pass\n"), Some(&globals), None)?; py.eval(ffi::c_str!("A"), Some(&globals), None) .downcast_into::<PyType>() } #[test] fn test_weakref_proxy_behavior() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; assert!(!reference.is(&object)); assert!(reference.upgrade().unwrap().is(&object)); #[cfg(not(Py_LIMITED_API))] assert_eq!( reference.get_type().to_string(), format!("<class {}>", CLASS_NAME) ); assert_eq!(reference.getattr("__class__")?.to_string(), "<class 'A'>"); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, &object, Some("A"))?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyAttributeError>(py))); assert!(reference.call0().err().map_or(false, |err| { let result = err.is_instance_of::<PyTypeError>(py); #[cfg(not(Py_LIMITED_API))] let result = result & (err.value(py).to_string() == format!("{} object is not callable", CLASS_NAME)); result })); drop(object); assert!(reference.upgrade().is_none()); assert!(reference .getattr("__class__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, py.None().bind(py), None)?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); assert!(reference.call0().err().map_or(false, |err| { let result = err.is_instance_of::<PyTypeError>(py); #[cfg(not(Py_LIMITED_API))] let result = result & (err.value(py).to_string() == format!("{} object is not callable", CLASS_NAME)); result })); Ok(()) }) } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(reference.upgrade().is_none()); Ok(()) }) } #[test] fn test_weakref_get_object() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; assert!(reference.upgrade().unwrap().is(&object)); drop(object); assert!(reference.upgrade().is_none()); Ok(()) }) } } // under 'abi3-py37' and 'abi3-py38' PyClass cannot be weakreferencable. #[cfg(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))))] mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} #[test] fn test_weakref_proxy_behavior() -> PyResult<()> { Python::with_gil(|py| { let object: Bound<'_, WeakrefablePyClass> = Bound::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(&object)?; assert!(!reference.is(&object)); assert!(reference.upgrade().unwrap().is(&object)); #[cfg(not(Py_LIMITED_API))] assert_eq!( reference.get_type().to_string(), format!("<class {}>", CLASS_NAME) ); assert_eq!( reference.getattr("__class__")?.to_string(), "<class 'builtins.WeakrefablePyClass'>" ); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, object.as_any(), Some("WeakrefablePyClass"))?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyAttributeError>(py))); assert!(reference.call0().err().map_or(false, |err| { let result = err.is_instance_of::<PyTypeError>(py); #[cfg(not(Py_LIMITED_API))] let result = result & (err.value(py).to_string() == format!("{} object is not callable", CLASS_NAME)); result })); drop(object); assert!(reference.upgrade().is_none()); assert!(reference .getattr("__class__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, py.None().bind(py), None)?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); assert!(reference.call0().err().map_or(false, |err| { let result = err.is_instance_of::<PyTypeError>(py); #[cfg(not(Py_LIMITED_API))] let result = result & (err.value(py).to_string() == format!("{} object is not callable", CLASS_NAME)); result })); Ok(()) }) } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(reference.upgrade().is_none()); Ok(()) }) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; assert!(reference.get_object().is(&object)); drop(object); assert!(reference.get_object().is_none()); Ok(()) }) } } } mod callable_proxy { use super::*; #[cfg(all(not(Py_LIMITED_API), Py_3_10))] const CLASS_NAME: &str = "<class 'weakref.CallableProxyType'>"; #[cfg(all(not(Py_LIMITED_API), not(Py_3_10)))] const CLASS_NAME: &str = "<class 'weakcallableproxy'>"; mod python_class { use super::*; use crate::ffi; use crate::{py_result_ext::PyResultExt, types::PyDict, types::PyType}; fn get_type(py: Python<'_>) -> PyResult<Bound<'_, PyType>> { let globals = PyDict::new(py); py.run( ffi::c_str!("class A:\n def __call__(self):\n return 'This class is callable!'\n"), Some(&globals), None, )?; py.eval(ffi::c_str!("A"), Some(&globals), None) .downcast_into::<PyType>() } #[test] fn test_weakref_proxy_behavior() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; assert!(!reference.is(&object)); assert!(reference.upgrade().unwrap().is(&object)); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.get_type().to_string(), CLASS_NAME); assert_eq!(reference.getattr("__class__")?.to_string(), "<class 'A'>"); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, &object, Some("A"))?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyAttributeError>(py))); assert_eq!(reference.call0()?.to_string(), "This class is callable!"); drop(object); assert!(reference.upgrade().is_none()); assert!(reference .getattr("__class__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, py.None().bind(py), None)?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); assert!(reference .call0() .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py) & (err.value(py).to_string() == "weakly-referenced object no longer exists"))); Ok(()) }) } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = reference.upgrade_as::<PyAny>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr() && obj.is_exact_instance(&class))); } drop(object); { // This test is a bit weird but ok. let obj = unsafe { reference.upgrade_as_unchecked::<PyAny>() }; assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(reference.upgrade().is_none()); Ok(()) }) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { Python::with_gil(|py| { let class = get_type(py)?; let object = class.call0()?; let reference = PyWeakrefProxy::new(&object)?; assert!(reference.get_object().is(&object)); drop(object); assert!(reference.get_object().is_none()); Ok(()) }) } } // under 'abi3-py37' and 'abi3-py38' PyClass cannot be weakreferencable. #[cfg(all(feature = "macros", not(all(Py_LIMITED_API, not(Py_3_9)))))] mod pyo3_pyclass { use super::*; use crate::{pyclass, pymethods, Py}; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} #[pymethods(crate = "crate")] impl WeakrefablePyClass { fn __call__(&self) -> &str { "This class is callable!" } } #[test] fn test_weakref_proxy_behavior() -> PyResult<()> { Python::with_gil(|py| { let object: Bound<'_, WeakrefablePyClass> = Bound::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(&object)?; assert!(!reference.is(&object)); assert!(reference.upgrade().unwrap().is(&object)); #[cfg(not(Py_LIMITED_API))] assert_eq!(reference.get_type().to_string(), CLASS_NAME); assert_eq!( reference.getattr("__class__")?.to_string(), "<class 'builtins.WeakrefablePyClass'>" ); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, object.as_any(), Some("WeakrefablePyClass"))?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyAttributeError>(py))); assert_eq!(reference.call0()?.to_string(), "This class is callable!"); drop(object); assert!(reference.upgrade().is_none()); assert!(reference .getattr("__class__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); #[cfg(not(Py_LIMITED_API))] check_repr(&reference, py.None().bind(py), None)?; assert!(reference .getattr("__callback__") .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py))); assert!(reference .call0() .err() .map_or(false, |err| err.is_instance_of::<PyReferenceError>(py) & (err.value(py).to_string() == "weakly-referenced object no longer exists"))); Ok(()) }) } #[test] fn test_weakref_upgrade_as() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = reference.upgrade_as::<WeakrefablePyClass>(); assert!(obj.is_ok()); let obj = obj.unwrap(); assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade_as_unchecked() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_some()); assert!(obj.map_or(false, |obj| obj.as_ptr() == object.as_ptr())); } drop(object); { let obj = unsafe { reference.upgrade_as_unchecked::<WeakrefablePyClass>() }; assert!(obj.is_none()); } Ok(()) }) } #[test] fn test_weakref_upgrade() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; assert!(reference.upgrade().is_some()); assert!(reference.upgrade().map_or(false, |obj| obj.is(&object))); drop(object); assert!(reference.upgrade().is_none()); Ok(()) }) } #[test] #[allow(deprecated)] fn test_weakref_get_object() -> PyResult<()> { Python::with_gil(|py| { let object = Py::new(py, WeakrefablePyClass {})?; let reference = PyWeakrefProxy::new(object.bind(py))?; assert!(reference.get_object().is(&object)); drop(object); assert!(reference.get_object().is_none()); Ok(()) }) } } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types
lc_public_repos/langsmith-sdk/vendor/pyo3/src/types/weakref/mod.rs
pub use anyref::{PyWeakref, PyWeakrefMethods}; pub use proxy::PyWeakrefProxy; pub use reference::PyWeakrefReference; pub(crate) mod anyref; pub(crate) mod proxy; pub(crate) mod reference;
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/internal/get_slot.rs
use crate::{ ffi, types::{PyType, PyTypeMethods}, Borrowed, Bound, }; use std::os::raw::c_int; impl Bound<'_, PyType> { #[inline] pub(crate) fn get_slot<const S: c_int>(&self, slot: Slot<S>) -> <Slot<S> as GetSlotImpl>::Type where Slot<S>: GetSlotImpl, { // SAFETY: `self` is a valid type object. unsafe { slot.get_slot( self.as_type_ptr(), #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] is_runtime_3_10(self.py()), ) } } } impl Borrowed<'_, '_, PyType> { #[inline] pub(crate) fn get_slot<const S: c_int>(self, slot: Slot<S>) -> <Slot<S> as GetSlotImpl>::Type where Slot<S>: GetSlotImpl, { // SAFETY: `self` is a valid type object. unsafe { slot.get_slot( self.as_type_ptr(), #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] is_runtime_3_10(self.py()), ) } } } /// Gets a slot from a raw FFI pointer. /// /// Safety: /// - `ty` must be a valid non-null pointer to a `PyTypeObject`. /// - The Python runtime must be initialized pub(crate) unsafe fn get_slot<const S: c_int>( ty: *mut ffi::PyTypeObject, slot: Slot<S>, ) -> <Slot<S> as GetSlotImpl>::Type where Slot<S>: GetSlotImpl, { slot.get_slot( ty, // SAFETY: the Python runtime is initialized #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] is_runtime_3_10(crate::Python::assume_gil_acquired()), ) } pub(crate) trait GetSlotImpl { type Type; /// Gets the requested slot from a type object. /// /// Safety: /// - `ty` must be a valid non-null pointer to a `PyTypeObject`. /// - `is_runtime_3_10` must be `false` if the runtime is not Python 3.10 or later. unsafe fn get_slot( self, ty: *mut ffi::PyTypeObject, #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] is_runtime_3_10: bool, ) -> Self::Type; } #[derive(Copy, Clone)] pub(crate) struct Slot<const S: c_int>; macro_rules! impl_slots { ($($name:ident: ($slot:ident, $field:ident) -> $tp:ty),+ $(,)?) => { $( pub (crate) const $name: Slot<{ ffi::$slot }> = Slot; impl GetSlotImpl for Slot<{ ffi::$slot }> { type Type = $tp; #[inline] unsafe fn get_slot( self, ty: *mut ffi::PyTypeObject, #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] is_runtime_3_10: bool ) -> Self::Type { #[cfg(not(Py_LIMITED_API))] { (*ty).$field } #[cfg(Py_LIMITED_API)] { #[cfg(not(Py_3_10))] { // Calling PyType_GetSlot on static types is not valid before Python 3.10 // ... so the workaround is to first do a runtime check for these versions // (3.7, 3.8, 3.9) and then look in the type object anyway. This is only ok // because we know that the interpreter is not going to change the size // of the type objects for these historical versions. if !is_runtime_3_10 && ffi::PyType_HasFeature(ty, ffi::Py_TPFLAGS_HEAPTYPE) == 0 { return (*ty.cast::<PyTypeObject39Snapshot>()).$field; } } // SAFETY: slot type is set carefully to be valid std::mem::transmute(ffi::PyType_GetSlot(ty, ffi::$slot)) } } } )* }; } // Slots are implemented on-demand as needed.) impl_slots! { TP_ALLOC: (Py_tp_alloc, tp_alloc) -> Option<ffi::allocfunc>, TP_BASE: (Py_tp_base, tp_base) -> *mut ffi::PyTypeObject, TP_CLEAR: (Py_tp_clear, tp_clear) -> Option<ffi::inquiry>, TP_DESCR_GET: (Py_tp_descr_get, tp_descr_get) -> Option<ffi::descrgetfunc>, TP_FREE: (Py_tp_free, tp_free) -> Option<ffi::freefunc>, TP_TRAVERSE: (Py_tp_traverse, tp_traverse) -> Option<ffi::traverseproc>, } #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] fn is_runtime_3_10(py: crate::Python<'_>) -> bool { use crate::sync::GILOnceCell; static IS_RUNTIME_3_10: GILOnceCell<bool> = GILOnceCell::new(); *IS_RUNTIME_3_10.get_or_init(py, || py.version_info() >= (3, 10)) } #[repr(C)] #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] pub struct PyNumberMethods39Snapshot { pub nb_add: Option<ffi::binaryfunc>, pub nb_subtract: Option<ffi::binaryfunc>, pub nb_multiply: Option<ffi::binaryfunc>, pub nb_remainder: Option<ffi::binaryfunc>, pub nb_divmod: Option<ffi::binaryfunc>, pub nb_power: Option<ffi::ternaryfunc>, pub nb_negative: Option<ffi::unaryfunc>, pub nb_positive: Option<ffi::unaryfunc>, pub nb_absolute: Option<ffi::unaryfunc>, pub nb_bool: Option<ffi::inquiry>, pub nb_invert: Option<ffi::unaryfunc>, pub nb_lshift: Option<ffi::binaryfunc>, pub nb_rshift: Option<ffi::binaryfunc>, pub nb_and: Option<ffi::binaryfunc>, pub nb_xor: Option<ffi::binaryfunc>, pub nb_or: Option<ffi::binaryfunc>, pub nb_int: Option<ffi::unaryfunc>, pub nb_reserved: *mut std::os::raw::c_void, pub nb_float: Option<ffi::unaryfunc>, pub nb_inplace_add: Option<ffi::binaryfunc>, pub nb_inplace_subtract: Option<ffi::binaryfunc>, pub nb_inplace_multiply: Option<ffi::binaryfunc>, pub nb_inplace_remainder: Option<ffi::binaryfunc>, pub nb_inplace_power: Option<ffi::ternaryfunc>, pub nb_inplace_lshift: Option<ffi::binaryfunc>, pub nb_inplace_rshift: Option<ffi::binaryfunc>, pub nb_inplace_and: Option<ffi::binaryfunc>, pub nb_inplace_xor: Option<ffi::binaryfunc>, pub nb_inplace_or: Option<ffi::binaryfunc>, pub nb_floor_divide: Option<ffi::binaryfunc>, pub nb_true_divide: Option<ffi::binaryfunc>, pub nb_inplace_floor_divide: Option<ffi::binaryfunc>, pub nb_inplace_true_divide: Option<ffi::binaryfunc>, pub nb_index: Option<ffi::unaryfunc>, pub nb_matrix_multiply: Option<ffi::binaryfunc>, pub nb_inplace_matrix_multiply: Option<ffi::binaryfunc>, } #[repr(C)] #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] pub struct PySequenceMethods39Snapshot { pub sq_length: Option<ffi::lenfunc>, pub sq_concat: Option<ffi::binaryfunc>, pub sq_repeat: Option<ffi::ssizeargfunc>, pub sq_item: Option<ffi::ssizeargfunc>, pub was_sq_slice: *mut std::os::raw::c_void, pub sq_ass_item: Option<ffi::ssizeobjargproc>, pub was_sq_ass_slice: *mut std::os::raw::c_void, pub sq_contains: Option<ffi::objobjproc>, pub sq_inplace_concat: Option<ffi::binaryfunc>, pub sq_inplace_repeat: Option<ffi::ssizeargfunc>, } #[repr(C)] #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] pub struct PyMappingMethods39Snapshot { pub mp_length: Option<ffi::lenfunc>, pub mp_subscript: Option<ffi::binaryfunc>, pub mp_ass_subscript: Option<ffi::objobjargproc>, } #[repr(C)] #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] pub struct PyAsyncMethods39Snapshot { pub am_await: Option<ffi::unaryfunc>, pub am_aiter: Option<ffi::unaryfunc>, pub am_anext: Option<ffi::unaryfunc>, } #[repr(C)] #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] pub struct PyBufferProcs39Snapshot { // not available in limited api, but structure needs to have the right size pub bf_getbuffer: *mut std::os::raw::c_void, pub bf_releasebuffer: *mut std::os::raw::c_void, } /// Snapshot of the structure of PyTypeObject for Python 3.7 through 3.9. /// /// This is used as a fallback for static types in abi3 when the Python version is less than 3.10; /// this is a bit of a hack but there's no better option and the structure of the type object is /// not going to change for those historical versions. #[repr(C)] #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] struct PyTypeObject39Snapshot { pub ob_base: ffi::PyVarObject, pub tp_name: *const std::os::raw::c_char, pub tp_basicsize: ffi::Py_ssize_t, pub tp_itemsize: ffi::Py_ssize_t, pub tp_dealloc: Option<ffi::destructor>, #[cfg(not(Py_3_8))] pub tp_print: *mut std::os::raw::c_void, // stubbed out, not available in limited API #[cfg(Py_3_8)] pub tp_vectorcall_offset: ffi::Py_ssize_t, pub tp_getattr: Option<ffi::getattrfunc>, pub tp_setattr: Option<ffi::setattrfunc>, pub tp_as_async: *mut PyAsyncMethods39Snapshot, pub tp_repr: Option<ffi::reprfunc>, pub tp_as_number: *mut PyNumberMethods39Snapshot, pub tp_as_sequence: *mut PySequenceMethods39Snapshot, pub tp_as_mapping: *mut PyMappingMethods39Snapshot, pub tp_hash: Option<ffi::hashfunc>, pub tp_call: Option<ffi::ternaryfunc>, pub tp_str: Option<ffi::reprfunc>, pub tp_getattro: Option<ffi::getattrofunc>, pub tp_setattro: Option<ffi::setattrofunc>, pub tp_as_buffer: *mut PyBufferProcs39Snapshot, pub tp_flags: std::os::raw::c_ulong, pub tp_doc: *const std::os::raw::c_char, pub tp_traverse: Option<ffi::traverseproc>, pub tp_clear: Option<ffi::inquiry>, pub tp_richcompare: Option<ffi::richcmpfunc>, pub tp_weaklistoffset: ffi::Py_ssize_t, pub tp_iter: Option<ffi::getiterfunc>, pub tp_iternext: Option<ffi::iternextfunc>, pub tp_methods: *mut ffi::PyMethodDef, pub tp_members: *mut ffi::PyMemberDef, pub tp_getset: *mut ffi::PyGetSetDef, pub tp_base: *mut ffi::PyTypeObject, pub tp_dict: *mut ffi::PyObject, pub tp_descr_get: Option<ffi::descrgetfunc>, pub tp_descr_set: Option<ffi::descrsetfunc>, pub tp_dictoffset: ffi::Py_ssize_t, pub tp_init: Option<ffi::initproc>, pub tp_alloc: Option<ffi::allocfunc>, pub tp_new: Option<ffi::newfunc>, pub tp_free: Option<ffi::freefunc>, pub tp_is_gc: Option<ffi::inquiry>, pub tp_bases: *mut ffi::PyObject, pub tp_mro: *mut ffi::PyObject, pub tp_cache: *mut ffi::PyObject, pub tp_subclasses: *mut ffi::PyObject, pub tp_weaklist: *mut ffi::PyObject, pub tp_del: Option<ffi::destructor>, pub tp_version_tag: std::os::raw::c_uint, pub tp_finalize: Option<ffi::destructor>, #[cfg(Py_3_8)] pub tp_vectorcall: Option<ffi::vectorcallfunc>, }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pycell/impl_.rs
#![allow(missing_docs)] //! Crate-private implementation of PyClassObject use std::cell::UnsafeCell; use std::marker::PhantomData; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicUsize, Ordering}; use crate::impl_::pyclass::{ PyClassBaseType, PyClassDict, PyClassImpl, PyClassThreadChecker, PyClassWeakRef, }; use crate::internal::get_slot::TP_FREE; use crate::type_object::{PyLayout, PySizedLayout}; use crate::types::{PyType, PyTypeMethods}; use crate::{ffi, PyClass, PyTypeInfo, Python}; use super::{PyBorrowError, PyBorrowMutError}; pub trait PyClassMutability { // The storage for this inheritance layer. Only the first mutable class in // an inheritance hierarchy needs to store the borrow flag. type Storage: PyClassBorrowChecker; // The borrow flag needed to implement this class' mutability. Empty until // the first mutable class, at which point it is BorrowChecker and will be // for all subclasses. type Checker: PyClassBorrowChecker; type ImmutableChild: PyClassMutability; type MutableChild: PyClassMutability; } pub struct ImmutableClass(()); pub struct MutableClass(()); pub struct ExtendsMutableAncestor<M: PyClassMutability>(PhantomData<M>); impl PyClassMutability for ImmutableClass { type Storage = EmptySlot; type Checker = EmptySlot; type ImmutableChild = ImmutableClass; type MutableChild = MutableClass; } impl PyClassMutability for MutableClass { type Storage = BorrowChecker; type Checker = BorrowChecker; type ImmutableChild = ExtendsMutableAncestor<ImmutableClass>; type MutableChild = ExtendsMutableAncestor<MutableClass>; } impl<M: PyClassMutability> PyClassMutability for ExtendsMutableAncestor<M> { type Storage = EmptySlot; type Checker = BorrowChecker; type ImmutableChild = ExtendsMutableAncestor<ImmutableClass>; type MutableChild = ExtendsMutableAncestor<MutableClass>; } #[derive(Debug)] struct BorrowFlag(AtomicUsize); impl BorrowFlag { pub(crate) const UNUSED: usize = 0; const HAS_MUTABLE_BORROW: usize = usize::MAX; fn increment(&self) -> Result<(), PyBorrowError> { let mut value = self.0.load(Ordering::Relaxed); loop { if value == BorrowFlag::HAS_MUTABLE_BORROW { return Err(PyBorrowError { _private: () }); } match self.0.compare_exchange( // only increment if the value hasn't changed since the // last atomic load value, value + 1, Ordering::Relaxed, Ordering::Relaxed, ) { Ok(..) => { // value has been successfully incremented, we need an acquire fence // so that data this borrow flag protects can be read safely in this thread std::sync::atomic::fence(Ordering::Acquire); break Ok(()); } Err(changed_value) => { // value changed under us, need to try again value = changed_value; } } } } fn decrement(&self) { // impossible to get into a bad state from here so relaxed // ordering is fine, the decrement only needs to eventually // be visible self.0.fetch_sub(1, Ordering::Relaxed); } } pub struct EmptySlot(()); pub struct BorrowChecker(BorrowFlag); pub trait PyClassBorrowChecker { /// Initial value for self fn new() -> Self; /// Increments immutable borrow count, if possible fn try_borrow(&self) -> Result<(), PyBorrowError>; /// Decrements immutable borrow count fn release_borrow(&self); /// Increments mutable borrow count, if possible fn try_borrow_mut(&self) -> Result<(), PyBorrowMutError>; /// Decremements mutable borrow count fn release_borrow_mut(&self); } impl PyClassBorrowChecker for EmptySlot { #[inline] fn new() -> Self { EmptySlot(()) } #[inline] fn try_borrow(&self) -> Result<(), PyBorrowError> { Ok(()) } #[inline] fn release_borrow(&self) {} #[inline] fn try_borrow_mut(&self) -> Result<(), PyBorrowMutError> { unreachable!() } #[inline] fn release_borrow_mut(&self) { unreachable!() } } impl PyClassBorrowChecker for BorrowChecker { #[inline] fn new() -> Self { Self(BorrowFlag(AtomicUsize::new(BorrowFlag::UNUSED))) } fn try_borrow(&self) -> Result<(), PyBorrowError> { self.0.increment() } fn release_borrow(&self) { self.0.decrement(); } fn try_borrow_mut(&self) -> Result<(), PyBorrowMutError> { let flag = &self.0; match flag.0.compare_exchange( // only allowed to transition to mutable borrow if the reference is // currently unused BorrowFlag::UNUSED, BorrowFlag::HAS_MUTABLE_BORROW, // On success, reading the flag and updating its state are an atomic // operation Ordering::AcqRel, // It doesn't matter precisely when the failure gets turned // into an error Ordering::Relaxed, ) { Ok(..) => Ok(()), Err(..) => Err(PyBorrowMutError { _private: () }), } } fn release_borrow_mut(&self) { self.0 .0.store(BorrowFlag::UNUSED, Ordering::Release) } } pub trait GetBorrowChecker<T: PyClassImpl> { fn borrow_checker( class_object: &PyClassObject<T>, ) -> &<T::PyClassMutability as PyClassMutability>::Checker; } impl<T: PyClassImpl<PyClassMutability = Self>> GetBorrowChecker<T> for MutableClass { fn borrow_checker(class_object: &PyClassObject<T>) -> &BorrowChecker { &class_object.contents.borrow_checker } } impl<T: PyClassImpl<PyClassMutability = Self>> GetBorrowChecker<T> for ImmutableClass { fn borrow_checker(class_object: &PyClassObject<T>) -> &EmptySlot { &class_object.contents.borrow_checker } } impl<T: PyClassImpl<PyClassMutability = Self>, M: PyClassMutability> GetBorrowChecker<T> for ExtendsMutableAncestor<M> where T::BaseType: PyClassImpl + PyClassBaseType<LayoutAsBase = PyClassObject<T::BaseType>>, <T::BaseType as PyClassImpl>::PyClassMutability: PyClassMutability<Checker = BorrowChecker>, { fn borrow_checker(class_object: &PyClassObject<T>) -> &BorrowChecker { <<T::BaseType as PyClassImpl>::PyClassMutability as GetBorrowChecker<T::BaseType>>::borrow_checker(&class_object.ob_base) } } /// Base layout of PyClassObject. #[doc(hidden)] #[repr(C)] pub struct PyClassObjectBase<T> { ob_base: T, } unsafe impl<T, U> PyLayout<T> for PyClassObjectBase<U> where U: PySizedLayout<T> {} #[doc(hidden)] pub trait PyClassObjectLayout<T>: PyLayout<T> { fn ensure_threadsafe(&self); fn check_threadsafe(&self) -> Result<(), PyBorrowError>; /// Implementation of tp_dealloc. /// # Safety /// - slf must be a valid pointer to an instance of a T or a subclass. /// - slf must not be used after this call (as it will be freed). unsafe fn tp_dealloc(py: Python<'_>, slf: *mut ffi::PyObject); } impl<T, U> PyClassObjectLayout<T> for PyClassObjectBase<U> where U: PySizedLayout<T>, T: PyTypeInfo, { fn ensure_threadsafe(&self) {} fn check_threadsafe(&self) -> Result<(), PyBorrowError> { Ok(()) } unsafe fn tp_dealloc(py: Python<'_>, slf: *mut ffi::PyObject) { // FIXME: there is potentially subtle issues here if the base is overwritten // at runtime? To be investigated. let type_obj = T::type_object(py); let type_ptr = type_obj.as_type_ptr(); let actual_type = PyType::from_borrowed_type_ptr(py, ffi::Py_TYPE(slf)); // For `#[pyclass]` types which inherit from PyAny, we can just call tp_free if type_ptr == std::ptr::addr_of_mut!(ffi::PyBaseObject_Type) { let tp_free = actual_type .get_slot(TP_FREE) .expect("PyBaseObject_Type should have tp_free"); return tp_free(slf.cast()); } // More complex native types (e.g. `extends=PyDict`) require calling the base's dealloc. #[cfg(not(Py_LIMITED_API))] { // FIXME: should this be using actual_type.tp_dealloc? if let Some(dealloc) = (*type_ptr).tp_dealloc { // Before CPython 3.11 BaseException_dealloc would use Py_GC_UNTRACK which // assumes the exception is currently GC tracked, so we have to re-track // before calling the dealloc so that it can safely call Py_GC_UNTRACK. #[cfg(not(any(Py_3_11, PyPy)))] if ffi::PyType_FastSubclass(type_ptr, ffi::Py_TPFLAGS_BASE_EXC_SUBCLASS) == 1 { ffi::PyObject_GC_Track(slf.cast()); } dealloc(slf); } else { (*actual_type.as_type_ptr()) .tp_free .expect("type missing tp_free")(slf.cast()); } } #[cfg(Py_LIMITED_API)] unreachable!("subclassing native types is not possible with the `abi3` feature"); } } /// The layout of a PyClass as a Python object #[repr(C)] pub struct PyClassObject<T: PyClassImpl> { pub(crate) ob_base: <T::BaseType as PyClassBaseType>::LayoutAsBase, pub(crate) contents: PyClassObjectContents<T>, } #[repr(C)] pub(crate) struct PyClassObjectContents<T: PyClassImpl> { pub(crate) value: ManuallyDrop<UnsafeCell<T>>, pub(crate) borrow_checker: <T::PyClassMutability as PyClassMutability>::Storage, pub(crate) thread_checker: T::ThreadChecker, pub(crate) dict: T::Dict, pub(crate) weakref: T::WeakRef, } impl<T: PyClassImpl> PyClassObject<T> { pub(crate) fn get_ptr(&self) -> *mut T { self.contents.value.get() } /// Gets the offset of the dictionary from the start of the struct in bytes. pub(crate) fn dict_offset() -> ffi::Py_ssize_t { use memoffset::offset_of; let offset = offset_of!(PyClassObject<T>, contents) + offset_of!(PyClassObjectContents<T>, dict); // Py_ssize_t may not be equal to isize on all platforms #[allow(clippy::useless_conversion)] offset.try_into().expect("offset should fit in Py_ssize_t") } /// Gets the offset of the weakref list from the start of the struct in bytes. pub(crate) fn weaklist_offset() -> ffi::Py_ssize_t { use memoffset::offset_of; let offset = offset_of!(PyClassObject<T>, contents) + offset_of!(PyClassObjectContents<T>, weakref); // Py_ssize_t may not be equal to isize on all platforms #[allow(clippy::useless_conversion)] offset.try_into().expect("offset should fit in Py_ssize_t") } } impl<T: PyClassImpl> PyClassObject<T> { pub(crate) fn borrow_checker(&self) -> &<T::PyClassMutability as PyClassMutability>::Checker { T::PyClassMutability::borrow_checker(self) } } unsafe impl<T: PyClassImpl> PyLayout<T> for PyClassObject<T> {} impl<T: PyClass> PySizedLayout<T> for PyClassObject<T> {} impl<T: PyClassImpl> PyClassObjectLayout<T> for PyClassObject<T> where <T::BaseType as PyClassBaseType>::LayoutAsBase: PyClassObjectLayout<T::BaseType>, { fn ensure_threadsafe(&self) { self.contents.thread_checker.ensure(); self.ob_base.ensure_threadsafe(); } fn check_threadsafe(&self) -> Result<(), PyBorrowError> { if !self.contents.thread_checker.check() { return Err(PyBorrowError { _private: () }); } self.ob_base.check_threadsafe() } unsafe fn tp_dealloc(py: Python<'_>, slf: *mut ffi::PyObject) { // Safety: Python only calls tp_dealloc when no references to the object remain. let class_object = &mut *(slf.cast::<PyClassObject<T>>()); if class_object.contents.thread_checker.can_drop(py) { ManuallyDrop::drop(&mut class_object.contents.value); } class_object.contents.dict.clear_dict(py); class_object.contents.weakref.clear_weakrefs(slf, py); <T::BaseType as PyClassBaseType>::LayoutAsBase::tp_dealloc(py, slf) } } #[cfg(test)] #[cfg(feature = "macros")] mod tests { use super::*; use crate::prelude::*; use crate::pyclass::boolean_struct::{False, True}; #[pyclass(crate = "crate", subclass)] struct MutableBase; #[pyclass(crate = "crate", extends = MutableBase, subclass)] struct MutableChildOfMutableBase; #[pyclass(crate = "crate", extends = MutableBase, frozen, subclass)] struct ImmutableChildOfMutableBase; #[pyclass(crate = "crate", extends = MutableChildOfMutableBase)] struct MutableChildOfMutableChildOfMutableBase; #[pyclass(crate = "crate", extends = ImmutableChildOfMutableBase)] struct MutableChildOfImmutableChildOfMutableBase; #[pyclass(crate = "crate", extends = MutableChildOfMutableBase, frozen)] struct ImmutableChildOfMutableChildOfMutableBase; #[pyclass(crate = "crate", extends = ImmutableChildOfMutableBase, frozen)] struct ImmutableChildOfImmutableChildOfMutableBase; #[pyclass(crate = "crate", frozen, subclass)] struct ImmutableBase; #[pyclass(crate = "crate", extends = ImmutableBase, subclass)] struct MutableChildOfImmutableBase; #[pyclass(crate = "crate", extends = ImmutableBase, frozen, subclass)] struct ImmutableChildOfImmutableBase; #[pyclass(crate = "crate", extends = MutableChildOfImmutableBase)] struct MutableChildOfMutableChildOfImmutableBase; #[pyclass(crate = "crate", extends = ImmutableChildOfImmutableBase)] struct MutableChildOfImmutableChildOfImmutableBase; #[pyclass(crate = "crate", extends = MutableChildOfImmutableBase, frozen)] struct ImmutableChildOfMutableChildOfImmutableBase; #[pyclass(crate = "crate", extends = ImmutableChildOfImmutableBase, frozen)] struct ImmutableChildOfImmutableChildOfImmutableBase; fn assert_mutable<T: PyClass<Frozen = False, PyClassMutability = MutableClass>>() {} fn assert_immutable<T: PyClass<Frozen = True, PyClassMutability = ImmutableClass>>() {} fn assert_mutable_with_mutable_ancestor< T: PyClass<Frozen = False, PyClassMutability = ExtendsMutableAncestor<MutableClass>>, >() { } fn assert_immutable_with_mutable_ancestor< T: PyClass<Frozen = True, PyClassMutability = ExtendsMutableAncestor<ImmutableClass>>, >() { } #[test] fn test_inherited_mutability() { // mutable base assert_mutable::<MutableBase>(); // children of mutable base have a mutable ancestor assert_mutable_with_mutable_ancestor::<MutableChildOfMutableBase>(); assert_immutable_with_mutable_ancestor::<ImmutableChildOfMutableBase>(); // grandchildren of mutable base have a mutable ancestor assert_mutable_with_mutable_ancestor::<MutableChildOfMutableChildOfMutableBase>(); assert_mutable_with_mutable_ancestor::<MutableChildOfImmutableChildOfMutableBase>(); assert_immutable_with_mutable_ancestor::<ImmutableChildOfMutableChildOfMutableBase>(); assert_immutable_with_mutable_ancestor::<ImmutableChildOfImmutableChildOfMutableBase>(); // immutable base and children assert_immutable::<ImmutableBase>(); assert_immutable::<ImmutableChildOfImmutableBase>(); assert_immutable::<ImmutableChildOfImmutableChildOfImmutableBase>(); // mutable children of immutable at any level are simply mutable assert_mutable::<MutableChildOfImmutableBase>(); assert_mutable::<MutableChildOfImmutableChildOfImmutableBase>(); // children of the mutable child display this property assert_mutable_with_mutable_ancestor::<MutableChildOfMutableChildOfImmutableBase>(); assert_immutable_with_mutable_ancestor::<ImmutableChildOfMutableChildOfImmutableBase>(); } #[test] fn test_mutable_borrow_prevents_further_borrows() { Python::with_gil(|py| { let mmm = Py::new( py, PyClassInitializer::from(MutableBase) .add_subclass(MutableChildOfMutableBase) .add_subclass(MutableChildOfMutableChildOfMutableBase), ) .unwrap(); let mmm_bound: &Bound<'_, MutableChildOfMutableChildOfMutableBase> = mmm.bind(py); let mmm_refmut = mmm_bound.borrow_mut(); // Cannot take any other mutable or immutable borrows whilst the object is borrowed mutably assert!(mmm_bound .extract::<PyRef<'_, MutableChildOfMutableChildOfMutableBase>>() .is_err()); assert!(mmm_bound .extract::<PyRef<'_, MutableChildOfMutableBase>>() .is_err()); assert!(mmm_bound.extract::<PyRef<'_, MutableBase>>().is_err()); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableChildOfMutableBase>>() .is_err()); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableBase>>() .is_err()); assert!(mmm_bound.extract::<PyRefMut<'_, MutableBase>>().is_err()); // With the borrow dropped, all other borrow attempts will succeed drop(mmm_refmut); assert!(mmm_bound .extract::<PyRef<'_, MutableChildOfMutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound .extract::<PyRef<'_, MutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound.extract::<PyRef<'_, MutableBase>>().is_ok()); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound.extract::<PyRefMut<'_, MutableBase>>().is_ok()); }) } #[test] fn test_immutable_borrows_prevent_mutable_borrows() { Python::with_gil(|py| { let mmm = Py::new( py, PyClassInitializer::from(MutableBase) .add_subclass(MutableChildOfMutableBase) .add_subclass(MutableChildOfMutableChildOfMutableBase), ) .unwrap(); let mmm_bound: &Bound<'_, MutableChildOfMutableChildOfMutableBase> = mmm.bind(py); let mmm_refmut = mmm_bound.borrow(); // Further immutable borrows are ok assert!(mmm_bound .extract::<PyRef<'_, MutableChildOfMutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound .extract::<PyRef<'_, MutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound.extract::<PyRef<'_, MutableBase>>().is_ok()); // Further mutable borrows are not ok assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableChildOfMutableBase>>() .is_err()); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableBase>>() .is_err()); assert!(mmm_bound.extract::<PyRefMut<'_, MutableBase>>().is_err()); // With the borrow dropped, all mutable borrow attempts will succeed drop(mmm_refmut); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound .extract::<PyRefMut<'_, MutableChildOfMutableBase>>() .is_ok()); assert!(mmm_bound.extract::<PyRefMut<'_, MutableBase>>().is_ok()); }) } #[test] #[cfg(not(target_arch = "wasm32"))] fn test_thread_safety() { #[crate::pyclass(crate = "crate")] struct MyClass { x: u64, } Python::with_gil(|py| { let inst = Py::new(py, MyClass { x: 0 }).unwrap(); let total_modifications = py.allow_threads(|| { std::thread::scope(|s| { // Spawn a bunch of threads all racing to write to // the same instance of `MyClass`. let threads = (0..10) .map(|_| { s.spawn(|| { Python::with_gil(|py| { // Each thread records its own view of how many writes it made let mut local_modifications = 0; for _ in 0..100 { if let Ok(mut i) = inst.try_borrow_mut(py) { i.x += 1; local_modifications += 1; } } local_modifications }) }) }) .collect::<Vec<_>>(); // Sum up the total number of writes made by all threads threads.into_iter().map(|t| t.join().unwrap()).sum::<u64>() }) }); // If the implementation is free of data races, the total number of writes // should match the final value of `x`. assert_eq!(total_modifications, inst.borrow(py).x); }); } #[test] #[cfg(not(target_arch = "wasm32"))] fn test_thread_safety_2() { struct SyncUnsafeCell<T>(UnsafeCell<T>); unsafe impl<T> Sync for SyncUnsafeCell<T> {} impl<T> SyncUnsafeCell<T> { fn get(&self) -> *mut T { self.0.get() } } let data = SyncUnsafeCell(UnsafeCell::new(0)); let data2 = SyncUnsafeCell(UnsafeCell::new(0)); let borrow_checker = BorrowChecker(BorrowFlag(AtomicUsize::new(BorrowFlag::UNUSED))); std::thread::scope(|s| { s.spawn(|| { for _ in 0..1_000_000 { if borrow_checker.try_borrow_mut().is_ok() { // thread 1 writes to both values during the mutable borrow unsafe { *data.get() += 1 }; unsafe { *data2.get() += 1 }; borrow_checker.release_borrow_mut(); } } }); s.spawn(|| { for _ in 0..1_000_000 { if borrow_checker.try_borrow().is_ok() { // if the borrow checker is working correctly, it should be impossible // for thread 2 to observe a difference in the two values assert_eq!(unsafe { *data.get() }, unsafe { *data2.get() }); borrow_checker.release_borrow(); } } }); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/coroutine/cancel.rs
use crate::{Py, PyAny, PyObject}; use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; #[derive(Debug, Default)] struct Inner { exception: Option<PyObject>, waker: Option<Waker>, } /// Helper used to wait and retrieve exception thrown in [`Coroutine`](super::Coroutine). /// /// Only the last exception thrown can be retrieved. #[derive(Debug, Default)] pub struct CancelHandle(Arc<Mutex<Inner>>); impl CancelHandle { /// Create a new `CoroutineCancel`. pub fn new() -> Self { Default::default() } /// Returns whether the associated coroutine has been cancelled. pub fn is_cancelled(&self) -> bool { self.0.lock().unwrap().exception.is_some() } /// Poll to retrieve the exception thrown in the associated coroutine. pub fn poll_cancelled(&mut self, cx: &mut Context<'_>) -> Poll<PyObject> { let mut inner = self.0.lock().unwrap(); if let Some(exc) = inner.exception.take() { return Poll::Ready(exc); } if let Some(ref waker) = inner.waker { if cx.waker().will_wake(waker) { return Poll::Pending; } } inner.waker = Some(cx.waker().clone()); Poll::Pending } /// Retrieve the exception thrown in the associated coroutine. pub async fn cancelled(&mut self) -> PyObject { Cancelled(self).await } #[doc(hidden)] pub fn throw_callback(&self) -> ThrowCallback { ThrowCallback(self.0.clone()) } } // Because `poll_fn` is not available in MSRV struct Cancelled<'a>(&'a mut CancelHandle); impl Future for Cancelled<'_> { type Output = PyObject; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.0.poll_cancelled(cx) } } #[doc(hidden)] pub struct ThrowCallback(Arc<Mutex<Inner>>); impl ThrowCallback { pub(super) fn throw(&self, exc: Py<PyAny>) { let mut inner = self.0.lock().unwrap(); inner.exception = Some(exc); if let Some(waker) = inner.waker.take() { waker.wake(); } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/coroutine/waker.rs
use crate::sync::GILOnceCell; use crate::types::any::PyAnyMethods; use crate::types::PyCFunction; use crate::{intern, wrap_pyfunction, Bound, Py, PyAny, PyObject, PyResult, Python}; use pyo3_macros::pyfunction; use std::sync::Arc; use std::task::Wake; /// Lazy `asyncio.Future` wrapper, implementing [`Wake`] by calling `Future.set_result`. /// /// asyncio future is let uninitialized until [`initialize_future`][1] is called. /// If [`wake`][2] is called before future initialization (during Rust future polling), /// [`initialize_future`][1] will return `None` (it is roughly equivalent to `asyncio.sleep(0)`) /// /// [1]: AsyncioWaker::initialize_future /// [2]: AsyncioWaker::wake pub struct AsyncioWaker(GILOnceCell<Option<LoopAndFuture>>); impl AsyncioWaker { pub(super) fn new() -> Self { Self(GILOnceCell::new()) } pub(super) fn reset(&mut self) { self.0.take(); } pub(super) fn initialize_future<'py>( &self, py: Python<'py>, ) -> PyResult<Option<&Bound<'py, PyAny>>> { let init = || LoopAndFuture::new(py).map(Some); let loop_and_future = self.0.get_or_try_init(py, init)?.as_ref(); Ok(loop_and_future.map(|LoopAndFuture { future, .. }| future.bind(py))) } } impl Wake for AsyncioWaker { fn wake(self: Arc<Self>) { self.wake_by_ref() } fn wake_by_ref(self: &Arc<Self>) { Python::with_gil(|gil| { if let Some(loop_and_future) = self.0.get_or_init(gil, || None) { loop_and_future .set_result(gil) .expect("unexpected error in coroutine waker"); } }); } } struct LoopAndFuture { event_loop: PyObject, future: PyObject, } impl LoopAndFuture { fn new(py: Python<'_>) -> PyResult<Self> { static GET_RUNNING_LOOP: GILOnceCell<PyObject> = GILOnceCell::new(); let import = || -> PyResult<_> { let module = py.import("asyncio")?; Ok(module.getattr("get_running_loop")?.into()) }; let event_loop = GET_RUNNING_LOOP.get_or_try_init(py, import)?.call0(py)?; let future = event_loop.call_method0(py, "create_future")?; Ok(Self { event_loop, future }) } fn set_result(&self, py: Python<'_>) -> PyResult<()> { static RELEASE_WAITER: GILOnceCell<Py<PyCFunction>> = GILOnceCell::new(); let release_waiter = RELEASE_WAITER.get_or_try_init(py, || { wrap_pyfunction!(release_waiter, py).map(Bound::unbind) })?; // `Future.set_result` must be called in event loop thread, // so it requires `call_soon_threadsafe` let call_soon_threadsafe = self.event_loop.call_method1( py, intern!(py, "call_soon_threadsafe"), (release_waiter, self.future.bind(py)), ); if let Err(err) = call_soon_threadsafe { // `call_soon_threadsafe` will raise if the event loop is closed; // instead of catching an unspecific `RuntimeError`, check directly if it's closed. let is_closed = self.event_loop.call_method0(py, "is_closed")?; if !is_closed.extract(py)? { return Err(err); } } Ok(()) } } /// Call `future.set_result` if the future is not done. /// /// Future can be cancelled by the event loop before being waken. /// See <https://github.com/python/cpython/blob/main/Lib/asyncio/tasks.py#L452C5-L452C5> #[pyfunction(crate = "crate")] fn release_waiter(future: &Bound<'_, PyAny>) -> PyResult<()> { let done = future.call_method0(intern!(future.py(), "done"))?; if !done.extract::<bool>()? { future.call_method1(intern!(future.py(), "set_result"), (future.py().None(),))?; } Ok(()) }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/err/err_state.rs
use std::{ cell::UnsafeCell, sync::{Mutex, Once}, thread::ThreadId, }; use crate::{ exceptions::{PyBaseException, PyTypeError}, ffi, ffi_ptr_ext::FfiPtrExt, types::{PyAnyMethods, PyTraceback, PyType}, Bound, Py, PyAny, PyErrArguments, PyObject, PyTypeInfo, Python, }; pub(crate) struct PyErrState { // Safety: can only hand out references when in the "normalized" state. Will never change // after normalization. normalized: Once, // Guard against re-entrancy when normalizing the exception state. normalizing_thread: Mutex<Option<ThreadId>>, inner: UnsafeCell<Option<PyErrStateInner>>, } // Safety: The inner value is protected by locking to ensure that only the normalized state is // handed out as a reference. unsafe impl Send for PyErrState {} unsafe impl Sync for PyErrState {} #[cfg(feature = "nightly")] unsafe impl crate::marker::Ungil for PyErrState {} impl PyErrState { pub(crate) fn lazy(f: Box<PyErrStateLazyFn>) -> Self { Self::from_inner(PyErrStateInner::Lazy(f)) } pub(crate) fn lazy_arguments(ptype: Py<PyAny>, args: impl PyErrArguments + 'static) -> Self { Self::from_inner(PyErrStateInner::Lazy(Box::new(move |py| { PyErrStateLazyFnOutput { ptype, pvalue: args.arguments(py), } }))) } pub(crate) fn normalized(normalized: PyErrStateNormalized) -> Self { Self::from_inner(PyErrStateInner::Normalized(normalized)) } pub(crate) fn restore(self, py: Python<'_>) { self.inner .into_inner() .expect("PyErr state should never be invalid outside of normalization") .restore(py) } fn from_inner(inner: PyErrStateInner) -> Self { Self { normalized: Once::new(), normalizing_thread: Mutex::new(None), inner: UnsafeCell::new(Some(inner)), } } #[inline] pub(crate) fn as_normalized(&self, py: Python<'_>) -> &PyErrStateNormalized { if self.normalized.is_completed() { match unsafe { // Safety: self.inner will never be written again once normalized. &*self.inner.get() } { Some(PyErrStateInner::Normalized(n)) => return n, _ => unreachable!(), } } self.make_normalized(py) } #[cold] fn make_normalized(&self, py: Python<'_>) -> &PyErrStateNormalized { // This process is safe because: // - Access is guaranteed not to be concurrent thanks to `Python` GIL token // - Write happens only once, and then never will change again. // Guard against re-entrant normalization, because `Once` does not provide // re-entrancy guarantees. if let Some(thread) = self.normalizing_thread.lock().unwrap().as_ref() { assert!( !(*thread == std::thread::current().id()), "Re-entrant normalization of PyErrState detected" ); } // avoid deadlock of `.call_once` with the GIL py.allow_threads(|| { self.normalized.call_once(|| { self.normalizing_thread .lock() .unwrap() .replace(std::thread::current().id()); // Safety: no other thread can access the inner value while we are normalizing it. let state = unsafe { (*self.inner.get()) .take() .expect("Cannot normalize a PyErr while already normalizing it.") }; let normalized_state = Python::with_gil(|py| PyErrStateInner::Normalized(state.normalize(py))); // Safety: no other thread can access the inner value while we are normalizing it. unsafe { *self.inner.get() = Some(normalized_state); } }) }); match unsafe { // Safety: self.inner will never be written again once normalized. &*self.inner.get() } { Some(PyErrStateInner::Normalized(n)) => n, _ => unreachable!(), } } } pub(crate) struct PyErrStateNormalized { #[cfg(not(Py_3_12))] ptype: Py<PyType>, pub pvalue: Py<PyBaseException>, #[cfg(not(Py_3_12))] ptraceback: Option<Py<PyTraceback>>, } impl PyErrStateNormalized { pub(crate) fn new(pvalue: Bound<'_, PyBaseException>) -> Self { Self { #[cfg(not(Py_3_12))] ptype: pvalue.get_type().into(), #[cfg(not(Py_3_12))] ptraceback: unsafe { Py::from_owned_ptr_or_opt( pvalue.py(), ffi::PyException_GetTraceback(pvalue.as_ptr()), ) }, pvalue: pvalue.into(), } } #[cfg(not(Py_3_12))] pub(crate) fn ptype<'py>(&self, py: Python<'py>) -> Bound<'py, PyType> { self.ptype.bind(py).clone() } #[cfg(Py_3_12)] pub(crate) fn ptype<'py>(&self, py: Python<'py>) -> Bound<'py, PyType> { self.pvalue.bind(py).get_type() } #[cfg(not(Py_3_12))] pub(crate) fn ptraceback<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>> { self.ptraceback .as_ref() .map(|traceback| traceback.bind(py).clone()) } #[cfg(Py_3_12)] pub(crate) fn ptraceback<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>> { unsafe { ffi::PyException_GetTraceback(self.pvalue.as_ptr()) .assume_owned_or_opt(py) .map(|b| b.downcast_into_unchecked()) } } pub(crate) fn take(py: Python<'_>) -> Option<PyErrStateNormalized> { #[cfg(Py_3_12)] { // Safety: PyErr_GetRaisedException can be called when attached to Python and // returns either NULL or an owned reference. unsafe { ffi::PyErr_GetRaisedException().assume_owned_or_opt(py) }.map(|pvalue| { PyErrStateNormalized { // Safety: PyErr_GetRaisedException returns a valid exception type. pvalue: unsafe { pvalue.downcast_into_unchecked() }.unbind(), } }) } #[cfg(not(Py_3_12))] { let (ptype, pvalue, ptraceback) = unsafe { let mut ptype: *mut ffi::PyObject = std::ptr::null_mut(); let mut pvalue: *mut ffi::PyObject = std::ptr::null_mut(); let mut ptraceback: *mut ffi::PyObject = std::ptr::null_mut(); ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback); // Ensure that the exception coming from the interpreter is normalized. if !ptype.is_null() { ffi::PyErr_NormalizeException(&mut ptype, &mut pvalue, &mut ptraceback); } // Safety: PyErr_NormalizeException will have produced up to three owned // references of the correct types. ( ptype .assume_owned_or_opt(py) .map(|b| b.downcast_into_unchecked()), pvalue .assume_owned_or_opt(py) .map(|b| b.downcast_into_unchecked()), ptraceback .assume_owned_or_opt(py) .map(|b| b.downcast_into_unchecked()), ) }; ptype.map(|ptype| PyErrStateNormalized { ptype: ptype.unbind(), pvalue: pvalue.expect("normalized exception value missing").unbind(), ptraceback: ptraceback.map(Bound::unbind), }) } } #[cfg(not(Py_3_12))] unsafe fn from_normalized_ffi_tuple( py: Python<'_>, ptype: *mut ffi::PyObject, pvalue: *mut ffi::PyObject, ptraceback: *mut ffi::PyObject, ) -> Self { PyErrStateNormalized { ptype: Py::from_owned_ptr_or_opt(py, ptype).expect("Exception type missing"), pvalue: Py::from_owned_ptr_or_opt(py, pvalue).expect("Exception value missing"), ptraceback: Py::from_owned_ptr_or_opt(py, ptraceback), } } pub fn clone_ref(&self, py: Python<'_>) -> Self { Self { #[cfg(not(Py_3_12))] ptype: self.ptype.clone_ref(py), pvalue: self.pvalue.clone_ref(py), #[cfg(not(Py_3_12))] ptraceback: self .ptraceback .as_ref() .map(|ptraceback| ptraceback.clone_ref(py)), } } } pub(crate) struct PyErrStateLazyFnOutput { pub(crate) ptype: PyObject, pub(crate) pvalue: PyObject, } pub(crate) type PyErrStateLazyFn = dyn for<'py> FnOnce(Python<'py>) -> PyErrStateLazyFnOutput + Send + Sync; enum PyErrStateInner { Lazy(Box<PyErrStateLazyFn>), Normalized(PyErrStateNormalized), } impl PyErrStateInner { fn normalize(self, py: Python<'_>) -> PyErrStateNormalized { match self { #[cfg(not(Py_3_12))] PyErrStateInner::Lazy(lazy) => { let (ptype, pvalue, ptraceback) = lazy_into_normalized_ffi_tuple(py, lazy); unsafe { PyErrStateNormalized::from_normalized_ffi_tuple(py, ptype, pvalue, ptraceback) } } #[cfg(Py_3_12)] PyErrStateInner::Lazy(lazy) => { // To keep the implementation simple, just write the exception into the interpreter, // which will cause it to be normalized raise_lazy(py, lazy); PyErrStateNormalized::take(py) .expect("exception missing after writing to the interpreter") } PyErrStateInner::Normalized(normalized) => normalized, } } #[cfg(not(Py_3_12))] fn restore(self, py: Python<'_>) { let (ptype, pvalue, ptraceback) = match self { PyErrStateInner::Lazy(lazy) => lazy_into_normalized_ffi_tuple(py, lazy), PyErrStateInner::Normalized(PyErrStateNormalized { ptype, pvalue, ptraceback, }) => ( ptype.into_ptr(), pvalue.into_ptr(), ptraceback.map_or(std::ptr::null_mut(), Py::into_ptr), ), }; unsafe { ffi::PyErr_Restore(ptype, pvalue, ptraceback) } } #[cfg(Py_3_12)] fn restore(self, py: Python<'_>) { match self { PyErrStateInner::Lazy(lazy) => raise_lazy(py, lazy), PyErrStateInner::Normalized(PyErrStateNormalized { pvalue }) => unsafe { ffi::PyErr_SetRaisedException(pvalue.into_ptr()) }, } } } #[cfg(not(Py_3_12))] fn lazy_into_normalized_ffi_tuple( py: Python<'_>, lazy: Box<PyErrStateLazyFn>, ) -> (*mut ffi::PyObject, *mut ffi::PyObject, *mut ffi::PyObject) { // To be consistent with 3.12 logic, go via raise_lazy, but also then normalize // the resulting exception raise_lazy(py, lazy); let mut ptype = std::ptr::null_mut(); let mut pvalue = std::ptr::null_mut(); let mut ptraceback = std::ptr::null_mut(); unsafe { ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback); ffi::PyErr_NormalizeException(&mut ptype, &mut pvalue, &mut ptraceback); } (ptype, pvalue, ptraceback) } /// Raises a "lazy" exception state into the Python interpreter. /// /// In principle this could be split in two; first a function to create an exception /// in a normalized state, and then a call to `PyErr_SetRaisedException` to raise it. /// /// This would require either moving some logic from C to Rust, or requesting a new /// API in CPython. fn raise_lazy(py: Python<'_>, lazy: Box<PyErrStateLazyFn>) { let PyErrStateLazyFnOutput { ptype, pvalue } = lazy(py); unsafe { if ffi::PyExceptionClass_Check(ptype.as_ptr()) == 0 { ffi::PyErr_SetString( PyTypeError::type_object_raw(py).cast(), ffi::c_str!("exceptions must derive from BaseException").as_ptr(), ) } else { ffi::PyErr_SetObject(ptype.as_ptr(), pvalue.as_ptr()) } } } #[cfg(test)] mod tests { use crate::{ exceptions::PyValueError, sync::GILOnceCell, PyErr, PyErrArguments, PyObject, Python, }; #[test] #[should_panic(expected = "Re-entrant normalization of PyErrState detected")] fn test_reentrant_normalization() { static ERR: GILOnceCell<PyErr> = GILOnceCell::new(); struct RecursiveArgs; impl PyErrArguments for RecursiveArgs { fn arguments(self, py: Python<'_>) -> PyObject { // .value(py) triggers normalization ERR.get(py) .expect("is set just below") .value(py) .clone() .into() } } Python::with_gil(|py| { ERR.set(py, PyValueError::new_err(RecursiveArgs)).unwrap(); ERR.get(py).expect("is set just above").value(py); }) } #[test] #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled fn test_no_deadlock_thread_switch() { static ERR: GILOnceCell<PyErr> = GILOnceCell::new(); struct GILSwitchArgs; impl PyErrArguments for GILSwitchArgs { fn arguments(self, py: Python<'_>) -> PyObject { // releasing the GIL potentially allows for other threads to deadlock // with the normalization going on here py.allow_threads(|| { std::thread::sleep(std::time::Duration::from_millis(10)); }); py.None() } } Python::with_gil(|py| ERR.set(py, PyValueError::new_err(GILSwitchArgs)).unwrap()); // Let many threads attempt to read the normalized value at the same time let handles = (0..10) .map(|_| { std::thread::spawn(|| { Python::with_gil(|py| { ERR.get(py).expect("is set just above").value(py); }); }) }) .collect::<Vec<_>>(); for handle in handles { handle.join().unwrap(); } // We should never have deadlocked, and should be able to run // this assertion Python::with_gil(|py| { assert!(ERR .get(py) .expect("is set above") .is_instance_of::<PyValueError>(py)) }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/err/impls.rs
use crate::IntoPyObject; use crate::{err::PyErrArguments, exceptions, PyErr, PyObject, Python}; use std::io; /// Convert `PyErr` to `io::Error` impl From<PyErr> for io::Error { fn from(err: PyErr) -> Self { let kind = Python::with_gil(|py| { if err.is_instance_of::<exceptions::PyBrokenPipeError>(py) { io::ErrorKind::BrokenPipe } else if err.is_instance_of::<exceptions::PyConnectionRefusedError>(py) { io::ErrorKind::ConnectionRefused } else if err.is_instance_of::<exceptions::PyConnectionAbortedError>(py) { io::ErrorKind::ConnectionAborted } else if err.is_instance_of::<exceptions::PyConnectionResetError>(py) { io::ErrorKind::ConnectionReset } else if err.is_instance_of::<exceptions::PyInterruptedError>(py) { io::ErrorKind::Interrupted } else if err.is_instance_of::<exceptions::PyFileNotFoundError>(py) { io::ErrorKind::NotFound } else if err.is_instance_of::<exceptions::PyPermissionError>(py) { io::ErrorKind::PermissionDenied } else if err.is_instance_of::<exceptions::PyFileExistsError>(py) { io::ErrorKind::AlreadyExists } else if err.is_instance_of::<exceptions::PyBlockingIOError>(py) { io::ErrorKind::WouldBlock } else if err.is_instance_of::<exceptions::PyTimeoutError>(py) { io::ErrorKind::TimedOut } else { io::ErrorKind::Other } }); io::Error::new(kind, err) } } /// Create `PyErr` from `io::Error` /// (`OSError` except if the `io::Error` is wrapping a Python exception, /// in this case the exception is returned) impl From<io::Error> for PyErr { fn from(err: io::Error) -> PyErr { // If the error wraps a Python error we return it if err.get_ref().map_or(false, |e| e.is::<PyErr>()) { return *err.into_inner().unwrap().downcast().unwrap(); } match err.kind() { io::ErrorKind::BrokenPipe => exceptions::PyBrokenPipeError::new_err(err), io::ErrorKind::ConnectionRefused => exceptions::PyConnectionRefusedError::new_err(err), io::ErrorKind::ConnectionAborted => exceptions::PyConnectionAbortedError::new_err(err), io::ErrorKind::ConnectionReset => exceptions::PyConnectionResetError::new_err(err), io::ErrorKind::Interrupted => exceptions::PyInterruptedError::new_err(err), io::ErrorKind::NotFound => exceptions::PyFileNotFoundError::new_err(err), io::ErrorKind::PermissionDenied => exceptions::PyPermissionError::new_err(err), io::ErrorKind::AlreadyExists => exceptions::PyFileExistsError::new_err(err), io::ErrorKind::WouldBlock => exceptions::PyBlockingIOError::new_err(err), io::ErrorKind::TimedOut => exceptions::PyTimeoutError::new_err(err), _ => exceptions::PyOSError::new_err(err), } } } impl PyErrArguments for io::Error { fn arguments(self, py: Python<'_>) -> PyObject { //FIXME(icxolu) remove unwrap self.to_string() .into_pyobject(py) .unwrap() .into_any() .unbind() } } impl<W> From<io::IntoInnerError<W>> for PyErr { fn from(err: io::IntoInnerError<W>) -> PyErr { err.into_error().into() } } impl<W: Send + Sync> PyErrArguments for io::IntoInnerError<W> { fn arguments(self, py: Python<'_>) -> PyObject { self.into_error().arguments(py) } } impl From<std::convert::Infallible> for PyErr { fn from(_: std::convert::Infallible) -> PyErr { unreachable!() } } macro_rules! impl_to_pyerr { ($err: ty, $pyexc: ty) => { impl PyErrArguments for $err { fn arguments(self, py: Python<'_>) -> PyObject { // FIXME(icxolu) remove unwrap self.to_string() .into_pyobject(py) .unwrap() .into_any() .unbind() } } impl std::convert::From<$err> for PyErr { fn from(err: $err) -> PyErr { <$pyexc>::new_err(err) } } }; } impl_to_pyerr!(std::array::TryFromSliceError, exceptions::PyValueError); impl_to_pyerr!(std::num::ParseIntError, exceptions::PyValueError); impl_to_pyerr!(std::num::ParseFloatError, exceptions::PyValueError); impl_to_pyerr!(std::num::TryFromIntError, exceptions::PyValueError); impl_to_pyerr!(std::str::ParseBoolError, exceptions::PyValueError); impl_to_pyerr!(std::ffi::IntoStringError, exceptions::PyUnicodeDecodeError); impl_to_pyerr!(std::ffi::NulError, exceptions::PyValueError); impl_to_pyerr!(std::str::Utf8Error, exceptions::PyUnicodeDecodeError); impl_to_pyerr!(std::string::FromUtf8Error, exceptions::PyUnicodeDecodeError); impl_to_pyerr!( std::string::FromUtf16Error, exceptions::PyUnicodeDecodeError ); impl_to_pyerr!( std::char::DecodeUtf16Error, exceptions::PyUnicodeDecodeError ); impl_to_pyerr!(std::net::AddrParseError, exceptions::PyValueError); #[cfg(test)] mod tests { use crate::{PyErr, Python}; use std::io; #[test] fn io_errors() { use crate::types::any::PyAnyMethods; let check_err = |kind, expected_ty| { Python::with_gil(|py| { let rust_err = io::Error::new(kind, "some error msg"); let py_err: PyErr = rust_err.into(); let py_err_msg = format!("{}: some error msg", expected_ty); assert_eq!(py_err.to_string(), py_err_msg); let py_error_clone = py_err.clone_ref(py); let rust_err_from_py_err: io::Error = py_err.into(); assert_eq!(rust_err_from_py_err.to_string(), py_err_msg); assert_eq!(rust_err_from_py_err.kind(), kind); let py_err_recovered_from_rust_err: PyErr = rust_err_from_py_err.into(); assert!(py_err_recovered_from_rust_err .value(py) .is(py_error_clone.value(py))); // It should be the same exception }) }; check_err(io::ErrorKind::BrokenPipe, "BrokenPipeError"); check_err(io::ErrorKind::ConnectionRefused, "ConnectionRefusedError"); check_err(io::ErrorKind::ConnectionAborted, "ConnectionAbortedError"); check_err(io::ErrorKind::ConnectionReset, "ConnectionResetError"); check_err(io::ErrorKind::Interrupted, "InterruptedError"); check_err(io::ErrorKind::NotFound, "FileNotFoundError"); check_err(io::ErrorKind::PermissionDenied, "PermissionError"); check_err(io::ErrorKind::AlreadyExists, "FileExistsError"); check_err(io::ErrorKind::WouldBlock, "BlockingIOError"); check_err(io::ErrorKind::TimedOut, "TimeoutError"); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/err/mod.rs
use crate::instance::Bound; use crate::panic::PanicException; use crate::type_object::PyTypeInfo; use crate::types::any::PyAnyMethods; use crate::types::{string::PyStringMethods, typeobject::PyTypeMethods, PyTraceback, PyType}; use crate::{ exceptions::{self, PyBaseException}, ffi, }; use crate::{Borrowed, BoundObject, Py, PyAny, PyObject, Python}; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; use std::borrow::Cow; use std::ffi::{CStr, CString}; mod err_state; mod impls; use crate::conversion::IntoPyObject; use err_state::{PyErrState, PyErrStateLazyFnOutput, PyErrStateNormalized}; use std::convert::Infallible; /// Represents a Python exception. /// /// To avoid needing access to [`Python`] in `Into` conversions to create `PyErr` (thus improving /// compatibility with `?` and other Rust errors) this type supports creating exceptions instances /// in a lazy fashion, where the full Python object for the exception is created only when needed. /// /// Accessing the contained exception in any way, such as with [`value_bound`](PyErr::value_bound), /// [`get_type_bound`](PyErr::get_type_bound), or [`is_instance_bound`](PyErr::is_instance_bound) /// will create the full exception object if it was not already created. pub struct PyErr { state: PyErrState, } // The inner value is only accessed through ways that require proving the gil is held #[cfg(feature = "nightly")] unsafe impl crate::marker::Ungil for PyErr {} /// Represents the result of a Python call. pub type PyResult<T> = Result<T, PyErr>; /// Error that indicates a failure to convert a PyAny to a more specific Python type. #[derive(Debug)] pub struct DowncastError<'a, 'py> { from: Borrowed<'a, 'py, PyAny>, to: Cow<'static, str>, } impl<'a, 'py> DowncastError<'a, 'py> { /// Create a new `PyDowncastError` representing a failure to convert the object /// `from` into the type named in `to`. pub fn new(from: &'a Bound<'py, PyAny>, to: impl Into<Cow<'static, str>>) -> Self { DowncastError { from: from.as_borrowed(), to: to.into(), } } pub(crate) fn new_from_borrowed( from: Borrowed<'a, 'py, PyAny>, to: impl Into<Cow<'static, str>>, ) -> Self { DowncastError { from, to: to.into(), } } } /// Error that indicates a failure to convert a PyAny to a more specific Python type. #[derive(Debug)] pub struct DowncastIntoError<'py> { from: Bound<'py, PyAny>, to: Cow<'static, str>, } impl<'py> DowncastIntoError<'py> { /// Create a new `DowncastIntoError` representing a failure to convert the object /// `from` into the type named in `to`. pub fn new(from: Bound<'py, PyAny>, to: impl Into<Cow<'static, str>>) -> Self { DowncastIntoError { from, to: to.into(), } } /// Consumes this `DowncastIntoError` and returns the original object, allowing continued /// use of it after a failed conversion. /// /// See [`downcast_into`][PyAnyMethods::downcast_into] for an example. pub fn into_inner(self) -> Bound<'py, PyAny> { self.from } } /// Helper conversion trait that allows to use custom arguments for lazy exception construction. pub trait PyErrArguments: Send + Sync { /// Arguments for exception fn arguments(self, py: Python<'_>) -> PyObject; } impl<T> PyErrArguments for T where T: for<'py> IntoPyObject<'py> + Send + Sync, { fn arguments(self, py: Python<'_>) -> PyObject { // FIXME: `arguments` should become fallible match self.into_pyobject(py) { Ok(obj) => obj.into_any().unbind(), Err(e) => panic!("Converting PyErr arguments failed: {}", e.into()), } } } impl PyErr { /// Creates a new PyErr of type `T`. /// /// `args` can be: /// * a tuple: the exception instance will be created using the equivalent to the Python /// expression `T(*tuple)` /// * any other value: the exception instance will be created using the equivalent to the Python /// expression `T(value)` /// /// This exception instance will be initialized lazily. This avoids the need for the Python GIL /// to be held, but requires `args` to be `Send` and `Sync`. If `args` is not `Send` or `Sync`, /// consider using [`PyErr::from_value_bound`] instead. /// /// If `T` does not inherit from `BaseException`, then a `TypeError` will be returned. /// /// If calling T's constructor with `args` raises an exception, that exception will be returned. /// /// # Examples /// /// ``` /// use pyo3::prelude::*; /// use pyo3::exceptions::PyTypeError; /// /// #[pyfunction] /// fn always_throws() -> PyResult<()> { /// Err(PyErr::new::<PyTypeError, _>("Error message")) /// } /// # /// # Python::with_gil(|py| { /// # let fun = pyo3::wrap_pyfunction!(always_throws, py).unwrap(); /// # let err = fun.call0().expect_err("called a function that should always return an error but the return value was Ok"); /// # assert!(err.is_instance_of::<PyTypeError>(py)) /// # }); /// ``` /// /// In most cases, you can use a concrete exception's constructor instead: /// /// ``` /// use pyo3::prelude::*; /// use pyo3::exceptions::PyTypeError; /// /// #[pyfunction] /// fn always_throws() -> PyResult<()> { /// Err(PyTypeError::new_err("Error message")) /// } /// # /// # Python::with_gil(|py| { /// # let fun = pyo3::wrap_pyfunction!(always_throws, py).unwrap(); /// # let err = fun.call0().expect_err("called a function that should always return an error but the return value was Ok"); /// # assert!(err.is_instance_of::<PyTypeError>(py)) /// # }); /// ``` #[inline] pub fn new<T, A>(args: A) -> PyErr where T: PyTypeInfo, A: PyErrArguments + Send + Sync + 'static, { PyErr::from_state(PyErrState::lazy(Box::new(move |py| { PyErrStateLazyFnOutput { ptype: T::type_object(py).into(), pvalue: args.arguments(py), } }))) } /// Constructs a new PyErr from the given Python type and arguments. /// /// `ty` is the exception type; usually one of the standard exceptions /// like `exceptions::PyRuntimeError`. /// /// `args` is either a tuple or a single value, with the same meaning as in [`PyErr::new`]. /// /// If `ty` does not inherit from `BaseException`, then a `TypeError` will be returned. /// /// If calling `ty` with `args` raises an exception, that exception will be returned. pub fn from_type<A>(ty: Bound<'_, PyType>, args: A) -> PyErr where A: PyErrArguments + Send + Sync + 'static, { PyErr::from_state(PyErrState::lazy_arguments(ty.unbind().into_any(), args)) } /// Deprecated name for [`PyErr::from_type`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::from_type`")] #[inline] pub fn from_type_bound<A>(ty: Bound<'_, PyType>, args: A) -> PyErr where A: PyErrArguments + Send + Sync + 'static, { Self::from_type(ty, args) } /// Creates a new PyErr. /// /// If `obj` is a Python exception object, the PyErr will contain that object. /// /// If `obj` is a Python exception type object, this is equivalent to `PyErr::from_type(obj, ())`. /// /// Otherwise, a `TypeError` is created. /// /// # Examples /// ```rust /// use pyo3::prelude::*; /// use pyo3::PyTypeInfo; /// use pyo3::exceptions::PyTypeError; /// use pyo3::types::PyString; /// /// Python::with_gil(|py| { /// // Case #1: Exception object /// let err = PyErr::from_value(PyTypeError::new_err("some type error") /// .value(py).clone().into_any()); /// assert_eq!(err.to_string(), "TypeError: some type error"); /// /// // Case #2: Exception type /// let err = PyErr::from_value(PyTypeError::type_object(py).into_any()); /// assert_eq!(err.to_string(), "TypeError: "); /// /// // Case #3: Invalid exception value /// let err = PyErr::from_value(PyString::new(py, "foo").into_any()); /// assert_eq!( /// err.to_string(), /// "TypeError: exceptions must derive from BaseException" /// ); /// }); /// ``` pub fn from_value(obj: Bound<'_, PyAny>) -> PyErr { let state = match obj.downcast_into::<PyBaseException>() { Ok(obj) => PyErrState::normalized(PyErrStateNormalized::new(obj)), Err(err) => { // Assume obj is Type[Exception]; let later normalization handle if this // is not the case let obj = err.into_inner(); let py = obj.py(); PyErrState::lazy_arguments(obj.unbind(), py.None()) } }; PyErr::from_state(state) } /// Deprecated name for [`PyErr::from_value`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::from_value`")] #[inline] pub fn from_value_bound(obj: Bound<'_, PyAny>) -> PyErr { Self::from_value(obj) } /// Returns the type of this exception. /// /// # Examples /// ```rust /// use pyo3::{prelude::*, exceptions::PyTypeError, types::PyType}; /// /// Python::with_gil(|py| { /// let err: PyErr = PyTypeError::new_err(("some type error",)); /// assert!(err.get_type(py).is(&PyType::new::<PyTypeError>(py))); /// }); /// ``` pub fn get_type<'py>(&self, py: Python<'py>) -> Bound<'py, PyType> { self.normalized(py).ptype(py) } /// Deprecated name for [`PyErr::get_type`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::get_type`")] #[inline] pub fn get_type_bound<'py>(&self, py: Python<'py>) -> Bound<'py, PyType> { self.get_type(py) } /// Returns the value of this exception. /// /// # Examples /// /// ```rust /// use pyo3::{exceptions::PyTypeError, PyErr, Python}; /// /// Python::with_gil(|py| { /// let err: PyErr = PyTypeError::new_err(("some type error",)); /// assert!(err.is_instance_of::<PyTypeError>(py)); /// assert_eq!(err.value(py).to_string(), "some type error"); /// }); /// ``` pub fn value<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException> { self.normalized(py).pvalue.bind(py) } /// Deprecated name for [`PyErr::value`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::value`")] #[inline] pub fn value_bound<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException> { self.value(py) } /// Consumes self to take ownership of the exception value contained in this error. pub fn into_value(self, py: Python<'_>) -> Py<PyBaseException> { // NB technically this causes one reference count increase and decrease in quick succession // on pvalue, but it's probably not worth optimizing this right now for the additional code // complexity. let normalized = self.normalized(py); let exc = normalized.pvalue.clone_ref(py); if let Some(tb) = normalized.ptraceback(py) { unsafe { ffi::PyException_SetTraceback(exc.as_ptr(), tb.as_ptr()); } } exc } /// Returns the traceback of this exception object. /// /// # Examples /// ```rust /// use pyo3::{exceptions::PyTypeError, Python}; /// /// Python::with_gil(|py| { /// let err = PyTypeError::new_err(("some type error",)); /// assert!(err.traceback(py).is_none()); /// }); /// ``` pub fn traceback<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>> { self.normalized(py).ptraceback(py) } /// Deprecated name for [`PyErr::traceback`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::traceback`")] #[inline] pub fn traceback_bound<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>> { self.traceback(py) } /// Gets whether an error is present in the Python interpreter's global state. #[inline] pub fn occurred(_: Python<'_>) -> bool { unsafe { !ffi::PyErr_Occurred().is_null() } } /// Takes the current error from the Python interpreter's global state and clears the global /// state. If no error is set, returns `None`. /// /// If the error is a `PanicException` (which would have originated from a panic in a pyo3 /// callback) then this function will resume the panic. /// /// Use this function when it is not known if an error should be present. If the error is /// expected to have been set, for example from [`PyErr::occurred`] or by an error return value /// from a C FFI function, use [`PyErr::fetch`]. pub fn take(py: Python<'_>) -> Option<PyErr> { let state = PyErrStateNormalized::take(py)?; let pvalue = state.pvalue.bind(py); if pvalue.get_type().as_ptr() == PanicException::type_object_raw(py).cast() { let msg: String = pvalue .str() .map(|py_str| py_str.to_string_lossy().into()) .unwrap_or_else(|_| String::from("Unwrapped panic from Python code")); Self::print_panic_and_unwind(py, PyErrState::normalized(state), msg) } Some(PyErr::from_state(PyErrState::normalized(state))) } fn print_panic_and_unwind(py: Python<'_>, state: PyErrState, msg: String) -> ! { eprintln!("--- PyO3 is resuming a panic after fetching a PanicException from Python. ---"); eprintln!("Python stack trace below:"); state.restore(py); unsafe { ffi::PyErr_PrintEx(0); } std::panic::resume_unwind(Box::new(msg)) } /// Equivalent to [PyErr::take], but when no error is set: /// - Panics in debug mode. /// - Returns a `SystemError` in release mode. /// /// This behavior is consistent with Python's internal handling of what happens when a C return /// value indicates an error occurred but the global error state is empty. (A lack of exception /// should be treated as a bug in the code which returned an error code but did not set an /// exception.) /// /// Use this function when the error is expected to have been set, for example from /// [PyErr::occurred] or by an error return value from a C FFI function. #[cfg_attr(debug_assertions, track_caller)] #[inline] pub fn fetch(py: Python<'_>) -> PyErr { const FAILED_TO_FETCH: &str = "attempted to fetch exception but none was set"; match PyErr::take(py) { Some(err) => err, #[cfg(debug_assertions)] None => panic!("{}", FAILED_TO_FETCH), #[cfg(not(debug_assertions))] None => exceptions::PySystemError::new_err(FAILED_TO_FETCH), } } /// Creates a new exception type with the given name and docstring. /// /// - `base` can be an existing exception type to subclass, or a tuple of classes. /// - `dict` specifies an optional dictionary of class variables and methods. /// - `doc` will be the docstring seen by python users. /// /// /// # Errors /// /// This function returns an error if `name` is not of the form `<module>.<ExceptionName>`. pub fn new_type<'py>( py: Python<'py>, name: &CStr, doc: Option<&CStr>, base: Option<&Bound<'py, PyType>>, dict: Option<PyObject>, ) -> PyResult<Py<PyType>> { let base: *mut ffi::PyObject = match base { None => std::ptr::null_mut(), Some(obj) => obj.as_ptr(), }; let dict: *mut ffi::PyObject = match dict { None => std::ptr::null_mut(), Some(obj) => obj.as_ptr(), }; let doc_ptr = match doc.as_ref() { Some(c) => c.as_ptr(), None => std::ptr::null(), }; let ptr = unsafe { ffi::PyErr_NewExceptionWithDoc(name.as_ptr(), doc_ptr, base, dict) }; unsafe { Py::from_owned_ptr_or_err(py, ptr) } } /// Deprecated name for [`PyErr::new_type`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::new_type`")] #[inline] pub fn new_type_bound<'py>( py: Python<'py>, name: &str, doc: Option<&str>, base: Option<&Bound<'py, PyType>>, dict: Option<PyObject>, ) -> PyResult<Py<PyType>> { let null_terminated_name = CString::new(name).expect("Failed to initialize nul terminated exception name"); let null_terminated_doc = doc.map(|d| CString::new(d).expect("Failed to initialize nul terminated docstring")); Self::new_type( py, &null_terminated_name, null_terminated_doc.as_deref(), base, dict, ) } /// Prints a standard traceback to `sys.stderr`. pub fn display(&self, py: Python<'_>) { #[cfg(Py_3_12)] unsafe { ffi::PyErr_DisplayException(self.value(py).as_ptr()) } #[cfg(not(Py_3_12))] unsafe { // keep the bound `traceback` alive for entire duration of // PyErr_Display. if we inline this, the `Bound` will be dropped // after the argument got evaluated, leading to call with a dangling // pointer. let traceback = self.traceback(py); let type_bound = self.get_type(py); ffi::PyErr_Display( type_bound.as_ptr(), self.value(py).as_ptr(), traceback .as_ref() .map_or(std::ptr::null_mut(), |traceback| traceback.as_ptr()), ) } } /// Calls `sys.excepthook` and then prints a standard traceback to `sys.stderr`. pub fn print(&self, py: Python<'_>) { self.clone_ref(py).restore(py); unsafe { ffi::PyErr_PrintEx(0) } } /// Calls `sys.excepthook` and then prints a standard traceback to `sys.stderr`. /// /// Additionally sets `sys.last_{type,value,traceback,exc}` attributes to this exception. pub fn print_and_set_sys_last_vars(&self, py: Python<'_>) { self.clone_ref(py).restore(py); unsafe { ffi::PyErr_PrintEx(1) } } /// Returns true if the current exception matches the exception in `exc`. /// /// If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass. /// If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match. pub fn matches<'py, T>(&self, py: Python<'py>, exc: T) -> Result<bool, T::Error> where T: IntoPyObject<'py>, { Ok(self.is_instance(py, &exc.into_pyobject(py)?.into_any().as_borrowed())) } /// Returns true if the current exception is instance of `T`. #[inline] pub fn is_instance(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool { let type_bound = self.get_type(py); (unsafe { ffi::PyErr_GivenExceptionMatches(type_bound.as_ptr(), ty.as_ptr()) }) != 0 } /// Deprecated name for [`PyErr::is_instance`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::is_instance`")] #[inline] pub fn is_instance_bound(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool { self.is_instance(py, ty) } /// Returns true if the current exception is instance of `T`. #[inline] pub fn is_instance_of<T>(&self, py: Python<'_>) -> bool where T: PyTypeInfo, { self.is_instance(py, &T::type_object(py)) } /// Writes the error back to the Python interpreter's global state. /// This is the opposite of `PyErr::fetch()`. #[inline] pub fn restore(self, py: Python<'_>) { self.state.restore(py) } /// Reports the error as unraisable. /// /// This calls `sys.unraisablehook()` using the current exception and obj argument. /// /// This method is useful to report errors in situations where there is no good mechanism /// to report back to the Python land. In Python this is used to indicate errors in /// background threads or destructors which are protected. In Rust code this is commonly /// useful when you are calling into a Python callback which might fail, but there is no /// obvious way to handle this error other than logging it. /// /// Calling this method has the benefit that the error goes back into a standardized callback /// in Python which for instance allows unittests to ensure that no unraisable error /// actually happend by hooking `sys.unraisablehook`. /// /// Example: /// ```rust /// # use pyo3::prelude::*; /// # use pyo3::exceptions::PyRuntimeError; /// # fn failing_function() -> PyResult<()> { Err(PyRuntimeError::new_err("foo")) } /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// match failing_function() { /// Err(pyerr) => pyerr.write_unraisable(py, None), /// Ok(..) => { /* do something here */ } /// } /// Ok(()) /// }) /// # } #[inline] pub fn write_unraisable(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>) { self.restore(py); unsafe { ffi::PyErr_WriteUnraisable(obj.map_or(std::ptr::null_mut(), Bound::as_ptr)) } } /// Deprecated name for [`PyErr::write_unraisable`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::write_unraisable`")] #[inline] pub fn write_unraisable_bound(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>) { self.write_unraisable(py, obj) } /// Issues a warning message. /// /// May return an `Err(PyErr)` if warnings-as-errors is enabled. /// /// Equivalent to `warnings.warn()` in Python. /// /// The `category` should be one of the `Warning` classes available in /// [`pyo3::exceptions`](crate::exceptions), or a subclass. The Python /// object can be retrieved using [`Python::get_type_bound()`]. /// /// Example: /// ```rust /// # use pyo3::prelude::*; /// # use pyo3::ffi::c_str; /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { /// let user_warning = py.get_type::<pyo3::exceptions::PyUserWarning>(); /// PyErr::warn(py, &user_warning, c_str!("I am warning you"), 0)?; /// Ok(()) /// }) /// # } /// ``` pub fn warn<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &CStr, stacklevel: i32, ) -> PyResult<()> { error_on_minusone(py, unsafe { ffi::PyErr_WarnEx( category.as_ptr(), message.as_ptr(), stacklevel as ffi::Py_ssize_t, ) }) } /// Deprecated name for [`PyErr::warn`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::warn`")] #[inline] pub fn warn_bound<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &str, stacklevel: i32, ) -> PyResult<()> { let message = CString::new(message)?; Self::warn(py, category, &message, stacklevel) } /// Issues a warning message, with more control over the warning attributes. /// /// May return a `PyErr` if warnings-as-errors is enabled. /// /// Equivalent to `warnings.warn_explicit()` in Python. /// /// The `category` should be one of the `Warning` classes available in /// [`pyo3::exceptions`](crate::exceptions), or a subclass. pub fn warn_explicit<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &CStr, filename: &CStr, lineno: i32, module: Option<&CStr>, registry: Option<&Bound<'py, PyAny>>, ) -> PyResult<()> { let module_ptr = match module { None => std::ptr::null_mut(), Some(s) => s.as_ptr(), }; let registry: *mut ffi::PyObject = match registry { None => std::ptr::null_mut(), Some(obj) => obj.as_ptr(), }; error_on_minusone(py, unsafe { ffi::PyErr_WarnExplicit( category.as_ptr(), message.as_ptr(), filename.as_ptr(), lineno, module_ptr, registry, ) }) } /// Deprecated name for [`PyErr::warn_explicit`]. #[deprecated(since = "0.23.0", note = "renamed to `PyErr::warn`")] #[inline] pub fn warn_explicit_bound<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &str, filename: &str, lineno: i32, module: Option<&str>, registry: Option<&Bound<'py, PyAny>>, ) -> PyResult<()> { let message = CString::new(message)?; let filename = CString::new(filename)?; let module = module.map(CString::new).transpose()?; Self::warn_explicit( py, category, &message, &filename, lineno, module.as_deref(), registry, ) } /// Clone the PyErr. This requires the GIL, which is why PyErr does not implement Clone. /// /// # Examples /// ```rust /// use pyo3::{exceptions::PyTypeError, PyErr, Python, prelude::PyAnyMethods}; /// Python::with_gil(|py| { /// let err: PyErr = PyTypeError::new_err(("some type error",)); /// let err_clone = err.clone_ref(py); /// assert!(err.get_type(py).is(&err_clone.get_type(py))); /// assert!(err.value(py).is(err_clone.value(py))); /// match err.traceback(py) { /// None => assert!(err_clone.traceback(py).is_none()), /// Some(tb) => assert!(err_clone.traceback(py).unwrap().is(&tb)), /// } /// }); /// ``` #[inline] pub fn clone_ref(&self, py: Python<'_>) -> PyErr { PyErr::from_state(PyErrState::normalized(self.normalized(py).clone_ref(py))) } /// Return the cause (either an exception instance, or None, set by `raise ... from ...`) /// associated with the exception, as accessible from Python through `__cause__`. pub fn cause(&self, py: Python<'_>) -> Option<PyErr> { use crate::ffi_ptr_ext::FfiPtrExt; let obj = unsafe { ffi::PyException_GetCause(self.value(py).as_ptr()).assume_owned_or_opt(py) }; // PyException_GetCause is documented as potentially returning PyNone, but only GraalPy seems to actually do that #[cfg(GraalPy)] if let Some(cause) = &obj { if cause.is_none() { return None; } } obj.map(Self::from_value) } /// Set the cause associated with the exception, pass `None` to clear it. pub fn set_cause(&self, py: Python<'_>, cause: Option<Self>) { let value = self.value(py); let cause = cause.map(|err| err.into_value(py)); unsafe { // PyException_SetCause _steals_ a reference to cause, so must use .into_ptr() ffi::PyException_SetCause( value.as_ptr(), cause.map_or(std::ptr::null_mut(), Py::into_ptr), ); } } #[inline] fn from_state(state: PyErrState) -> PyErr { PyErr { state } } #[inline] fn normalized(&self, py: Python<'_>) -> &PyErrStateNormalized { self.state.as_normalized(py) } } impl std::fmt::Debug for PyErr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { Python::with_gil(|py| { f.debug_struct("PyErr") .field("type", &self.get_type(py)) .field("value", self.value(py)) .field("traceback", &self.traceback(py)) .finish() }) } } impl std::fmt::Display for PyErr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Python::with_gil(|py| { let value = self.value(py); let type_name = value.get_type().qualname().map_err(|_| std::fmt::Error)?; write!(f, "{}", type_name)?; if let Ok(s) = value.str() { write!(f, ": {}", &s.to_string_lossy()) } else { write!(f, ": <exception str() failed>") } }) } } impl std::error::Error for PyErr {} #[allow(deprecated)] impl IntoPy<PyObject> for PyErr { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } #[allow(deprecated)] impl ToPyObject for PyErr { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } #[allow(deprecated)] impl IntoPy<PyObject> for &PyErr { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { self.into_pyobject(py).unwrap().into_any().unbind() } } impl<'py> IntoPyObject<'py> for PyErr { type Target = PyBaseException; type Output = Bound<'py, Self::Target>; type Error = Infallible; #[inline] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { Ok(self.into_value(py).into_bound(py)) } } impl<'py> IntoPyObject<'py> for &PyErr { type Target = PyBaseException; type Output = Bound<'py, Self::Target>; type Error = Infallible; #[inline] fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { self.clone_ref(py).into_pyobject(py) } } struct PyDowncastErrorArguments { from: Py<PyType>, to: Cow<'static, str>, } impl PyErrArguments for PyDowncastErrorArguments { fn arguments(self, py: Python<'_>) -> PyObject { const FAILED_TO_EXTRACT: Cow<'_, str> = Cow::Borrowed("<failed to extract type name>"); let from = self.from.bind(py).qualname(); let from = match &from { Ok(qn) => qn.to_cow().unwrap_or(FAILED_TO_EXTRACT), Err(_) => FAILED_TO_EXTRACT, }; format!("'{}' object cannot be converted to '{}'", from, self.to) .into_pyobject(py) .unwrap() .into_any() .unbind() } } /// Python exceptions that can be converted to [`PyErr`]. /// /// This is used to implement [`From<Bound<'_, T>> for PyErr`]. /// /// Users should not need to implement this trait directly. It is implemented automatically in the /// [`crate::import_exception!`] and [`crate::create_exception!`] macros. pub trait ToPyErr {} impl<'py, T> std::convert::From<Bound<'py, T>> for PyErr where T: ToPyErr, { #[inline] fn from(err: Bound<'py, T>) -> PyErr { PyErr::from_value(err.into_any()) } } /// Convert `DowncastError` to Python `TypeError`. impl std::convert::From<DowncastError<'_, '_>> for PyErr { fn from(err: DowncastError<'_, '_>) -> PyErr { let args = PyDowncastErrorArguments { from: err.from.get_type().into(), to: err.to, }; exceptions::PyTypeError::new_err(args) } } impl std::error::Error for DowncastError<'_, '_> {} impl std::fmt::Display for DowncastError<'_, '_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { display_downcast_error(f, &self.from, &self.to) } } /// Convert `DowncastIntoError` to Python `TypeError`. impl std::convert::From<DowncastIntoError<'_>> for PyErr { fn from(err: DowncastIntoError<'_>) -> PyErr { let args = PyDowncastErrorArguments { from: err.from.get_type().into(), to: err.to, }; exceptions::PyTypeError::new_err(args) } } impl std::error::Error for DowncastIntoError<'_> {} impl std::fmt::Display for DowncastIntoError<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { display_downcast_error(f, &self.from, &self.to) } } fn display_downcast_error( f: &mut std::fmt::Formatter<'_>, from: &Bound<'_, PyAny>, to: &str, ) -> std::fmt::Result { write!( f, "'{}' object cannot be converted to '{}'", from.get_type().qualname().map_err(|_| std::fmt::Error)?, to ) } #[track_caller] pub fn panic_after_error(_py: Python<'_>) -> ! { unsafe { ffi::PyErr_Print(); } panic!("Python API call failed"); } /// Returns Ok if the error code is not -1. #[inline] pub(crate) fn error_on_minusone<T: SignedInteger>(py: Python<'_>, result: T) -> PyResult<()> { if result != T::MINUS_ONE { Ok(()) } else { Err(PyErr::fetch(py)) } } pub(crate) trait SignedInteger: Eq { const MINUS_ONE: Self; } macro_rules! impl_signed_integer { ($t:ty) => { impl SignedInteger for $t { const MINUS_ONE: Self = -1; } }; } impl_signed_integer!(i8); impl_signed_integer!(i16); impl_signed_integer!(i32); impl_signed_integer!(i64); impl_signed_integer!(i128); impl_signed_integer!(isize); #[cfg(test)] mod tests { use super::PyErrState; use crate::exceptions::{self, PyTypeError, PyValueError}; use crate::{ffi, PyErr, PyTypeInfo, Python}; #[test] fn no_error() { assert!(Python::with_gil(PyErr::take).is_none()); } #[test] fn set_valueerror() { Python::with_gil(|py| { let err: PyErr = exceptions::PyValueError::new_err("some exception message"); assert!(err.is_instance_of::<exceptions::PyValueError>(py)); err.restore(py); assert!(PyErr::occurred(py)); let err = PyErr::fetch(py); assert!(err.is_instance_of::<exceptions::PyValueError>(py)); assert_eq!(err.to_string(), "ValueError: some exception message"); }) } #[test] fn invalid_error_type() { Python::with_gil(|py| { let err: PyErr = PyErr::new::<crate::types::PyString, _>(()); assert!(err.is_instance_of::<exceptions::PyTypeError>(py)); err.restore(py); let err = PyErr::fetch(py); assert!(err.is_instance_of::<exceptions::PyTypeError>(py)); assert_eq!( err.to_string(), "TypeError: exceptions must derive from BaseException" ); }) } #[test] fn set_typeerror() { Python::with_gil(|py| { let err: PyErr = exceptions::PyTypeError::new_err(()); err.restore(py); assert!(PyErr::occurred(py)); drop(PyErr::fetch(py)); }); } #[test] #[should_panic(expected = "new panic")] fn fetching_panic_exception_resumes_unwind() { use crate::panic::PanicException; Python::with_gil(|py| { let err: PyErr = PanicException::new_err("new panic"); err.restore(py); assert!(PyErr::occurred(py)); // should resume unwind let _ = PyErr::fetch(py); }); } #[test] #[should_panic(expected = "new panic")] #[cfg(not(Py_3_12))] fn fetching_normalized_panic_exception_resumes_unwind() { use crate::panic::PanicException; Python::with_gil(|py| { let err: PyErr = PanicException::new_err("new panic"); // Restoring an error doesn't normalize it before Python 3.12, // so we have to explicitly test this case. let _ = err.normalized(py); err.restore(py); assert!(PyErr::occurred(py)); // should resume unwind let _ = PyErr::fetch(py); }); } #[test] fn err_debug() { // Debug representation should be like the following (without the newlines): // PyErr { // type: <class 'Exception'>, // value: Exception('banana'), // traceback: Some(<traceback object at 0x..)" // } Python::with_gil(|py| { let err = py .run(ffi::c_str!("raise Exception('banana')"), None, None) .expect_err("raising should have given us an error"); let debug_str = format!("{:?}", err); assert!(debug_str.starts_with("PyErr { ")); assert!(debug_str.ends_with(" }")); // strip "PyErr { " and " }" let mut fields = debug_str["PyErr { ".len()..debug_str.len() - 2].split(", "); assert_eq!(fields.next().unwrap(), "type: <class 'Exception'>"); assert_eq!(fields.next().unwrap(), "value: Exception('banana')"); let traceback = fields.next().unwrap(); assert!(traceback.starts_with("traceback: Some(<traceback object at 0x")); assert!(traceback.ends_with(">)")); assert!(fields.next().is_none()); }); } #[test] fn err_display() { Python::with_gil(|py| { let err = py .run(ffi::c_str!("raise Exception('banana')"), None, None) .expect_err("raising should have given us an error"); assert_eq!(err.to_string(), "Exception: banana"); }); } #[test] fn test_pyerr_send_sync() { fn is_send<T: Send>() {} fn is_sync<T: Sync>() {} is_send::<PyErr>(); is_sync::<PyErr>(); is_send::<PyErrState>(); is_sync::<PyErrState>(); } #[test] fn test_pyerr_matches() { Python::with_gil(|py| { let err = PyErr::new::<PyValueError, _>("foo"); assert!(err.matches(py, PyValueError::type_object(py)).unwrap()); assert!(err .matches( py, (PyValueError::type_object(py), PyTypeError::type_object(py)) ) .unwrap()); assert!(!err.matches(py, PyTypeError::type_object(py)).unwrap()); // String is not a valid exception class, so we should get a TypeError let err: PyErr = PyErr::from_type(crate::types::PyString::type_object(py), "foo"); assert!(err.matches(py, PyTypeError::type_object(py)).unwrap()); }) } #[test] fn test_pyerr_cause() { Python::with_gil(|py| { let err = py .run(ffi::c_str!("raise Exception('banana')"), None, None) .expect_err("raising should have given us an error"); assert!(err.cause(py).is_none()); let err = py .run( ffi::c_str!("raise Exception('banana') from Exception('apple')"), None, None, ) .expect_err("raising should have given us an error"); let cause = err .cause(py) .expect("raising from should have given us a cause"); assert_eq!(cause.to_string(), "Exception: apple"); err.set_cause(py, None); assert!(err.cause(py).is_none()); let new_cause = exceptions::PyValueError::new_err("orange"); err.set_cause(py, Some(new_cause)); let cause = err .cause(py) .expect("set_cause should have given us a cause"); assert_eq!(cause.to_string(), "ValueError: orange"); }); } #[test] fn warnings() { use crate::types::any::PyAnyMethods; // Note: although the warning filter is interpreter global, keeping the // GIL locked should prevent effects to be visible to other testing // threads. Python::with_gil(|py| { let cls = py.get_type::<exceptions::PyUserWarning>(); // Reset warning filter to default state let warnings = py.import("warnings").unwrap(); warnings.call_method0("resetwarnings").unwrap(); // First, test the warning is emitted #[cfg(not(Py_GIL_DISABLED))] assert_warnings!( py, { PyErr::warn(py, &cls, ffi::c_str!("I am warning you"), 0).unwrap() }, [(exceptions::PyUserWarning, "I am warning you")] ); // Test with raising warnings .call_method1("simplefilter", ("error", &cls)) .unwrap(); PyErr::warn(py, &cls, ffi::c_str!("I am warning you"), 0).unwrap_err(); // Test with error for an explicit module warnings.call_method0("resetwarnings").unwrap(); warnings .call_method1("filterwarnings", ("error", "", &cls, "pyo3test")) .unwrap(); // This has the wrong module and will not raise, just be emitted #[cfg(not(Py_GIL_DISABLED))] assert_warnings!( py, { PyErr::warn(py, &cls, ffi::c_str!("I am warning you"), 0).unwrap() }, [(exceptions::PyUserWarning, "I am warning you")] ); let err = PyErr::warn_explicit( py, &cls, ffi::c_str!("I am warning you"), ffi::c_str!("pyo3test.py"), 427, None, None, ) .unwrap_err(); assert!(err .value(py) .getattr("args") .unwrap() .get_item(0) .unwrap() .eq("I am warning you") .unwrap()); // Finally, reset filter again warnings.call_method0("resetwarnings").unwrap(); }); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/common.rs
// the inner mod enables the #![allow(dead_code)] to // be applied - `test_utils.rs` uses `include!` to pull in this file /// Common macros and helpers for tests #[allow(dead_code)] // many tests do not use the complete set of functionality offered here #[allow(missing_docs)] // only used in tests #[macro_use] mod inner { #[allow(unused_imports)] // pulls in `use crate as pyo3` in `test_utils.rs` use super::*; #[cfg(not(Py_GIL_DISABLED))] use pyo3::prelude::*; #[cfg(not(Py_GIL_DISABLED))] use pyo3::types::{IntoPyDict, PyList}; use uuid::Uuid; #[macro_export] macro_rules! py_assert { ($py:expr, $($val:ident)+, $assertion:literal) => { pyo3::py_run!($py, $($val)+, concat!("assert ", $assertion)) }; ($py:expr, *$dict:expr, $assertion:literal) => { pyo3::py_run!($py, *$dict, concat!("assert ", $assertion)) }; } #[macro_export] macro_rules! assert_py_eq { ($val:expr, $expected:expr) => { assert!($val.eq($expected).unwrap()); }; } #[macro_export] macro_rules! py_expect_exception { // Case1: idents & no err_msg ($py:expr, $($val:ident)+, $code:expr, $err:ident) => {{ use pyo3::types::IntoPyDict; use pyo3::BoundObject; let d = [$((stringify!($val), (&$val).into_pyobject($py).unwrap().into_any().into_bound()),)+].into_py_dict($py).unwrap(); py_expect_exception!($py, *d, $code, $err) }}; // Case2: dict & no err_msg ($py:expr, *$dict:expr, $code:expr, $err:ident) => {{ let res = $py.run(&std::ffi::CString::new($code).unwrap(), None, Some(&$dict.as_borrowed())); let err = res.expect_err(&format!("Did not raise {}", stringify!($err))); if !err.matches($py, $py.get_type::<pyo3::exceptions::$err>()).unwrap() { panic!("Expected {} but got {:?}", stringify!($err), err) } err }}; // Case3: idents & err_msg ($py:expr, $($val:ident)+, $code:expr, $err:ident, $err_msg:literal) => {{ let err = py_expect_exception!($py, $($val)+, $code, $err); // Suppose that the error message looks like 'TypeError: ~' assert_eq!(format!("Py{}", err), concat!(stringify!($err), ": ", $err_msg)); err }}; // Case4: dict & err_msg ($py:expr, *$dict:expr, $code:expr, $err:ident, $err_msg:literal) => {{ let err = py_expect_exception!($py, *$dict, $code, $err); assert_eq!(format!("Py{}", err), concat!(stringify!($err), ": ", $err_msg)); err }}; } // sys.unraisablehook not available until Python 3.8 #[cfg(all(feature = "macros", Py_3_8, not(Py_GIL_DISABLED)))] #[pyclass(crate = "pyo3")] pub struct UnraisableCapture { pub capture: Option<(PyErr, PyObject)>, old_hook: Option<PyObject>, } #[cfg(all(feature = "macros", Py_3_8, not(Py_GIL_DISABLED)))] #[pymethods(crate = "pyo3")] impl UnraisableCapture { pub fn hook(&mut self, unraisable: Bound<'_, PyAny>) { let err = PyErr::from_value(unraisable.getattr("exc_value").unwrap()); let instance = unraisable.getattr("object").unwrap(); self.capture = Some((err, instance.into())); } } #[cfg(all(feature = "macros", Py_3_8, not(Py_GIL_DISABLED)))] impl UnraisableCapture { pub fn install(py: Python<'_>) -> Py<Self> { let sys = py.import("sys").unwrap(); let old_hook = sys.getattr("unraisablehook").unwrap().into(); let capture = Py::new( py, UnraisableCapture { capture: None, old_hook: Some(old_hook), }, ) .unwrap(); sys.setattr("unraisablehook", capture.getattr(py, "hook").unwrap()) .unwrap(); capture } pub fn uninstall(&mut self, py: Python<'_>) { let old_hook = self.old_hook.take().unwrap(); let sys = py.import("sys").unwrap(); sys.setattr("unraisablehook", old_hook).unwrap(); } } #[cfg(not(Py_GIL_DISABLED))] pub struct CatchWarnings<'py> { catch_warnings: Bound<'py, PyAny>, } #[cfg(not(Py_GIL_DISABLED))] impl<'py> CatchWarnings<'py> { pub fn enter<R>( py: Python<'py>, f: impl FnOnce(&Bound<'py, PyList>) -> PyResult<R>, ) -> PyResult<R> { let warnings = py.import("warnings")?; let kwargs = [("record", true)].into_py_dict(py)?; let catch_warnings = warnings .getattr("catch_warnings")? .call((), Some(&kwargs))?; let list = catch_warnings.call_method0("__enter__")?.downcast_into()?; let _guard = Self { catch_warnings }; f(&list) } } #[cfg(not(Py_GIL_DISABLED))] impl Drop for CatchWarnings<'_> { fn drop(&mut self) { let py = self.catch_warnings.py(); self.catch_warnings .call_method1("__exit__", (py.None(), py.None(), py.None())) .unwrap(); } } #[cfg(not(Py_GIL_DISABLED))] #[macro_export] macro_rules! assert_warnings { ($py:expr, $body:expr, [$(($category:ty, $message:literal)),+] $(,)? ) => {{ $crate::tests::common::CatchWarnings::enter($py, |w| { use $crate::types::{PyListMethods, PyStringMethods}; $body; let expected_warnings = [$((<$category as $crate::type_object::PyTypeInfo>::type_object($py), $message)),+]; assert_eq!(w.len(), expected_warnings.len()); for (warning, (category, message)) in w.iter().zip(expected_warnings) { assert!(warning.getattr("category").unwrap().is(&category)); assert_eq!( warning.getattr("message").unwrap().str().unwrap().to_string_lossy(), message ); } Ok(()) }) .unwrap(); }}; } pub fn generate_unique_module_name(base: &str) -> std::ffi::CString { let uuid = Uuid::new_v4().simple().to_string(); std::ffi::CString::new(format!("{base}_{uuid}")).unwrap() } } #[allow(unused_imports)] // some tests use just the macros and none of the other functionality pub use inner::*;
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/mod.rs
#[macro_use] pub(crate) mod common { #[cfg(not(Py_GIL_DISABLED))] use crate as pyo3; include!("./common.rs"); } /// Test macro hygiene - this is in the crate since we won't have /// `pyo3` available in the crate root. #[cfg(all(test, feature = "macros"))] mod hygiene;
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/hygiene/misc.rs
#[derive(crate::FromPyObject)] #[pyo3(crate = "crate")] struct Derive1(i32); // newtype case #[derive(crate::FromPyObject)] #[pyo3(crate = "crate")] struct Derive2(i32, i32); // tuple case #[derive(crate::FromPyObject)] #[pyo3(crate = "crate")] struct Derive3 { f: i32, #[pyo3(item(42))] g: i32, } // struct case #[derive(crate::FromPyObject)] #[pyo3(crate = "crate")] enum Derive4 { A(i32), B { f: i32 }, } // enum case crate::create_exception!(mymodule, CustomError, crate::exceptions::PyException); crate::import_exception!(socket, gaierror); fn intern(py: crate::Python<'_>) { let _foo = crate::intern!(py, "foo"); let _bar = crate::intern!(py, stringify!(bar)); } #[cfg(not(PyPy))] fn append_to_inittab() { #[crate::pymodule] #[pyo3(crate = "crate")] mod module_for_inittab {} crate::append_to_inittab!(module_for_inittab); } macro_rules! macro_rules_hygiene { ($name_a:ident, $name_b:ident) => { #[crate::pyclass(crate = "crate")] struct $name_a {} #[crate::pymethods(crate = "crate")] impl $name_a { fn finalize(&mut self) -> $name_b { $name_b {} } } #[crate::pyclass(crate = "crate")] struct $name_b {} }; } macro_rules_hygiene!(MyClass1, MyClass2); #[derive(crate::IntoPyObject, crate::IntoPyObjectRef)] #[pyo3(crate = "crate")] struct IntoPyObject1(i32); // transparent newtype case #[derive(crate::IntoPyObject, crate::IntoPyObjectRef)] #[pyo3(crate = "crate", transparent)] struct IntoPyObject2<'a> { inner: &'a str, // transparent newtype case } #[derive(crate::IntoPyObject, crate::IntoPyObjectRef)] #[pyo3(crate = "crate")] struct IntoPyObject3<'py>(i32, crate::Bound<'py, crate::PyAny>); // tuple case #[derive(crate::IntoPyObject, crate::IntoPyObjectRef)] #[pyo3(crate = "crate")] struct IntoPyObject4<'a, 'py> { callable: &'a crate::Bound<'py, crate::PyAny>, // struct case num: usize, } #[derive(crate::IntoPyObject, crate::IntoPyObjectRef)] #[pyo3(crate = "crate")] enum IntoPyObject5<'a, 'py> { TransparentTuple(i32), #[pyo3(transparent)] TransparentStruct { f: crate::Py<crate::PyAny>, }, Tuple(crate::Bound<'py, crate::types::PyString>, usize), Struct { f: i32, g: &'a str, }, } // enum case
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/hygiene/pyclass.rs
#[crate::pyclass] #[pyo3(crate = "crate")] #[derive(::std::clone::Clone)] pub struct Foo; #[crate::pyclass] #[pyo3(crate = "crate")] pub struct Foo2; #[cfg_attr(any(Py_3_9, not(Py_LIMITED_API)), crate::pyclass( name = "ActuallyBar", freelist = 8, unsendable, subclass, extends = crate::types::PyAny, module = "Spam", weakref, dict ))] #[cfg_attr(not(any(Py_3_9, not(Py_LIMITED_API))), crate::pyclass( name = "ActuallyBar", freelist = 8, unsendable, subclass, extends = crate::types::PyAny, module = "Spam" ))] #[pyo3(crate = "crate")] pub struct Bar { #[pyo3(get, set)] a: u8, #[pyo3(get, set)] b: Foo, #[pyo3(set)] c: ::std::option::Option<crate::Py<Foo2>>, } #[crate::pyclass(eq, eq_int)] #[pyo3(crate = "crate")] #[derive(PartialEq)] pub enum Enum { Var0, } #[crate::pyclass] #[pyo3(crate = "crate")] pub struct Foo3 { #[pyo3(get, set)] #[cfg(any())] field: i32, #[pyo3(get, set)] #[cfg(not(any()))] field: u32, } #[crate::pyclass] #[pyo3(crate = "crate")] pub struct Foo4 { #[pyo3(get, set)] #[cfg(any())] #[cfg(not(any()))] field: i32, #[pyo3(get, set)] #[cfg(not(any()))] field: u32, } #[crate::pyclass(eq, ord)] #[pyo3(crate = "crate")] #[derive(PartialEq, PartialOrd)] pub struct PointEqOrd { x: u32, y: u32, z: u32, } #[crate::pyclass(eq, ord)] #[pyo3(crate = "crate")] #[derive(PartialEq, PartialOrd)] pub enum ComplexEnumEqOrd { Variant1 { a: u32, b: u32 }, Variant2 { c: u32 }, } #[crate::pyclass(eq, ord)] #[pyo3(crate = "crate")] #[derive(PartialEq, PartialOrd)] pub enum TupleEnumEqOrd { Variant1(u32, u32), Variant2(u32), } #[crate::pyclass(str = "{x}, {y}, {z}")] #[pyo3(crate = "crate")] pub struct PointFmt { x: u32, y: u32, z: u32, } #[crate::pyclass(str)] #[pyo3(crate = "crate")] pub struct Point { x: i32, y: i32, z: i32, } impl ::std::fmt::Display for Point { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::write!(f, "({}, {}, {})", self.x, self.y, self.z) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/hygiene/pymodule.rs
#[crate::pyfunction] #[pyo3(crate = "crate")] fn do_something(x: i32) -> crate::PyResult<i32> { ::std::result::Result::Ok(x) } #[crate::pymodule] #[pyo3(crate = "crate")] fn foo( _py: crate::Python<'_>, _m: &crate::Bound<'_, crate::types::PyModule>, ) -> crate::PyResult<()> { ::std::result::Result::Ok(()) } #[crate::pymodule] #[pyo3(crate = "crate")] fn my_module(m: &crate::Bound<'_, crate::types::PyModule>) -> crate::PyResult<()> { <crate::Bound<'_, crate::types::PyModule> as crate::types::PyModuleMethods>::add_function( m, crate::wrap_pyfunction!(do_something, m)?, )?; <crate::Bound<'_, crate::types::PyModule> as crate::types::PyModuleMethods>::add_wrapped( m, crate::wrap_pymodule!(foo), )?; ::std::result::Result::Ok(()) } #[crate::pymodule(submodule)] #[pyo3(crate = "crate")] mod my_module_declarative { #[pymodule_export] use super::{do_something, foo}; }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/hygiene/pyfunction.rs
#[crate::pyfunction] #[pyo3(crate = "crate")] fn do_something(x: i32) -> crate::PyResult<i32> { ::std::result::Result::Ok(x) } #[test] fn invoke_wrap_pyfunction() { crate::Python::with_gil(|py| { let func = crate::wrap_pyfunction!(do_something, py).unwrap(); crate::py_run!(py, func, r#"func(5)"#); }); }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/hygiene/pymethods.rs
#[crate::pyclass] #[pyo3(crate = "crate")] pub struct Dummy; #[crate::pyclass] #[pyo3(crate = "crate")] pub struct DummyIter; #[crate::pymethods] #[pyo3(crate = "crate")] impl Dummy { ////////////////////// // Basic customization ////////////////////// fn __repr__(&self) -> &'static str { "Dummy" } fn __str__(&self) -> &'static str { "Dummy" } fn __bytes__<'py>(&self, py: crate::Python<'py>) -> crate::Bound<'py, crate::types::PyBytes> { crate::types::PyBytes::new(py, &[0]) } fn __format__(&self, format_spec: ::std::string::String) -> ::std::string::String { ::std::unimplemented!() } fn __lt__(&self, other: &Self) -> bool { false } fn __le__(&self, other: &Self) -> bool { false } fn __eq__(&self, other: &Self) -> bool { false } fn __ne__(&self, other: &Self) -> bool { false } fn __gt__(&self, other: &Self) -> bool { false } fn __ge__(&self, other: &Self) -> bool { false } fn __hash__(&self) -> u64 { 42 } fn __bool__(&self) -> bool { true } ////////////////////// // Customizing attribute access ////////////////////// fn __getattr__(&self, name: ::std::string::String) -> &crate::Bound<'_, crate::PyAny> { ::std::unimplemented!() } fn __getattribute__(&self, name: ::std::string::String) -> &crate::Bound<'_, crate::PyAny> { ::std::unimplemented!() } fn __setattr__(&mut self, name: ::std::string::String, value: ::std::string::String) {} fn __delattr__(&mut self, name: ::std::string::String) {} fn __dir__<'py>( &self, py: crate::Python<'py>, ) -> crate::PyResult<crate::Bound<'py, crate::types::PyList>> { crate::types::PyList::new(py, ::std::vec![0_u8]) } ////////////////////// // Implementing Descriptors ////////////////////// fn __get__( &self, instance: &crate::Bound<'_, crate::PyAny>, owner: &crate::Bound<'_, crate::PyAny>, ) -> crate::PyResult<&crate::Bound<'_, crate::PyAny>> { ::std::unimplemented!() } fn __set__( &self, instance: &crate::Bound<'_, crate::PyAny>, owner: &crate::Bound<'_, crate::PyAny>, ) { } fn __delete__(&self, instance: &crate::Bound<'_, crate::PyAny>) {} fn __set_name__( &self, owner: &crate::Bound<'_, crate::PyAny>, name: &crate::Bound<'_, crate::PyAny>, ) { } ////////////////////// // Implementing Descriptors ////////////////////// fn __len__(&self) -> usize { 0 } fn __getitem__(&self, key: u32) -> crate::PyResult<u32> { ::std::result::Result::Err(crate::exceptions::PyKeyError::new_err("boo")) } fn __setitem__(&self, key: u32, value: u32) {} fn __delitem__(&self, key: u32) {} fn __iter__(_: crate::pycell::PyRef<'_, Self>, py: crate::Python<'_>) -> crate::Py<DummyIter> { crate::Py::new(py, DummyIter {}).unwrap() } fn __next__(&mut self) -> ::std::option::Option<()> { ::std::option::Option::None } fn __reversed__( slf: crate::pycell::PyRef<'_, Self>, py: crate::Python<'_>, ) -> crate::Py<DummyIter> { crate::Py::new(py, DummyIter {}).unwrap() } fn __contains__(&self, item: u32) -> bool { false } ////////////////////// // Emulating numeric types ////////////////////// fn __add__(&self, other: &Self) -> Dummy { Dummy {} } fn __sub__(&self, other: &Self) -> Dummy { Dummy {} } fn __mul__(&self, other: &Self) -> Dummy { Dummy {} } fn __truediv__(&self, _other: &Self) -> crate::PyResult<()> { ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __floordiv__(&self, _other: &Self) -> crate::PyResult<()> { ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __mod__(&self, _other: &Self) -> u32 { 0 } fn __divmod__(&self, _other: &Self) -> (u32, u32) { (0, 0) } fn __pow__(&self, _other: &Self, modulo: ::std::option::Option<i32>) -> Dummy { Dummy {} } fn __lshift__(&self, other: &Self) -> Dummy { Dummy {} } fn __rshift__(&self, other: &Self) -> Dummy { Dummy {} } fn __and__(&self, other: &Self) -> Dummy { Dummy {} } fn __xor__(&self, other: &Self) -> Dummy { Dummy {} } fn __or__(&self, other: &Self) -> Dummy { Dummy {} } fn __radd__(&self, other: &Self) -> Dummy { Dummy {} } fn __rrsub__(&self, other: &Self) -> Dummy { Dummy {} } fn __rmul__(&self, other: &Self) -> Dummy { Dummy {} } fn __rtruediv__(&self, _other: &Self) -> crate::PyResult<()> { ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __rfloordiv__(&self, _other: &Self) -> crate::PyResult<()> { ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __rmod__(&self, _other: &Self) -> u32 { 0 } fn __rdivmod__(&self, _other: &Self) -> (u32, u32) { (0, 0) } fn __rpow__(&self, _other: &Self, modulo: ::std::option::Option<i32>) -> Dummy { Dummy {} } fn __rlshift__(&self, other: &Self) -> Dummy { Dummy {} } fn __rrshift__(&self, other: &Self) -> Dummy { Dummy {} } fn __rand__(&self, other: &Self) -> Dummy { Dummy {} } fn __rxor__(&self, other: &Self) -> Dummy { Dummy {} } fn __ror__(&self, other: &Self) -> Dummy { Dummy {} } fn __iadd__(&mut self, other: &Self) {} fn __irsub__(&mut self, other: &Self) {} fn __imul__(&mut self, other: &Self) {} fn __itruediv__(&mut self, _other: &Self) {} fn __ifloordiv__(&mut self, _other: &Self) {} fn __imod__(&mut self, _other: &Self) {} fn __ipow__(&mut self, _other: &Self, modulo: ::std::option::Option<i32>) {} fn __ilshift__(&mut self, other: &Self) {} fn __irshift__(&mut self, other: &Self) {} fn __iand__(&mut self, other: &Self) {} fn __ixor__(&mut self, other: &Self) {} fn __ior__(&mut self, other: &Self) {} fn __neg__(slf: crate::pycell::PyRef<'_, Self>) -> crate::pycell::PyRef<'_, Self> { slf } fn __pos__(slf: crate::pycell::PyRef<'_, Self>) -> crate::pycell::PyRef<'_, Self> { slf } fn __abs__(slf: crate::pycell::PyRef<'_, Self>) -> crate::pycell::PyRef<'_, Self> { slf } fn __invert__(slf: crate::pycell::PyRef<'_, Self>) -> crate::pycell::PyRef<'_, Self> { slf } fn __complex__<'py>( &self, py: crate::Python<'py>, ) -> crate::Bound<'py, crate::types::PyComplex> { crate::types::PyComplex::from_doubles(py, 0.0, 0.0) } fn __int__(&self) -> u32 { 0 } fn __float__(&self) -> f64 { 0.0 } fn __index__(&self) -> u32 { 0 } #[pyo3(signature=(ndigits=::std::option::Option::None))] fn __round__(&self, ndigits: ::std::option::Option<u32>) -> u32 { 0 } fn __trunc__(&self) -> u32 { 0 } fn __floor__(&self) -> u32 { 0 } fn __ceil__(&self) -> u32 { 0 } ////////////////////// // With Statement Context Managers ////////////////////// fn __enter__(&mut self) {} fn __exit__( &mut self, exc_type: &crate::Bound<'_, crate::PyAny>, exc_value: &crate::Bound<'_, crate::PyAny>, traceback: &crate::Bound<'_, crate::PyAny>, ) { } ////////////////////// // Awaitable Objects ////////////////////// fn __await__(slf: crate::pycell::PyRef<'_, Self>) -> crate::pycell::PyRef<'_, Self> { slf } ////////////////////// // Asynchronous Iterators ////////////////////// fn __aiter__( slf: crate::pycell::PyRef<'_, Self>, py: crate::Python<'_>, ) -> crate::Py<DummyIter> { crate::Py::new(py, DummyIter {}).unwrap() } fn __anext__(&mut self) -> ::std::option::Option<()> { ::std::option::Option::None } ////////////////////// // Asynchronous Context Managers ////////////////////// fn __aenter__(&mut self) {} fn __aexit__( &mut self, exc_type: &crate::Bound<'_, crate::PyAny>, exc_value: &crate::Bound<'_, crate::PyAny>, traceback: &crate::Bound<'_, crate::PyAny>, ) { } // Things with attributes #[pyo3(signature = (_y, *, _z=2))] fn test(&self, _y: &Dummy, _z: i32) {} #[staticmethod] fn staticmethod() {} #[classmethod] fn clsmethod(_: &crate::Bound<'_, crate::types::PyType>) {} #[pyo3(signature = (*_args, **_kwds))] fn __call__( &self, _args: &crate::Bound<'_, crate::types::PyTuple>, _kwds: ::std::option::Option<&crate::Bound<'_, crate::types::PyDict>>, ) -> crate::PyResult<i32> { ::std::unimplemented!() } #[new] fn new(a: u8) -> Self { Dummy {} } #[getter] fn get(&self) -> i32 { 0 } #[setter] fn set(&mut self, _v: i32) {} #[classattr] fn class_attr() -> i32 { 0 } // Dunder methods invented for protocols // PyGcProtocol // Buffer protocol? } #[crate::pyclass(crate = "crate")] struct Clear; #[crate::pymethods(crate = "crate")] impl Clear { pub fn __traverse__( &self, visit: crate::PyVisit<'_>, ) -> ::std::result::Result<(), crate::PyTraverseError> { ::std::result::Result::Ok(()) } pub fn __clear__(&self) {} #[pyo3(signature=(*, reuse=false))] pub fn clear(&self, reuse: bool) {} } // Ensure that crate argument is also accepted inline #[crate::pyclass(crate = "crate")] struct Dummy2; #[crate::pymethods(crate = "crate")] impl Dummy2 { #[classmethod] fn __len__(cls: &crate::Bound<'_, crate::types::PyType>) -> crate::PyResult<usize> { ::std::result::Result::Ok(0) } #[staticmethod] fn __repr__() -> &'static str { "Dummy" } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests
lc_public_repos/langsmith-sdk/vendor/pyo3/src/tests/hygiene/mod.rs
#![no_implicit_prelude] #![allow(dead_code, unused_variables, clippy::unnecessary_wraps)] // The modules in this test are used to check PyO3 macro expansion is hygienic. By locating the test // inside the crate the global `::pyo3` namespace is not available, so in combination with // #[pyo3(crate = "crate")] this validates that all macro expansion respects the setting. mod misc; mod pyclass; mod pyfunction; mod pymethods; mod pymodule;
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pyclass/gc.rs
use std::{ marker::PhantomData, os::raw::{c_int, c_void}, }; use crate::{ffi, AsPyPointer}; /// Error returned by a `__traverse__` visitor implementation. #[repr(transparent)] pub struct PyTraverseError(NonZeroCInt); impl PyTraverseError { /// Returns the error code. pub(crate) fn into_inner(self) -> c_int { self.0.into() } } /// Object visitor for GC. #[derive(Clone)] pub struct PyVisit<'a> { pub(crate) visit: ffi::visitproc, pub(crate) arg: *mut c_void, /// Prevents the `PyVisit` from outliving the `__traverse__` call. pub(crate) _guard: PhantomData<&'a ()>, } impl PyVisit<'_> { /// Visit `obj`. pub fn call<T>(&self, obj: &T) -> Result<(), PyTraverseError> where T: AsPyPointer, { let ptr = obj.as_ptr(); if !ptr.is_null() { match NonZeroCInt::new(unsafe { (self.visit)(ptr, self.arg) }) { None => Ok(()), Some(r) => Err(PyTraverseError(r)), } } else { Ok(()) } } } /// Workaround for `NonZero<c_int>` not being available until MSRV 1.79 mod get_nonzero_c_int { pub struct GetNonZeroCInt<const WIDTH: usize>(); pub trait NonZeroCIntType { type Type; } impl NonZeroCIntType for GetNonZeroCInt<16> { type Type = std::num::NonZeroI16; } impl NonZeroCIntType for GetNonZeroCInt<32> { type Type = std::num::NonZeroI32; } pub type Type = <GetNonZeroCInt<{ std::mem::size_of::<std::os::raw::c_int>() * 8 }> as NonZeroCIntType>::Type; } use get_nonzero_c_int::Type as NonZeroCInt; #[cfg(test)] mod tests { use super::PyVisit; use static_assertions::assert_not_impl_any; #[test] fn py_visit_not_send_sync() { assert_not_impl_any!(PyVisit<'_>: Send, Sync); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/pyclass/create_type_object.rs
use crate::{ exceptions::PyTypeError, ffi, impl_::{ pycell::PyClassObject, pyclass::{ assign_sequence_item_from_mapping, get_sequence_item_from_mapping, tp_dealloc, tp_dealloc_with_gc, MaybeRuntimePyMethodDef, PyClassItemsIter, }, pymethods::{Getter, PyGetterDef, PyMethodDefType, PySetterDef, Setter, _call_clear}, trampoline::trampoline, }, internal_tricks::ptr_from_ref, types::{typeobject::PyTypeMethods, PyType}, Py, PyClass, PyResult, PyTypeInfo, Python, }; use std::{ collections::HashMap, ffi::{CStr, CString}, os::raw::{c_char, c_int, c_ulong, c_void}, ptr, }; pub(crate) struct PyClassTypeObject { pub type_object: Py<PyType>, #[allow(dead_code)] // This is purely a cache that must live as long as the type object getset_destructors: Vec<GetSetDefDestructor>, } pub(crate) fn create_type_object<T>(py: Python<'_>) -> PyResult<PyClassTypeObject> where T: PyClass, { // Written this way to monomorphize the majority of the logic. #[allow(clippy::too_many_arguments)] unsafe fn inner( py: Python<'_>, base: *mut ffi::PyTypeObject, dealloc: unsafe extern "C" fn(*mut ffi::PyObject), dealloc_with_gc: unsafe extern "C" fn(*mut ffi::PyObject), is_mapping: bool, is_sequence: bool, doc: &'static CStr, dict_offset: Option<ffi::Py_ssize_t>, weaklist_offset: Option<ffi::Py_ssize_t>, is_basetype: bool, items_iter: PyClassItemsIter, name: &'static str, module: Option<&'static str>, size_of: usize, ) -> PyResult<PyClassTypeObject> { PyTypeBuilder { slots: Vec::new(), method_defs: Vec::new(), member_defs: Vec::new(), getset_builders: HashMap::new(), cleanup: Vec::new(), tp_base: base, tp_dealloc: dealloc, tp_dealloc_with_gc: dealloc_with_gc, is_mapping, is_sequence, has_new: false, has_dealloc: false, has_getitem: false, has_setitem: false, has_traverse: false, has_clear: false, dict_offset: None, class_flags: 0, #[cfg(all(not(Py_3_9), not(Py_LIMITED_API)))] buffer_procs: Default::default(), } .type_doc(doc) .offsets(dict_offset, weaklist_offset) .set_is_basetype(is_basetype) .class_items(items_iter) .build(py, name, module, size_of) } unsafe { inner( py, T::BaseType::type_object_raw(py), tp_dealloc::<T>, tp_dealloc_with_gc::<T>, T::IS_MAPPING, T::IS_SEQUENCE, T::doc(py)?, T::dict_offset(), T::weaklist_offset(), T::IS_BASETYPE, T::items_iter(), T::NAME, T::MODULE, std::mem::size_of::<PyClassObject<T>>(), ) } } type PyTypeBuilderCleanup = Box<dyn Fn(&PyTypeBuilder, *mut ffi::PyTypeObject)>; struct PyTypeBuilder { slots: Vec<ffi::PyType_Slot>, method_defs: Vec<ffi::PyMethodDef>, member_defs: Vec<ffi::PyMemberDef>, getset_builders: HashMap<&'static CStr, GetSetDefBuilder>, /// Used to patch the type objects for the things there's no /// PyType_FromSpec API for... there's no reason this should work, /// except for that it does and we have tests. cleanup: Vec<PyTypeBuilderCleanup>, tp_base: *mut ffi::PyTypeObject, tp_dealloc: ffi::destructor, tp_dealloc_with_gc: ffi::destructor, is_mapping: bool, is_sequence: bool, has_new: bool, has_dealloc: bool, has_getitem: bool, has_setitem: bool, has_traverse: bool, has_clear: bool, dict_offset: Option<ffi::Py_ssize_t>, class_flags: c_ulong, // Before Python 3.9, need to patch in buffer methods manually (they don't work in slots) #[cfg(all(not(Py_3_9), not(Py_LIMITED_API)))] buffer_procs: ffi::PyBufferProcs, } impl PyTypeBuilder { /// # Safety /// The given pointer must be of the correct type for the given slot unsafe fn push_slot<T>(&mut self, slot: c_int, pfunc: *mut T) { match slot { ffi::Py_tp_new => self.has_new = true, ffi::Py_tp_dealloc => self.has_dealloc = true, ffi::Py_mp_subscript => self.has_getitem = true, ffi::Py_mp_ass_subscript => self.has_setitem = true, ffi::Py_tp_traverse => { self.has_traverse = true; self.class_flags |= ffi::Py_TPFLAGS_HAVE_GC; } ffi::Py_tp_clear => self.has_clear = true, #[cfg(all(not(Py_3_9), not(Py_LIMITED_API)))] ffi::Py_bf_getbuffer => { // Safety: slot.pfunc is a valid function pointer self.buffer_procs.bf_getbuffer = Some(std::mem::transmute::<*mut T, ffi::getbufferproc>(pfunc)); } #[cfg(all(not(Py_3_9), not(Py_LIMITED_API)))] ffi::Py_bf_releasebuffer => { // Safety: slot.pfunc is a valid function pointer self.buffer_procs.bf_releasebuffer = Some(std::mem::transmute::<*mut T, ffi::releasebufferproc>(pfunc)); } _ => {} } self.slots.push(ffi::PyType_Slot { slot, pfunc: pfunc as _, }); } /// # Safety /// It is the caller's responsibility that `data` is of the correct type for the given slot. unsafe fn push_raw_vec_slot<T>(&mut self, slot: c_int, mut data: Vec<T>) { if !data.is_empty() { // Python expects a zeroed entry to mark the end of the defs data.push(std::mem::zeroed()); self.push_slot(slot, Box::into_raw(data.into_boxed_slice()) as *mut c_void); } } fn pymethod_def(&mut self, def: &PyMethodDefType) { match def { PyMethodDefType::Getter(getter) => self .getset_builders .entry(getter.name) .or_default() .add_getter(getter), PyMethodDefType::Setter(setter) => self .getset_builders .entry(setter.name) .or_default() .add_setter(setter), PyMethodDefType::Method(def) | PyMethodDefType::Class(def) | PyMethodDefType::Static(def) => self.method_defs.push(def.as_method_def()), // These class attributes are added after the type gets created by LazyStaticType PyMethodDefType::ClassAttribute(_) => {} PyMethodDefType::StructMember(def) => self.member_defs.push(*def), } } fn finalize_methods_and_properties(&mut self) -> Vec<GetSetDefDestructor> { let method_defs: Vec<pyo3_ffi::PyMethodDef> = std::mem::take(&mut self.method_defs); // Safety: Py_tp_methods expects a raw vec of PyMethodDef unsafe { self.push_raw_vec_slot(ffi::Py_tp_methods, method_defs) }; let member_defs = std::mem::take(&mut self.member_defs); // Safety: Py_tp_members expects a raw vec of PyMemberDef unsafe { self.push_raw_vec_slot(ffi::Py_tp_members, member_defs) }; let mut getset_destructors = Vec::with_capacity(self.getset_builders.len()); #[allow(unused_mut)] let mut property_defs: Vec<_> = self .getset_builders .iter() .map(|(name, builder)| { let (def, destructor) = builder.as_get_set_def(name); getset_destructors.push(destructor); def }) .collect(); // PyPy automatically adds __dict__ getter / setter. #[cfg(not(PyPy))] // Supported on unlimited API for all versions, and on 3.9+ for limited API #[cfg(any(Py_3_9, not(Py_LIMITED_API)))] if let Some(dict_offset) = self.dict_offset { let get_dict; let closure; // PyObject_GenericGetDict not in the limited API until Python 3.10. #[cfg(any(not(Py_LIMITED_API), Py_3_10))] { let _ = dict_offset; get_dict = ffi::PyObject_GenericGetDict; closure = ptr::null_mut(); } // ... so we write a basic implementation ourselves #[cfg(not(any(not(Py_LIMITED_API), Py_3_10)))] { extern "C" fn get_dict_impl( object: *mut ffi::PyObject, closure: *mut c_void, ) -> *mut ffi::PyObject { unsafe { trampoline(|_| { let dict_offset = closure as ffi::Py_ssize_t; // we don't support negative dict_offset here; PyO3 doesn't set it negative assert!(dict_offset > 0); // TODO: use `.byte_offset` on MSRV 1.75 let dict_ptr = object .cast::<u8>() .offset(dict_offset) .cast::<*mut ffi::PyObject>(); if (*dict_ptr).is_null() { std::ptr::write(dict_ptr, ffi::PyDict_New()); } Ok(ffi::compat::Py_XNewRef(*dict_ptr)) }) } } get_dict = get_dict_impl; closure = dict_offset as _; } property_defs.push(ffi::PyGetSetDef { name: ffi::c_str!("__dict__").as_ptr(), get: Some(get_dict), set: Some(ffi::PyObject_GenericSetDict), doc: ptr::null(), closure, }); } // Safety: Py_tp_getset expects a raw vec of PyGetSetDef unsafe { self.push_raw_vec_slot(ffi::Py_tp_getset, property_defs) }; // If mapping methods implemented, define sequence methods get implemented too. // CPython does the same for Python `class` statements. // NB we don't implement sq_length to avoid annoying CPython behaviour of automatically adding // the length to negative indices. // Don't add these methods for "pure" mappings. if !self.is_mapping && self.has_getitem { // Safety: This is the correct slot type for Py_sq_item unsafe { self.push_slot( ffi::Py_sq_item, get_sequence_item_from_mapping as *mut c_void, ) } } if !self.is_mapping && self.has_setitem { // Safety: This is the correct slot type for Py_sq_ass_item unsafe { self.push_slot( ffi::Py_sq_ass_item, assign_sequence_item_from_mapping as *mut c_void, ) } } getset_destructors } fn set_is_basetype(mut self, is_basetype: bool) -> Self { if is_basetype { self.class_flags |= ffi::Py_TPFLAGS_BASETYPE; } self } /// # Safety /// All slots in the PyClassItemsIter should be correct unsafe fn class_items(mut self, iter: PyClassItemsIter) -> Self { for items in iter { for slot in items.slots { self.push_slot(slot.slot, slot.pfunc); } for method in items.methods { let built_method; let method = match method { MaybeRuntimePyMethodDef::Runtime(builder) => { built_method = builder(); &built_method } MaybeRuntimePyMethodDef::Static(method) => method, }; self.pymethod_def(method); } } self } fn type_doc(mut self, type_doc: &'static CStr) -> Self { let slice = type_doc.to_bytes(); if !slice.is_empty() { unsafe { self.push_slot(ffi::Py_tp_doc, type_doc.as_ptr() as *mut c_char) } // Running this causes PyPy to segfault. #[cfg(all(not(PyPy), not(Py_LIMITED_API), not(Py_3_10)))] { // Until CPython 3.10, tp_doc was treated specially for // heap-types, and it removed the text_signature value from it. // We go in after the fact and replace tp_doc with something // that _does_ include the text_signature value! self.cleanup .push(Box::new(move |_self, type_object| unsafe { ffi::PyObject_Free((*type_object).tp_doc as _); let data = ffi::PyMem_Malloc(slice.len()); data.copy_from(slice.as_ptr() as _, slice.len()); (*type_object).tp_doc = data as _; })) } } self } fn offsets( mut self, dict_offset: Option<ffi::Py_ssize_t>, #[allow(unused_variables)] weaklist_offset: Option<ffi::Py_ssize_t>, ) -> Self { self.dict_offset = dict_offset; #[cfg(Py_3_9)] { #[inline(always)] fn offset_def(name: &'static CStr, offset: ffi::Py_ssize_t) -> ffi::PyMemberDef { ffi::PyMemberDef { name: name.as_ptr().cast(), type_code: ffi::Py_T_PYSSIZET, offset, flags: ffi::Py_READONLY, doc: std::ptr::null_mut(), } } // __dict__ support if let Some(dict_offset) = dict_offset { self.member_defs .push(offset_def(ffi::c_str!("__dictoffset__"), dict_offset)); } // weakref support if let Some(weaklist_offset) = weaklist_offset { self.member_defs.push(offset_def( ffi::c_str!("__weaklistoffset__"), weaklist_offset, )); } } // Setting buffer protocols, tp_dictoffset and tp_weaklistoffset via slots doesn't work until // Python 3.9, so on older versions we must manually fixup the type object. #[cfg(all(not(Py_LIMITED_API), not(Py_3_9)))] { self.cleanup .push(Box::new(move |builder, type_object| unsafe { (*(*type_object).tp_as_buffer).bf_getbuffer = builder.buffer_procs.bf_getbuffer; (*(*type_object).tp_as_buffer).bf_releasebuffer = builder.buffer_procs.bf_releasebuffer; if let Some(dict_offset) = dict_offset { (*type_object).tp_dictoffset = dict_offset; } if let Some(weaklist_offset) = weaklist_offset { (*type_object).tp_weaklistoffset = weaklist_offset; } })); } self } fn build( mut self, py: Python<'_>, name: &'static str, module_name: Option<&'static str>, basicsize: usize, ) -> PyResult<PyClassTypeObject> { // `c_ulong` and `c_uint` have the same size // on some platforms (like windows) #![allow(clippy::useless_conversion)] let getset_destructors = self.finalize_methods_and_properties(); unsafe { self.push_slot(ffi::Py_tp_base, self.tp_base) } if !self.has_new { // Safety: This is the correct slot type for Py_tp_new unsafe { self.push_slot(ffi::Py_tp_new, no_constructor_defined as *mut c_void) } } let base_is_gc = unsafe { ffi::PyType_IS_GC(self.tp_base) == 1 }; let tp_dealloc = if self.has_traverse || base_is_gc { self.tp_dealloc_with_gc } else { self.tp_dealloc }; unsafe { self.push_slot(ffi::Py_tp_dealloc, tp_dealloc as *mut c_void) } if self.has_clear && !self.has_traverse { return Err(PyTypeError::new_err(format!( "`#[pyclass]` {} implements __clear__ without __traverse__", name ))); } // If this type is a GC type, and the base also is, we may need to add // `tp_traverse` / `tp_clear` implementations to call the base, if this type didn't // define `__traverse__` or `__clear__`. // // This is because when Py_TPFLAGS_HAVE_GC is set, then `tp_traverse` and // `tp_clear` are not inherited. if ((self.class_flags & ffi::Py_TPFLAGS_HAVE_GC) != 0) && base_is_gc { // If this assertion breaks, need to consider doing the same for __traverse__. assert!(self.has_traverse); // Py_TPFLAGS_HAVE_GC is set when a `__traverse__` method is found if !self.has_clear { // Safety: This is the correct slot type for Py_tp_clear unsafe { self.push_slot(ffi::Py_tp_clear, call_super_clear as *mut c_void) } } } // For sequences, implement sq_length instead of mp_length if self.is_sequence { for slot in &mut self.slots { if slot.slot == ffi::Py_mp_length { slot.slot = ffi::Py_sq_length; } } } // Add empty sentinel at the end // Safety: python expects this empty slot unsafe { self.push_slot(0, ptr::null_mut::<c_void>()) } let class_name = py_class_qualified_name(module_name, name)?; let mut spec = ffi::PyType_Spec { name: class_name.as_ptr() as _, basicsize: basicsize as c_int, itemsize: 0, flags: (ffi::Py_TPFLAGS_DEFAULT | self.class_flags) .try_into() .unwrap(), slots: self.slots.as_mut_ptr(), }; // Safety: We've correctly setup the PyType_Spec at this point let type_object: Py<PyType> = unsafe { Py::from_owned_ptr_or_err(py, ffi::PyType_FromSpec(&mut spec))? }; #[cfg(not(Py_3_11))] bpo_45315_workaround(py, class_name); for cleanup in std::mem::take(&mut self.cleanup) { cleanup(&self, type_object.bind(py).as_type_ptr()); } Ok(PyClassTypeObject { type_object, getset_destructors, }) } } fn py_class_qualified_name(module_name: Option<&str>, class_name: &str) -> PyResult<CString> { Ok(CString::new(format!( "{}.{}", module_name.unwrap_or("builtins"), class_name ))?) } /// Workaround for Python issue 45315; no longer necessary in Python 3.11 #[inline] #[cfg(not(Py_3_11))] fn bpo_45315_workaround(py: Python<'_>, class_name: CString) { #[cfg(Py_LIMITED_API)] { // Must check version at runtime for abi3 wheels - they could run against a higher version // than the build config suggests. use crate::sync::GILOnceCell; static IS_PYTHON_3_11: GILOnceCell<bool> = GILOnceCell::new(); if *IS_PYTHON_3_11.get_or_init(py, || py.version_info() >= (3, 11)) { // No fix needed - the wheel is running on a sufficiently new interpreter. return; } } #[cfg(not(Py_LIMITED_API))] { // suppress unused variable warning let _ = py; } std::mem::forget(class_name); } /// Default new implementation unsafe extern "C" fn no_constructor_defined( subtype: *mut ffi::PyTypeObject, _args: *mut ffi::PyObject, _kwds: *mut ffi::PyObject, ) -> *mut ffi::PyObject { trampoline(|py| { let tpobj = PyType::from_borrowed_type_ptr(py, subtype); let name = tpobj .name() .map_or_else(|_| "<unknown>".into(), |name| name.to_string()); Err(crate::exceptions::PyTypeError::new_err(format!( "No constructor defined for {}", name ))) }) } unsafe extern "C" fn call_super_clear(slf: *mut ffi::PyObject) -> c_int { _call_clear(slf, |_, _| Ok(()), call_super_clear) } #[derive(Default)] struct GetSetDefBuilder { doc: Option<&'static CStr>, getter: Option<Getter>, setter: Option<Setter>, } impl GetSetDefBuilder { fn add_getter(&mut self, getter: &PyGetterDef) { // TODO: be smarter about merging getter and setter docs if self.doc.is_none() { self.doc = Some(getter.doc); } // TODO: return an error if getter already defined? self.getter = Some(getter.meth) } fn add_setter(&mut self, setter: &PySetterDef) { // TODO: be smarter about merging getter and setter docs if self.doc.is_none() { self.doc = Some(setter.doc); } // TODO: return an error if setter already defined? self.setter = Some(setter.meth) } fn as_get_set_def(&self, name: &'static CStr) -> (ffi::PyGetSetDef, GetSetDefDestructor) { let getset_type = match (self.getter, self.setter) { (Some(getter), None) => GetSetDefType::Getter(getter), (None, Some(setter)) => GetSetDefType::Setter(setter), (Some(getter), Some(setter)) => { GetSetDefType::GetterAndSetter(Box::new(GetterAndSetter { getter, setter })) } (None, None) => { unreachable!("GetSetDefBuilder expected to always have either getter or setter") } }; let getset_def = getset_type.create_py_get_set_def(name, self.doc); let destructor = GetSetDefDestructor { closure: getset_type, }; (getset_def, destructor) } } #[allow(dead_code)] // a stack of fields which are purely to cache until dropped struct GetSetDefDestructor { closure: GetSetDefType, } /// Possible forms of property - either a getter, setter, or both enum GetSetDefType { Getter(Getter), Setter(Setter), // The box is here so that the `GetterAndSetter` has a stable // memory address even if the `GetSetDefType` enum is moved GetterAndSetter(Box<GetterAndSetter>), } pub(crate) struct GetterAndSetter { getter: Getter, setter: Setter, } impl GetSetDefType { /// Fills a PyGetSetDef structure /// It is only valid for as long as this GetSetDefType remains alive, /// as well as name and doc members pub(crate) fn create_py_get_set_def( &self, name: &CStr, doc: Option<&CStr>, ) -> ffi::PyGetSetDef { let (get, set, closure): (Option<ffi::getter>, Option<ffi::setter>, *mut c_void) = match self { &Self::Getter(closure) => { unsafe extern "C" fn getter( slf: *mut ffi::PyObject, closure: *mut c_void, ) -> *mut ffi::PyObject { // Safety: PyO3 sets the closure when constructing the ffi getter so this cast should always be valid let getter: Getter = std::mem::transmute(closure); trampoline(|py| getter(py, slf)) } (Some(getter), None, closure as Getter as _) } &Self::Setter(closure) => { unsafe extern "C" fn setter( slf: *mut ffi::PyObject, value: *mut ffi::PyObject, closure: *mut c_void, ) -> c_int { // Safety: PyO3 sets the closure when constructing the ffi setter so this cast should always be valid let setter: Setter = std::mem::transmute(closure); trampoline(|py| setter(py, slf, value)) } (None, Some(setter), closure as Setter as _) } Self::GetterAndSetter(closure) => { unsafe extern "C" fn getset_getter( slf: *mut ffi::PyObject, closure: *mut c_void, ) -> *mut ffi::PyObject { let getset: &GetterAndSetter = &*closure.cast(); trampoline(|py| (getset.getter)(py, slf)) } unsafe extern "C" fn getset_setter( slf: *mut ffi::PyObject, value: *mut ffi::PyObject, closure: *mut c_void, ) -> c_int { let getset: &GetterAndSetter = &*closure.cast(); trampoline(|py| (getset.setter)(py, slf, value)) } ( Some(getset_getter), Some(getset_setter), ptr_from_ref::<GetterAndSetter>(closure) as *mut _, ) } }; ffi::PyGetSetDef { name: name.as_ptr(), doc: doc.map_or(ptr::null(), CStr::as_ptr), get, set, closure, } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pycell.rs
//! Externally-accessible implementation of pycell pub use crate::pycell::impl_::{ GetBorrowChecker, PyClassMutability, PyClassObject, PyClassObjectBase, PyClassObjectLayout, };
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/wrap.rs
use std::{convert::Infallible, marker::PhantomData, ops::Deref}; #[allow(deprecated)] use crate::IntoPy; use crate::{ conversion::IntoPyObject, ffi, types::PyNone, Bound, BoundObject, PyObject, PyResult, Python, }; /// Used to wrap values in `Option<T>` for default arguments. pub trait SomeWrap<T> { fn wrap(self) -> Option<T>; } impl<T> SomeWrap<T> for T { fn wrap(self) -> Option<T> { Some(self) } } impl<T> SomeWrap<T> for Option<T> { fn wrap(self) -> Self { self } } // Hierarchy of conversions used in the `IntoPy` implementation pub struct Converter<T>(EmptyTupleConverter<T>); pub struct EmptyTupleConverter<T>(IntoPyObjectConverter<T>); pub struct IntoPyObjectConverter<T>(IntoPyConverter<T>); pub struct IntoPyConverter<T>(UnknownReturnResultType<T>); pub struct UnknownReturnResultType<T>(UnknownReturnType<T>); pub struct UnknownReturnType<T>(PhantomData<T>); pub fn converter<T>(_: &T) -> Converter<T> { Converter(EmptyTupleConverter(IntoPyObjectConverter(IntoPyConverter( UnknownReturnResultType(UnknownReturnType(PhantomData)), )))) } impl<T> Deref for Converter<T> { type Target = EmptyTupleConverter<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> Deref for EmptyTupleConverter<T> { type Target = IntoPyObjectConverter<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> Deref for IntoPyObjectConverter<T> { type Target = IntoPyConverter<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> Deref for IntoPyConverter<T> { type Target = UnknownReturnResultType<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> Deref for UnknownReturnResultType<T> { type Target = UnknownReturnType<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl EmptyTupleConverter<PyResult<()>> { #[inline] pub fn map_into_ptr(&self, py: Python<'_>, obj: PyResult<()>) -> PyResult<*mut ffi::PyObject> { obj.map(|_| PyNone::get(py).to_owned().into_ptr()) } } impl<'py, T: IntoPyObject<'py>> IntoPyObjectConverter<T> { #[inline] pub fn wrap(&self, obj: T) -> Result<T, Infallible> { Ok(obj) } } impl<'py, T: IntoPyObject<'py>, E> IntoPyObjectConverter<Result<T, E>> { #[inline] pub fn wrap(&self, obj: Result<T, E>) -> Result<T, E> { obj } #[inline] pub fn map_into_pyobject(&self, py: Python<'py>, obj: PyResult<T>) -> PyResult<PyObject> where T: IntoPyObject<'py>, { obj.and_then(|obj| obj.into_pyobject(py).map_err(Into::into)) .map(BoundObject::into_any) .map(BoundObject::unbind) } #[inline] pub fn map_into_ptr(&self, py: Python<'py>, obj: PyResult<T>) -> PyResult<*mut ffi::PyObject> where T: IntoPyObject<'py>, { obj.and_then(|obj| obj.into_pyobject(py).map_err(Into::into)) .map(BoundObject::into_bound) .map(Bound::into_ptr) } } #[allow(deprecated)] impl<T: IntoPy<PyObject>> IntoPyConverter<T> { #[inline] pub fn wrap(&self, obj: T) -> Result<T, Infallible> { Ok(obj) } } #[allow(deprecated)] impl<T: IntoPy<PyObject>, E> IntoPyConverter<Result<T, E>> { #[inline] pub fn wrap(&self, obj: Result<T, E>) -> Result<T, E> { obj } #[inline] pub fn map_into_pyobject(&self, py: Python<'_>, obj: PyResult<T>) -> PyResult<PyObject> { obj.map(|obj| obj.into_py(py)) } #[inline] pub fn map_into_ptr(&self, py: Python<'_>, obj: PyResult<T>) -> PyResult<*mut ffi::PyObject> { obj.map(|obj| obj.into_py(py).into_ptr()) } } impl<T, E> UnknownReturnResultType<Result<T, E>> { #[inline] pub fn wrap<'py>(&self, _: Result<T, E>) -> Result<T, E> where T: IntoPyObject<'py>, { unreachable!("should be handled by IntoPyObjectConverter") } } impl<T> UnknownReturnType<T> { #[inline] pub fn wrap<'py>(&self, _: T) -> T where T: IntoPyObject<'py>, { unreachable!("should be handled by IntoPyObjectConverter") } #[inline] pub fn map_into_pyobject<'py>(&self, _: Python<'py>, _: PyResult<T>) -> PyResult<PyObject> where T: IntoPyObject<'py>, { unreachable!("should be handled by IntoPyObjectConverter") } #[inline] pub fn map_into_ptr<'py>(&self, _: Python<'py>, _: PyResult<T>) -> PyResult<*mut ffi::PyObject> where T: IntoPyObject<'py>, { unreachable!("should be handled by IntoPyObjectConverter") } } #[cfg(test)] mod tests { use super::*; #[test] fn wrap_option() { let a: Option<u8> = SomeWrap::wrap(42); assert_eq!(a, Some(42)); let b: Option<u8> = SomeWrap::wrap(None); assert_eq!(b, None); } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/pyclass.rs
use crate::{ conversion::IntoPyObject, exceptions::{PyAttributeError, PyNotImplementedError, PyRuntimeError, PyValueError}, ffi, impl_::{ freelist::FreeList, pycell::{GetBorrowChecker, PyClassMutability, PyClassObjectLayout}, pyclass_init::PyObjectInit, pymethods::{PyGetterDef, PyMethodDefType}, }, pycell::PyBorrowError, types::{any::PyAnyMethods, PyBool}, Borrowed, BoundObject, Py, PyAny, PyClass, PyErr, PyRef, PyResult, PyTypeInfo, Python, }; #[allow(deprecated)] use crate::{IntoPy, ToPyObject}; use std::{ borrow::Cow, ffi::{CStr, CString}, marker::PhantomData, os::raw::{c_int, c_void}, ptr::NonNull, thread, }; mod assertions; mod lazy_type_object; mod probes; pub use assertions::*; pub use lazy_type_object::LazyTypeObject; pub use probes::*; /// Gets the offset of the dictionary from the start of the object in bytes. #[inline] pub fn dict_offset<T: PyClass>() -> ffi::Py_ssize_t { PyClassObject::<T>::dict_offset() } /// Gets the offset of the weakref list from the start of the object in bytes. #[inline] pub fn weaklist_offset<T: PyClass>() -> ffi::Py_ssize_t { PyClassObject::<T>::weaklist_offset() } /// Represents the `__dict__` field for `#[pyclass]`. pub trait PyClassDict { /// Initial form of a [PyObject](crate::ffi::PyObject) `__dict__` reference. const INIT: Self; /// Empties the dictionary of its key-value pairs. #[inline] fn clear_dict(&mut self, _py: Python<'_>) {} private_decl! {} } /// Represents the `__weakref__` field for `#[pyclass]`. pub trait PyClassWeakRef { /// Initializes a `weakref` instance. const INIT: Self; /// Clears the weak references to the given object. /// /// # Safety /// - `_obj` must be a pointer to the pyclass instance which contains `self`. /// - The GIL must be held. #[inline] unsafe fn clear_weakrefs(&mut self, _obj: *mut ffi::PyObject, _py: Python<'_>) {} private_decl! {} } /// Zero-sized dummy field. pub struct PyClassDummySlot; impl PyClassDict for PyClassDummySlot { private_impl! {} const INIT: Self = PyClassDummySlot; } impl PyClassWeakRef for PyClassDummySlot { private_impl! {} const INIT: Self = PyClassDummySlot; } /// Actual dict field, which holds the pointer to `__dict__`. /// /// `#[pyclass(dict)]` automatically adds this. #[repr(transparent)] #[allow(dead_code)] // These are constructed in INIT and used by the macro code pub struct PyClassDictSlot(*mut ffi::PyObject); impl PyClassDict for PyClassDictSlot { private_impl! {} const INIT: Self = Self(std::ptr::null_mut()); #[inline] fn clear_dict(&mut self, _py: Python<'_>) { if !self.0.is_null() { unsafe { ffi::PyDict_Clear(self.0) } } } } /// Actual weakref field, which holds the pointer to `__weakref__`. /// /// `#[pyclass(weakref)]` automatically adds this. #[repr(transparent)] #[allow(dead_code)] // These are constructed in INIT and used by the macro code pub struct PyClassWeakRefSlot(*mut ffi::PyObject); impl PyClassWeakRef for PyClassWeakRefSlot { private_impl! {} const INIT: Self = Self(std::ptr::null_mut()); #[inline] unsafe fn clear_weakrefs(&mut self, obj: *mut ffi::PyObject, _py: Python<'_>) { if !self.0.is_null() { ffi::PyObject_ClearWeakRefs(obj) } } } /// This type is used as a "dummy" type on which dtolnay specializations are /// applied to apply implementations from `#[pymethods]` pub struct PyClassImplCollector<T>(PhantomData<T>); impl<T> PyClassImplCollector<T> { pub fn new() -> Self { Self(PhantomData) } } impl<T> Default for PyClassImplCollector<T> { fn default() -> Self { Self::new() } } impl<T> Clone for PyClassImplCollector<T> { fn clone(&self) -> Self { *self } } impl<T> Copy for PyClassImplCollector<T> {} pub enum MaybeRuntimePyMethodDef { /// Used in cases where const functionality is not sufficient to define the method /// purely at compile time. Runtime(fn() -> PyMethodDefType), Static(PyMethodDefType), } pub struct PyClassItems { pub methods: &'static [MaybeRuntimePyMethodDef], pub slots: &'static [ffi::PyType_Slot], } // Allow PyClassItems in statics unsafe impl Sync for PyClassItems {} /// Implements the underlying functionality of `#[pyclass]`, assembled by various proc macros. /// /// Users are discouraged from implementing this trait manually; it is a PyO3 implementation detail /// and may be changed at any time. pub trait PyClassImpl: Sized + 'static { /// #[pyclass(subclass)] const IS_BASETYPE: bool = false; /// #[pyclass(extends=...)] const IS_SUBCLASS: bool = false; /// #[pyclass(mapping)] const IS_MAPPING: bool = false; /// #[pyclass(sequence)] const IS_SEQUENCE: bool = false; /// Base class type BaseType: PyTypeInfo + PyClassBaseType; /// Immutable or mutable type PyClassMutability: PyClassMutability + GetBorrowChecker<Self>; /// Specify this class has `#[pyclass(dict)]` or not. type Dict: PyClassDict; /// Specify this class has `#[pyclass(weakref)]` or not. type WeakRef: PyClassWeakRef; /// The closest native ancestor. This is `PyAny` by default, and when you declare /// `#[pyclass(extends=PyDict)]`, it's `PyDict`. type BaseNativeType: PyTypeInfo; /// This handles following two situations: /// 1. In case `T` is `Send`, stub `ThreadChecker` is used and does nothing. /// This implementation is used by default. Compile fails if `T: !Send`. /// 2. In case `T` is `!Send`, `ThreadChecker` panics when `T` is accessed by another thread. /// This implementation is used when `#[pyclass(unsendable)]` is given. /// Panicking makes it safe to expose `T: !Send` to the Python interpreter, where all objects /// can be accessed by multiple threads by `threading` module. type ThreadChecker: PyClassThreadChecker<Self>; #[cfg(feature = "multiple-pymethods")] type Inventory: PyClassInventory; /// Rendered class doc fn doc(py: Python<'_>) -> PyResult<&'static CStr>; fn items_iter() -> PyClassItemsIter; #[inline] fn dict_offset() -> Option<ffi::Py_ssize_t> { None } #[inline] fn weaklist_offset() -> Option<ffi::Py_ssize_t> { None } fn lazy_type_object() -> &'static LazyTypeObject<Self>; } /// Runtime helper to build a class docstring from the `doc` and `text_signature`. /// /// This is done at runtime because the class text signature is collected via dtolnay /// specialization in to the `#[pyclass]` macro from the `#[pymethods]` macro. pub fn build_pyclass_doc( class_name: &'static str, doc: &'static CStr, text_signature: Option<&'static str>, ) -> PyResult<Cow<'static, CStr>> { if let Some(text_signature) = text_signature { let doc = CString::new(format!( "{}{}\n--\n\n{}", class_name, text_signature, doc.to_str().unwrap(), )) .map_err(|_| PyValueError::new_err("class doc cannot contain nul bytes"))?; Ok(Cow::Owned(doc)) } else { Ok(Cow::Borrowed(doc)) } } /// Iterator used to process all class items during type instantiation. pub struct PyClassItemsIter { /// Iteration state idx: usize, /// Items from the `#[pyclass]` macro pyclass_items: &'static PyClassItems, /// Items from the `#[pymethods]` macro #[cfg(not(feature = "multiple-pymethods"))] pymethods_items: &'static PyClassItems, /// Items from the `#[pymethods]` macro with inventory #[cfg(feature = "multiple-pymethods")] pymethods_items: Box<dyn Iterator<Item = &'static PyClassItems>>, } impl PyClassItemsIter { pub fn new( pyclass_items: &'static PyClassItems, #[cfg(not(feature = "multiple-pymethods"))] pymethods_items: &'static PyClassItems, #[cfg(feature = "multiple-pymethods")] pymethods_items: Box< dyn Iterator<Item = &'static PyClassItems>, >, ) -> Self { Self { idx: 0, pyclass_items, pymethods_items, } } } impl Iterator for PyClassItemsIter { type Item = &'static PyClassItems; #[cfg(not(feature = "multiple-pymethods"))] fn next(&mut self) -> Option<Self::Item> { match self.idx { 0 => { self.idx += 1; Some(self.pyclass_items) } 1 => { self.idx += 1; Some(self.pymethods_items) } // Termination clause _ => None, } } #[cfg(feature = "multiple-pymethods")] fn next(&mut self) -> Option<Self::Item> { match self.idx { 0 => { self.idx += 1; Some(self.pyclass_items) } // Termination clause _ => self.pymethods_items.next(), } } } // Traits describing known special methods. macro_rules! slot_fragment_trait { ($trait_name:ident, $($default_method:tt)*) => { #[allow(non_camel_case_types)] pub trait $trait_name<T>: Sized { $($default_method)* } impl<T> $trait_name<T> for &'_ PyClassImplCollector<T> {} } } slot_fragment_trait! { PyClass__getattribute__SlotFragment, /// # Safety: _slf and _attr must be valid non-null Python objects #[inline] unsafe fn __getattribute__( self, py: Python<'_>, slf: *mut ffi::PyObject, attr: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { let res = ffi::PyObject_GenericGetAttr(slf, attr); if res.is_null() { Err(PyErr::fetch(py)) } else { Ok(res) } } } slot_fragment_trait! { PyClass__getattr__SlotFragment, /// # Safety: _slf and _attr must be valid non-null Python objects #[inline] unsafe fn __getattr__( self, py: Python<'_>, _slf: *mut ffi::PyObject, attr: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Err(PyErr::new::<PyAttributeError, _>( (Py::<PyAny>::from_borrowed_ptr(py, attr),) )) } } #[doc(hidden)] #[macro_export] macro_rules! generate_pyclass_getattro_slot { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, attr: *mut $crate::ffi::PyObject, ) -> *mut $crate::ffi::PyObject { $crate::impl_::trampoline::getattrofunc(_slf, attr, |py, _slf, attr| { use ::std::result::Result::*; use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); // Strategy: // - Try __getattribute__ first. Its default is PyObject_GenericGetAttr. // - If it returns a result, use it. // - If it fails with AttributeError, try __getattr__. // - If it fails otherwise, reraise. match collector.__getattribute__(py, _slf, attr) { Ok(obj) => Ok(obj), Err(e) if e.is_instance_of::<$crate::exceptions::PyAttributeError>(py) => { collector.__getattr__(py, _slf, attr) } Err(e) => Err(e), } }) } $crate::ffi::PyType_Slot { slot: $crate::ffi::Py_tp_getattro, pfunc: __wrap as $crate::ffi::getattrofunc as _, } }}; } pub use generate_pyclass_getattro_slot; /// Macro which expands to three items /// - Trait for a __setitem__ dunder /// - Trait for the corresponding __delitem__ dunder /// - A macro which will use dtolnay specialisation to generate the shared slot for the two dunders macro_rules! define_pyclass_setattr_slot { ( $set_trait:ident, $del_trait:ident, $set:ident, $del:ident, $set_error:expr, $del_error:expr, $generate_macro:ident, $slot:ident, $func_ty:ident, ) => { slot_fragment_trait! { $set_trait, /// # Safety: _slf and _attr must be valid non-null Python objects #[inline] unsafe fn $set( self, _py: Python<'_>, _slf: *mut ffi::PyObject, _attr: *mut ffi::PyObject, _value: NonNull<ffi::PyObject>, ) -> PyResult<()> { $set_error } } slot_fragment_trait! { $del_trait, /// # Safety: _slf and _attr must be valid non-null Python objects #[inline] unsafe fn $del( self, _py: Python<'_>, _slf: *mut ffi::PyObject, _attr: *mut ffi::PyObject, ) -> PyResult<()> { $del_error } } #[doc(hidden)] #[macro_export] macro_rules! $generate_macro { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, attr: *mut $crate::ffi::PyObject, value: *mut $crate::ffi::PyObject, ) -> ::std::os::raw::c_int { $crate::impl_::trampoline::setattrofunc( _slf, attr, value, |py, _slf, attr, value| { use ::std::option::Option::*; use $crate::impl_::callback::IntoPyCallbackOutput; use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); if let Some(value) = ::std::ptr::NonNull::new(value) { collector.$set(py, _slf, attr, value).convert(py) } else { collector.$del(py, _slf, attr).convert(py) } }, ) } $crate::ffi::PyType_Slot { slot: $crate::ffi::$slot, pfunc: __wrap as $crate::ffi::$func_ty as _, } }}; } pub use $generate_macro; }; } define_pyclass_setattr_slot! { PyClass__setattr__SlotFragment, PyClass__delattr__SlotFragment, __setattr__, __delattr__, Err(PyAttributeError::new_err("can't set attribute")), Err(PyAttributeError::new_err("can't delete attribute")), generate_pyclass_setattr_slot, Py_tp_setattro, setattrofunc, } define_pyclass_setattr_slot! { PyClass__set__SlotFragment, PyClass__delete__SlotFragment, __set__, __delete__, Err(PyNotImplementedError::new_err("can't set descriptor")), Err(PyNotImplementedError::new_err("can't delete descriptor")), generate_pyclass_setdescr_slot, Py_tp_descr_set, descrsetfunc, } define_pyclass_setattr_slot! { PyClass__setitem__SlotFragment, PyClass__delitem__SlotFragment, __setitem__, __delitem__, Err(PyNotImplementedError::new_err("can't set item")), Err(PyNotImplementedError::new_err("can't delete item")), generate_pyclass_setitem_slot, Py_mp_ass_subscript, objobjargproc, } /// Macro which expands to three items /// - Trait for a lhs dunder e.g. __add__ /// - Trait for the corresponding rhs e.g. __radd__ /// - A macro which will use dtolnay specialisation to generate the shared slot for the two dunders macro_rules! define_pyclass_binary_operator_slot { ( $lhs_trait:ident, $rhs_trait:ident, $lhs:ident, $rhs:ident, $generate_macro:ident, $slot:ident, $func_ty:ident, ) => { slot_fragment_trait! { $lhs_trait, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn $lhs( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } slot_fragment_trait! { $rhs_trait, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn $rhs( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } #[doc(hidden)] #[macro_export] macro_rules! $generate_macro { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, _other: *mut $crate::ffi::PyObject, ) -> *mut $crate::ffi::PyObject { $crate::impl_::trampoline::binaryfunc(_slf, _other, |py, _slf, _other| { use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); let lhs_result = collector.$lhs(py, _slf, _other)?; if lhs_result == $crate::ffi::Py_NotImplemented() { $crate::ffi::Py_DECREF(lhs_result); collector.$rhs(py, _other, _slf) } else { ::std::result::Result::Ok(lhs_result) } }) } $crate::ffi::PyType_Slot { slot: $crate::ffi::$slot, pfunc: __wrap as $crate::ffi::$func_ty as _, } }}; } pub use $generate_macro; }; } define_pyclass_binary_operator_slot! { PyClass__add__SlotFragment, PyClass__radd__SlotFragment, __add__, __radd__, generate_pyclass_add_slot, Py_nb_add, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__sub__SlotFragment, PyClass__rsub__SlotFragment, __sub__, __rsub__, generate_pyclass_sub_slot, Py_nb_subtract, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__mul__SlotFragment, PyClass__rmul__SlotFragment, __mul__, __rmul__, generate_pyclass_mul_slot, Py_nb_multiply, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__mod__SlotFragment, PyClass__rmod__SlotFragment, __mod__, __rmod__, generate_pyclass_mod_slot, Py_nb_remainder, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__divmod__SlotFragment, PyClass__rdivmod__SlotFragment, __divmod__, __rdivmod__, generate_pyclass_divmod_slot, Py_nb_divmod, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__lshift__SlotFragment, PyClass__rlshift__SlotFragment, __lshift__, __rlshift__, generate_pyclass_lshift_slot, Py_nb_lshift, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__rshift__SlotFragment, PyClass__rrshift__SlotFragment, __rshift__, __rrshift__, generate_pyclass_rshift_slot, Py_nb_rshift, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__and__SlotFragment, PyClass__rand__SlotFragment, __and__, __rand__, generate_pyclass_and_slot, Py_nb_and, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__or__SlotFragment, PyClass__ror__SlotFragment, __or__, __ror__, generate_pyclass_or_slot, Py_nb_or, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__xor__SlotFragment, PyClass__rxor__SlotFragment, __xor__, __rxor__, generate_pyclass_xor_slot, Py_nb_xor, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__matmul__SlotFragment, PyClass__rmatmul__SlotFragment, __matmul__, __rmatmul__, generate_pyclass_matmul_slot, Py_nb_matrix_multiply, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__truediv__SlotFragment, PyClass__rtruediv__SlotFragment, __truediv__, __rtruediv__, generate_pyclass_truediv_slot, Py_nb_true_divide, binaryfunc, } define_pyclass_binary_operator_slot! { PyClass__floordiv__SlotFragment, PyClass__rfloordiv__SlotFragment, __floordiv__, __rfloordiv__, generate_pyclass_floordiv_slot, Py_nb_floor_divide, binaryfunc, } slot_fragment_trait! { PyClass__pow__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __pow__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, _mod: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } slot_fragment_trait! { PyClass__rpow__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __rpow__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, _mod: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } #[doc(hidden)] #[macro_export] macro_rules! generate_pyclass_pow_slot { ($cls:ty) => {{ unsafe extern "C" fn __wrap( _slf: *mut $crate::ffi::PyObject, _other: *mut $crate::ffi::PyObject, _mod: *mut $crate::ffi::PyObject, ) -> *mut $crate::ffi::PyObject { $crate::impl_::trampoline::ternaryfunc(_slf, _other, _mod, |py, _slf, _other, _mod| { use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); let lhs_result = collector.__pow__(py, _slf, _other, _mod)?; if lhs_result == $crate::ffi::Py_NotImplemented() { $crate::ffi::Py_DECREF(lhs_result); collector.__rpow__(py, _other, _slf, _mod) } else { ::std::result::Result::Ok(lhs_result) } }) } $crate::ffi::PyType_Slot { slot: $crate::ffi::Py_nb_power, pfunc: __wrap as $crate::ffi::ternaryfunc as _, } }}; } pub use generate_pyclass_pow_slot; slot_fragment_trait! { PyClass__lt__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __lt__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } slot_fragment_trait! { PyClass__le__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __le__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } slot_fragment_trait! { PyClass__eq__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __eq__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } slot_fragment_trait! { PyClass__ne__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __ne__( self, py: Python<'_>, slf: *mut ffi::PyObject, other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { // By default `__ne__` will try `__eq__` and invert the result let slf = Borrowed::from_ptr(py, slf); let other = Borrowed::from_ptr(py, other); slf.eq(other).map(|is_eq| PyBool::new(py, !is_eq).to_owned().into_ptr()) } } slot_fragment_trait! { PyClass__gt__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __gt__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } slot_fragment_trait! { PyClass__ge__SlotFragment, /// # Safety: _slf and _other must be valid non-null Python objects #[inline] unsafe fn __ge__( self, py: Python<'_>, _slf: *mut ffi::PyObject, _other: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { Ok(py.NotImplemented().into_ptr()) } } #[doc(hidden)] #[macro_export] macro_rules! generate_pyclass_richcompare_slot { ($cls:ty) => {{ #[allow(unknown_lints, non_local_definitions)] impl $cls { #[allow(non_snake_case)] unsafe extern "C" fn __pymethod___richcmp____( slf: *mut $crate::ffi::PyObject, other: *mut $crate::ffi::PyObject, op: ::std::os::raw::c_int, ) -> *mut $crate::ffi::PyObject { impl $crate::impl_::pyclass::HasCustomRichCmp for $cls {} $crate::impl_::trampoline::richcmpfunc(slf, other, op, |py, slf, other, op| { use $crate::class::basic::CompareOp; use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); match CompareOp::from_raw(op).expect("invalid compareop") { CompareOp::Lt => collector.__lt__(py, slf, other), CompareOp::Le => collector.__le__(py, slf, other), CompareOp::Eq => collector.__eq__(py, slf, other), CompareOp::Ne => collector.__ne__(py, slf, other), CompareOp::Gt => collector.__gt__(py, slf, other), CompareOp::Ge => collector.__ge__(py, slf, other), } }) } } $crate::ffi::PyType_Slot { slot: $crate::ffi::Py_tp_richcompare, pfunc: <$cls>::__pymethod___richcmp____ as $crate::ffi::richcmpfunc as _, } }}; } pub use generate_pyclass_richcompare_slot; use super::{pycell::PyClassObject, pymethods::BoundRef}; /// Implements a freelist. /// /// Do not implement this trait manually. Instead, use `#[pyclass(freelist = N)]` /// on a Rust struct to implement it. pub trait PyClassWithFreeList: PyClass { fn get_free_list(py: Python<'_>) -> &mut FreeList<*mut ffi::PyObject>; } /// Implementation of tp_alloc for `freelist` classes. /// /// # Safety /// - `subtype` must be a valid pointer to the type object of T or a subclass. /// - The GIL must be held. pub unsafe extern "C" fn alloc_with_freelist<T: PyClassWithFreeList>( subtype: *mut ffi::PyTypeObject, nitems: ffi::Py_ssize_t, ) -> *mut ffi::PyObject { let py = Python::assume_gil_acquired(); #[cfg(not(Py_3_8))] bpo_35810_workaround(py, subtype); let self_type = T::type_object_raw(py); // If this type is a variable type or the subtype is not equal to this type, we cannot use the // freelist if nitems == 0 && subtype == self_type { if let Some(obj) = T::get_free_list(py).pop() { ffi::PyObject_Init(obj, subtype); return obj as _; } } ffi::PyType_GenericAlloc(subtype, nitems) } /// Implementation of tp_free for `freelist` classes. /// /// # Safety /// - `obj` must be a valid pointer to an instance of T (not a subclass). /// - The GIL must be held. pub unsafe extern "C" fn free_with_freelist<T: PyClassWithFreeList>(obj: *mut c_void) { let obj = obj as *mut ffi::PyObject; debug_assert_eq!( T::type_object_raw(Python::assume_gil_acquired()), ffi::Py_TYPE(obj) ); if let Some(obj) = T::get_free_list(Python::assume_gil_acquired()).insert(obj) { let ty = ffi::Py_TYPE(obj); // Deduce appropriate inverse of PyType_GenericAlloc let free = if ffi::PyType_IS_GC(ty) != 0 { ffi::PyObject_GC_Del } else { ffi::PyObject_Free }; free(obj as *mut c_void); #[cfg(Py_3_8)] if ffi::PyType_HasFeature(ty, ffi::Py_TPFLAGS_HEAPTYPE) != 0 { ffi::Py_DECREF(ty as *mut ffi::PyObject); } } } /// Workaround for Python issue 35810; no longer necessary in Python 3.8 #[inline] #[cfg(not(Py_3_8))] unsafe fn bpo_35810_workaround(py: Python<'_>, ty: *mut ffi::PyTypeObject) { #[cfg(Py_LIMITED_API)] { // Must check version at runtime for abi3 wheels - they could run against a higher version // than the build config suggests. use crate::sync::GILOnceCell; static IS_PYTHON_3_8: GILOnceCell<bool> = GILOnceCell::new(); if *IS_PYTHON_3_8.get_or_init(py, || py.version_info() >= (3, 8)) { // No fix needed - the wheel is running on a sufficiently new interpreter. return; } } #[cfg(not(Py_LIMITED_API))] { // suppress unused variable warning let _ = py; } ffi::Py_INCREF(ty as *mut ffi::PyObject); } /// Method storage for `#[pyclass]`. /// /// Implementation detail. Only to be used through our proc macro code. /// Allows arbitrary `#[pymethod]` blocks to submit their methods, /// which are eventually collected by `#[pyclass]`. #[cfg(feature = "multiple-pymethods")] pub trait PyClassInventory: inventory::Collect { /// Returns the items for a single `#[pymethods] impl` block fn items(&'static self) -> &'static PyClassItems; } // Items from #[pymethods] if not using inventory. #[cfg(not(feature = "multiple-pymethods"))] pub trait PyMethods<T> { fn py_methods(self) -> &'static PyClassItems; } #[cfg(not(feature = "multiple-pymethods"))] impl<T> PyMethods<T> for &'_ PyClassImplCollector<T> { fn py_methods(self) -> &'static PyClassItems { &PyClassItems { methods: &[], slots: &[], } } } // Text signature for __new__ pub trait PyClassNewTextSignature<T> { fn new_text_signature(self) -> Option<&'static str>; } impl<T> PyClassNewTextSignature<T> for &'_ PyClassImplCollector<T> { #[inline] fn new_text_signature(self) -> Option<&'static str> { None } } // Thread checkers #[doc(hidden)] pub trait PyClassThreadChecker<T>: Sized { fn ensure(&self); fn check(&self) -> bool; fn can_drop(&self, py: Python<'_>) -> bool; fn new() -> Self; private_decl! {} } /// Default thread checker for `#[pyclass]`. /// /// Keeping the T: Send bound here slightly improves the compile /// error message to hint to users to figure out what's wrong /// when `#[pyclass]` types do not implement `Send`. #[doc(hidden)] pub struct SendablePyClass<T: Send>(PhantomData<T>); impl<T: Send> PyClassThreadChecker<T> for SendablePyClass<T> { fn ensure(&self) {} fn check(&self) -> bool { true } fn can_drop(&self, _py: Python<'_>) -> bool { true } #[inline] fn new() -> Self { SendablePyClass(PhantomData) } private_impl! {} } /// Thread checker for `#[pyclass(unsendable)]` types. /// Panics when the value is accessed by another thread. #[doc(hidden)] pub struct ThreadCheckerImpl(thread::ThreadId); impl ThreadCheckerImpl { fn ensure(&self, type_name: &'static str) { assert_eq!( thread::current().id(), self.0, "{} is unsendable, but sent to another thread", type_name ); } fn check(&self) -> bool { thread::current().id() == self.0 } fn can_drop(&self, py: Python<'_>, type_name: &'static str) -> bool { if thread::current().id() != self.0 { PyRuntimeError::new_err(format!( "{} is unsendable, but is being dropped on another thread", type_name )) .write_unraisable(py, None); return false; } true } } impl<T> PyClassThreadChecker<T> for ThreadCheckerImpl { fn ensure(&self) { self.ensure(std::any::type_name::<T>()); } fn check(&self) -> bool { self.check() } fn can_drop(&self, py: Python<'_>) -> bool { self.can_drop(py, std::any::type_name::<T>()) } fn new() -> Self { ThreadCheckerImpl(thread::current().id()) } private_impl! {} } /// Trait denoting that this class is suitable to be used as a base type for PyClass. #[cfg_attr( all(diagnostic_namespace, Py_LIMITED_API), diagnostic::on_unimplemented( message = "pyclass `{Self}` cannot be subclassed", label = "required for `#[pyclass(extends={Self})]`", note = "`{Self}` must have `#[pyclass(subclass)]` to be eligible for subclassing", note = "with the `abi3` feature enabled, PyO3 does not support subclassing native types", ) )] #[cfg_attr( all(diagnostic_namespace, not(Py_LIMITED_API)), diagnostic::on_unimplemented( message = "pyclass `{Self}` cannot be subclassed", label = "required for `#[pyclass(extends={Self})]`", note = "`{Self}` must have `#[pyclass(subclass)]` to be eligible for subclassing", ) )] pub trait PyClassBaseType: Sized { type LayoutAsBase: PyClassObjectLayout<Self>; type BaseNativeType; type Initializer: PyObjectInit<Self>; type PyClassMutability: PyClassMutability; } /// Implementation of tp_dealloc for pyclasses without gc pub(crate) unsafe extern "C" fn tp_dealloc<T: PyClass>(obj: *mut ffi::PyObject) { crate::impl_::trampoline::dealloc(obj, PyClassObject::<T>::tp_dealloc) } /// Implementation of tp_dealloc for pyclasses with gc pub(crate) unsafe extern "C" fn tp_dealloc_with_gc<T: PyClass>(obj: *mut ffi::PyObject) { #[cfg(not(PyPy))] { ffi::PyObject_GC_UnTrack(obj.cast()); } crate::impl_::trampoline::dealloc(obj, PyClassObject::<T>::tp_dealloc) } pub(crate) unsafe extern "C" fn get_sequence_item_from_mapping( obj: *mut ffi::PyObject, index: ffi::Py_ssize_t, ) -> *mut ffi::PyObject { let index = ffi::PyLong_FromSsize_t(index); if index.is_null() { return std::ptr::null_mut(); } let result = ffi::PyObject_GetItem(obj, index); ffi::Py_DECREF(index); result } pub(crate) unsafe extern "C" fn assign_sequence_item_from_mapping( obj: *mut ffi::PyObject, index: ffi::Py_ssize_t, value: *mut ffi::PyObject, ) -> c_int { let index = ffi::PyLong_FromSsize_t(index); if index.is_null() { return -1; } let result = if value.is_null() { ffi::PyObject_DelItem(obj, index) } else { ffi::PyObject_SetItem(obj, index, value) }; ffi::Py_DECREF(index); result } /// Helper trait to locate field within a `#[pyclass]` for a `#[pyo3(get)]`. /// /// Below MSRV 1.77 we can't use `std::mem::offset_of!`, and the replacement in /// `memoffset::offset_of` doesn't work in const contexts for types containing `UnsafeCell`. /// /// # Safety /// /// The trait is unsafe to implement because producing an incorrect offset will lead to UB. pub unsafe trait OffsetCalculator<T: PyClass, U> { /// Offset to the field within a `PyClassObject<T>`, in bytes. fn offset() -> usize; } // Used in generated implementations of OffsetCalculator pub fn class_offset<T: PyClass>() -> usize { offset_of!(PyClassObject<T>, contents) } // Used in generated implementations of OffsetCalculator pub use memoffset::offset_of; /// Type which uses specialization on impl blocks to determine how to read a field from a Rust pyclass /// as part of a `#[pyo3(get)]` annotation. pub struct PyClassGetterGenerator< // structural information about the field: class type, field type, where the field is within the // class struct ClassT: PyClass, FieldT, Offset: OffsetCalculator<ClassT, FieldT>, // on Rust 1.77+ this could be a const OFFSET: usize // additional metadata about the field which is used to switch between different implementations // at compile time const IS_PY_T: bool, const IMPLEMENTS_TOPYOBJECT: bool, const IMPLEMENTS_INTOPY: bool, const IMPLEMENTS_INTOPYOBJECT_REF: bool, const IMPLEMENTS_INTOPYOBJECT: bool, >(PhantomData<(ClassT, FieldT, Offset)>); impl< ClassT: PyClass, FieldT, Offset: OffsetCalculator<ClassT, FieldT>, const IS_PY_T: bool, const IMPLEMENTS_TOPYOBJECT: bool, const IMPLEMENTS_INTOPY: bool, const IMPLEMENTS_INTOPYOBJECT_REF: bool, const IMPLEMENTS_INTOPYOBJECT: bool, > PyClassGetterGenerator< ClassT, FieldT, Offset, IS_PY_T, IMPLEMENTS_TOPYOBJECT, IMPLEMENTS_INTOPY, IMPLEMENTS_INTOPYOBJECT_REF, IMPLEMENTS_INTOPYOBJECT, > { /// Safety: constructing this type requires that there exists a value of type FieldT /// at the calculated offset within the type ClassT. pub const unsafe fn new() -> Self { Self(PhantomData) } } impl< ClassT: PyClass, U, Offset: OffsetCalculator<ClassT, Py<U>>, const IMPLEMENTS_TOPYOBJECT: bool, const IMPLEMENTS_INTOPY: bool, const IMPLEMENTS_INTOPYOBJECT_REF: bool, const IMPLEMENTS_INTOPYOBJECT: bool, > PyClassGetterGenerator< ClassT, Py<U>, Offset, true, IMPLEMENTS_TOPYOBJECT, IMPLEMENTS_INTOPY, IMPLEMENTS_INTOPYOBJECT_REF, IMPLEMENTS_INTOPYOBJECT, > { /// `Py<T>` fields have a potential optimization to use Python's "struct members" to read /// the field directly from the struct, rather than using a getter function. /// /// This is the most efficient operation the Python interpreter could possibly do to /// read a field, but it's only possible for us to allow this for frozen classes. pub fn generate(&self, name: &'static CStr, doc: &'static CStr) -> PyMethodDefType { use crate::pyclass::boolean_struct::private::Boolean; if ClassT::Frozen::VALUE { PyMethodDefType::StructMember(ffi::PyMemberDef { name: name.as_ptr(), type_code: ffi::Py_T_OBJECT_EX, offset: Offset::offset() as ffi::Py_ssize_t, flags: ffi::Py_READONLY, doc: doc.as_ptr(), }) } else { PyMethodDefType::Getter(PyGetterDef { name, meth: pyo3_get_value_topyobject::<ClassT, Py<U>, Offset>, doc, }) } } } /// Fallback case; Field is not `Py<T>`; try to use `ToPyObject` to avoid potentially expensive /// clones of containers like `Vec` #[allow(deprecated)] impl< ClassT: PyClass, FieldT: ToPyObject, Offset: OffsetCalculator<ClassT, FieldT>, const IMPLEMENTS_INTOPY: bool, > PyClassGetterGenerator<ClassT, FieldT, Offset, false, true, IMPLEMENTS_INTOPY, false, false> { pub const fn generate(&self, name: &'static CStr, doc: &'static CStr) -> PyMethodDefType { PyMethodDefType::Getter(PyGetterDef { name, meth: pyo3_get_value_topyobject::<ClassT, FieldT, Offset>, doc, }) } } /// Field is not `Py<T>`; try to use `IntoPyObject` for `&T` (prefered over `ToPyObject`) to avoid /// potentially expensive clones of containers like `Vec` impl< ClassT, FieldT, Offset, const IMPLEMENTS_TOPYOBJECT: bool, const IMPLEMENTS_INTOPY: bool, const IMPLEMENTS_INTOPYOBJECT: bool, > PyClassGetterGenerator< ClassT, FieldT, Offset, false, IMPLEMENTS_TOPYOBJECT, IMPLEMENTS_INTOPY, true, IMPLEMENTS_INTOPYOBJECT, > where ClassT: PyClass, for<'a, 'py> &'a FieldT: IntoPyObject<'py>, Offset: OffsetCalculator<ClassT, FieldT>, { pub const fn generate(&self, name: &'static CStr, doc: &'static CStr) -> PyMethodDefType { PyMethodDefType::Getter(PyGetterDef { name, meth: pyo3_get_value_into_pyobject_ref::<ClassT, FieldT, Offset>, doc, }) } } /// Temporary case to prefer `IntoPyObject + Clone` over `IntoPy + Clone`, while still showing the /// `IntoPyObject` suggestion if neither is implemented; impl<ClassT, FieldT, Offset, const IMPLEMENTS_TOPYOBJECT: bool, const IMPLEMENTS_INTOPY: bool> PyClassGetterGenerator< ClassT, FieldT, Offset, false, IMPLEMENTS_TOPYOBJECT, IMPLEMENTS_INTOPY, false, true, > where ClassT: PyClass, Offset: OffsetCalculator<ClassT, FieldT>, for<'py> FieldT: IntoPyObject<'py> + Clone, { pub const fn generate(&self, name: &'static CStr, doc: &'static CStr) -> PyMethodDefType { PyMethodDefType::Getter(PyGetterDef { name, meth: pyo3_get_value_into_pyobject::<ClassT, FieldT, Offset>, doc, }) } } /// IntoPy + Clone fallback case, which was the only behaviour before PyO3 0.22. #[allow(deprecated)] impl<ClassT, FieldT, Offset> PyClassGetterGenerator<ClassT, FieldT, Offset, false, false, true, false, false> where ClassT: PyClass, Offset: OffsetCalculator<ClassT, FieldT>, FieldT: IntoPy<Py<PyAny>> + Clone, { pub const fn generate(&self, name: &'static CStr, doc: &'static CStr) -> PyMethodDefType { PyMethodDefType::Getter(PyGetterDef { name, meth: pyo3_get_value::<ClassT, FieldT, Offset>, doc, }) } } #[cfg_attr( diagnostic_namespace, diagnostic::on_unimplemented( message = "`{Self}` cannot be converted to a Python object", label = "required by `#[pyo3(get)]` to create a readable property from a field of type `{Self}`", note = "implement `IntoPyObject` for `&{Self}` or `IntoPyObject + Clone` for `{Self}` to define the conversion" ) )] pub trait PyO3GetField<'py>: IntoPyObject<'py> + Clone {} impl<'py, T> PyO3GetField<'py> for T where T: IntoPyObject<'py> + Clone {} /// Base case attempts to use IntoPyObject + Clone impl<ClassT: PyClass, FieldT, Offset: OffsetCalculator<ClassT, FieldT>> PyClassGetterGenerator<ClassT, FieldT, Offset, false, false, false, false, false> { pub const fn generate(&self, _name: &'static CStr, _doc: &'static CStr) -> PyMethodDefType // The bound goes here rather than on the block so that this impl is always available // if no specialization is used instead where for<'py> FieldT: PyO3GetField<'py>, { // unreachable not allowed in const panic!( "exists purely to emit diagnostics on unimplemented traits. When `ToPyObject` \ and `IntoPy` are fully removed this will be replaced by the temporary `IntoPyObject` case above." ) } } /// ensures `obj` is not mutably aliased #[inline] unsafe fn ensure_no_mutable_alias<'py, ClassT: PyClass>( py: Python<'py>, obj: &*mut ffi::PyObject, ) -> Result<PyRef<'py, ClassT>, PyBorrowError> { BoundRef::ref_from_ptr(py, obj) .downcast_unchecked::<ClassT>() .try_borrow() } /// calculates the field pointer from an PyObject pointer #[inline] fn field_from_object<ClassT, FieldT, Offset>(obj: *mut ffi::PyObject) -> *mut FieldT where ClassT: PyClass, Offset: OffsetCalculator<ClassT, FieldT>, { unsafe { obj.cast::<u8>().add(Offset::offset()).cast::<FieldT>() } } #[allow(deprecated)] fn pyo3_get_value_topyobject< ClassT: PyClass, FieldT: ToPyObject, Offset: OffsetCalculator<ClassT, FieldT>, >( py: Python<'_>, obj: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { let _holder = unsafe { ensure_no_mutable_alias::<ClassT>(py, &obj)? }; let value = field_from_object::<ClassT, FieldT, Offset>(obj); // SAFETY: Offset is known to describe the location of the value, and // _holder is preventing mutable aliasing Ok((unsafe { &*value }).to_object(py).into_ptr()) } fn pyo3_get_value_into_pyobject_ref<ClassT, FieldT, Offset>( py: Python<'_>, obj: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> where ClassT: PyClass, for<'a, 'py> &'a FieldT: IntoPyObject<'py>, Offset: OffsetCalculator<ClassT, FieldT>, { let _holder = unsafe { ensure_no_mutable_alias::<ClassT>(py, &obj)? }; let value = field_from_object::<ClassT, FieldT, Offset>(obj); // SAFETY: Offset is known to describe the location of the value, and // _holder is preventing mutable aliasing Ok((unsafe { &*value }) .into_pyobject(py) .map_err(Into::into)? .into_ptr()) } fn pyo3_get_value_into_pyobject<ClassT, FieldT, Offset>( py: Python<'_>, obj: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> where ClassT: PyClass, for<'py> FieldT: IntoPyObject<'py> + Clone, Offset: OffsetCalculator<ClassT, FieldT>, { let _holder = unsafe { ensure_no_mutable_alias::<ClassT>(py, &obj)? }; let value = field_from_object::<ClassT, FieldT, Offset>(obj); // SAFETY: Offset is known to describe the location of the value, and // _holder is preventing mutable aliasing Ok((unsafe { &*value }) .clone() .into_pyobject(py) .map_err(Into::into)? .into_ptr()) } #[allow(deprecated)] fn pyo3_get_value< ClassT: PyClass, FieldT: IntoPy<Py<PyAny>> + Clone, Offset: OffsetCalculator<ClassT, FieldT>, >( py: Python<'_>, obj: *mut ffi::PyObject, ) -> PyResult<*mut ffi::PyObject> { let _holder = unsafe { ensure_no_mutable_alias::<ClassT>(py, &obj)? }; let value = field_from_object::<ClassT, FieldT, Offset>(obj); // SAFETY: Offset is known to describe the location of the value, and // _holder is preventing mutable aliasing Ok((unsafe { &*value }).clone().into_py(py).into_ptr()) } pub struct ConvertField< const IMPLEMENTS_INTOPYOBJECT_REF: bool, const IMPLEMENTS_INTOPYOBJECT: bool, >; impl<const IMPLEMENTS_INTOPYOBJECT: bool> ConvertField<true, IMPLEMENTS_INTOPYOBJECT> { #[inline] pub fn convert_field<'a, 'py, T>(obj: &'a T, py: Python<'py>) -> PyResult<Py<PyAny>> where &'a T: IntoPyObject<'py>, { obj.into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::unbind) .map_err(Into::into) } } impl<const IMPLEMENTS_INTOPYOBJECT: bool> ConvertField<false, IMPLEMENTS_INTOPYOBJECT> { #[inline] pub fn convert_field<'py, T>(obj: &T, py: Python<'py>) -> PyResult<Py<PyAny>> where T: PyO3GetField<'py>, { obj.clone() .into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::unbind) .map_err(Into::into) } } /// Marker trait whether a class implemented a custom comparison. Used to /// silence deprecation of autogenerated `__richcmp__` for enums. pub trait HasCustomRichCmp {} /// Autoref specialization setup to emit deprecation warnings for autogenerated /// pyclass equality. pub struct DeprecationTest<T>(Deprecation, ::std::marker::PhantomData<T>); pub struct Deprecation; impl<T> DeprecationTest<T> { #[inline] #[allow(clippy::new_without_default)] pub const fn new() -> Self { DeprecationTest(Deprecation, ::std::marker::PhantomData) } } impl<T> std::ops::Deref for DeprecationTest<T> { type Target = Deprecation; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DeprecationTest<T> where T: HasCustomRichCmp, { /// For `HasCustomRichCmp` types; no deprecation warning. #[inline] pub fn autogenerated_equality(&self) {} } impl Deprecation { #[deprecated( since = "0.22.0", note = "Implicit equality for simple enums is deprecated. Use `#[pyclass(eq, eq_int)]` to keep the current behavior." )] /// For types which don't implement `HasCustomRichCmp`; emits deprecation warning. #[inline] pub fn autogenerated_equality(&self) {} } #[cfg(test)] #[cfg(feature = "macros")] mod tests { use super::*; #[test] fn get_py_for_frozen_class() { #[crate::pyclass(crate = "crate", frozen)] struct FrozenClass { #[pyo3(get)] value: Py<PyAny>, } let mut methods = Vec::new(); let mut slots = Vec::new(); for items in FrozenClass::items_iter() { methods.extend(items.methods.iter().map(|m| match m { MaybeRuntimePyMethodDef::Static(m) => m.clone(), MaybeRuntimePyMethodDef::Runtime(r) => r(), })); slots.extend_from_slice(items.slots); } assert_eq!(methods.len(), 1); assert!(slots.is_empty()); match methods.first() { Some(PyMethodDefType::StructMember(member)) => { assert_eq!(unsafe { CStr::from_ptr(member.name) }, ffi::c_str!("value")); assert_eq!(member.type_code, ffi::Py_T_OBJECT_EX); assert_eq!( member.offset, (memoffset::offset_of!(PyClassObject<FrozenClass>, contents) + memoffset::offset_of!(FrozenClass, value)) as ffi::Py_ssize_t ); assert_eq!(member.flags, ffi::Py_READONLY); } _ => panic!("Expected a StructMember"), } } #[test] fn get_py_for_non_frozen_class() { #[crate::pyclass(crate = "crate")] struct FrozenClass { #[pyo3(get)] value: Py<PyAny>, } let mut methods = Vec::new(); let mut slots = Vec::new(); for items in FrozenClass::items_iter() { methods.extend(items.methods.iter().map(|m| match m { MaybeRuntimePyMethodDef::Static(m) => m.clone(), MaybeRuntimePyMethodDef::Runtime(r) => r(), })); slots.extend_from_slice(items.slots); } assert_eq!(methods.len(), 1); assert!(slots.is_empty()); match methods.first() { Some(PyMethodDefType::Getter(getter)) => { assert_eq!(getter.name, ffi::c_str!("value")); assert_eq!(getter.doc, ffi::c_str!("")); // tests for the function pointer are in test_getter_setter.py } _ => panic!("Expected a StructMember"), } } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/exceptions.rs
use crate::{sync::GILOnceCell, types::PyType, Bound, Py, Python}; pub struct ImportedExceptionTypeObject { imported_value: GILOnceCell<Py<PyType>>, module: &'static str, name: &'static str, } impl ImportedExceptionTypeObject { pub const fn new(module: &'static str, name: &'static str) -> Self { Self { imported_value: GILOnceCell::new(), module, name, } } pub fn get<'py>(&self, py: Python<'py>) -> &Bound<'py, PyType> { self.imported_value .import(py, self.module, self.name) .unwrap_or_else(|e| { panic!( "failed to import exception {}.{}: {}", self.module, self.name, e ) }) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/panic.rs
/// Type which will panic if dropped. /// /// If this is dropped during a panic, this will cause an abort. /// /// Use this to avoid letting unwinds cross through the FFI boundary, which is UB. pub struct PanicTrap { msg: &'static str, } impl PanicTrap { #[inline] pub const fn new(msg: &'static str) -> Self { Self { msg } } #[inline] pub const fn disarm(self) { std::mem::forget(self) } } impl Drop for PanicTrap { fn drop(&mut self) { // Panic here will abort the process, assuming in an unwind. panic!("{}", self.msg) } }
0
lc_public_repos/langsmith-sdk/vendor/pyo3/src
lc_public_repos/langsmith-sdk/vendor/pyo3/src/impl_/callback.rs
//! Utilities for a Python callable object that invokes a Rust function. use crate::err::{PyErr, PyResult}; use crate::exceptions::PyOverflowError; use crate::ffi::{self, Py_hash_t}; use crate::{BoundObject, IntoPyObject, PyObject, Python}; use std::os::raw::c_int; /// A type which can be the return type of a python C-API callback pub trait PyCallbackOutput: Copy { /// The error value to return to python if the callback raised an exception const ERR_VALUE: Self; } impl PyCallbackOutput for *mut ffi::PyObject { const ERR_VALUE: Self = std::ptr::null_mut(); } impl PyCallbackOutput for std::os::raw::c_int { const ERR_VALUE: Self = -1; } impl PyCallbackOutput for ffi::Py_ssize_t { const ERR_VALUE: Self = -1; } /// Convert the result of callback function into the appropriate return value. pub trait IntoPyCallbackOutput<'py, Target> { fn convert(self, py: Python<'py>) -> PyResult<Target>; } impl<'py, T, E, U> IntoPyCallbackOutput<'py, U> for Result<T, E> where T: IntoPyCallbackOutput<'py, U>, E: Into<PyErr>, { #[inline] fn convert(self, py: Python<'py>) -> PyResult<U> { match self { Ok(v) => v.convert(py), Err(e) => Err(e.into()), } } } impl<'py, T> IntoPyCallbackOutput<'py, *mut ffi::PyObject> for T where T: IntoPyObject<'py>, { #[inline] fn convert(self, py: Python<'py>) -> PyResult<*mut ffi::PyObject> { self.into_pyobject(py) .map(BoundObject::into_ptr) .map_err(Into::into) } } impl IntoPyCallbackOutput<'_, Self> for *mut ffi::PyObject { #[inline] fn convert(self, _: Python<'_>) -> PyResult<Self> { Ok(self) } } impl IntoPyCallbackOutput<'_, std::os::raw::c_int> for () { #[inline] fn convert(self, _: Python<'_>) -> PyResult<std::os::raw::c_int> { Ok(0) } } impl IntoPyCallbackOutput<'_, std::os::raw::c_int> for bool { #[inline] fn convert(self, _: Python<'_>) -> PyResult<std::os::raw::c_int> { Ok(self as c_int) } } impl IntoPyCallbackOutput<'_, ()> for () { #[inline] fn convert(self, _: Python<'_>) -> PyResult<()> { Ok(()) } } impl IntoPyCallbackOutput<'_, ffi::Py_ssize_t> for usize { #[inline] fn convert(self, _py: Python<'_>) -> PyResult<ffi::Py_ssize_t> { self.try_into().map_err(|_err| PyOverflowError::new_err(())) } } // Converters needed for `#[pyproto]` implementations impl IntoPyCallbackOutput<'_, bool> for bool { #[inline] fn convert(self, _: Python<'_>) -> PyResult<bool> { Ok(self) } } impl IntoPyCallbackOutput<'_, usize> for usize { #[inline] fn convert(self, _: Python<'_>) -> PyResult<usize> { Ok(self) } } impl<'py, T> IntoPyCallbackOutput<'py, PyObject> for T where T: IntoPyObject<'py>, { #[inline] fn convert(self, py: Python<'py>) -> PyResult<PyObject> { self.into_pyobject(py) .map(BoundObject::into_any) .map(BoundObject::unbind) .map_err(Into::into) } } pub trait WrappingCastTo<T> { fn wrapping_cast(self) -> T; } macro_rules! wrapping_cast { ($from:ty, $to:ty) => { impl WrappingCastTo<$to> for $from { #[inline] fn wrapping_cast(self) -> $to { self as $to } } }; } wrapping_cast!(u8, Py_hash_t); wrapping_cast!(u16, Py_hash_t); wrapping_cast!(u32, Py_hash_t); wrapping_cast!(usize, Py_hash_t); wrapping_cast!(u64, Py_hash_t); wrapping_cast!(i8, Py_hash_t); wrapping_cast!(i16, Py_hash_t); wrapping_cast!(i32, Py_hash_t); wrapping_cast!(isize, Py_hash_t); wrapping_cast!(i64, Py_hash_t); pub struct HashCallbackOutput(Py_hash_t); impl IntoPyCallbackOutput<'_, Py_hash_t> for HashCallbackOutput { #[inline] fn convert(self, _py: Python<'_>) -> PyResult<Py_hash_t> { let hash = self.0; if hash == -1 { Ok(-2) } else { Ok(hash) } } } impl<T> IntoPyCallbackOutput<'_, HashCallbackOutput> for T where T: WrappingCastTo<Py_hash_t>, { #[inline] fn convert(self, _py: Python<'_>) -> PyResult<HashCallbackOutput> { Ok(HashCallbackOutput(self.wrapping_cast())) } } #[doc(hidden)] #[inline] pub fn convert<'py, T, U>(py: Python<'py>, value: T) -> PyResult<U> where T: IntoPyCallbackOutput<'py, U>, { value.convert(py) }