Skip to content

Commit f5aa30a

Browse files
Use vectorcall (where possible) when calling Python functions
This works without any changes to user code. The way it works is by creating a methods on `IntoPy` to call functions, and specializing them for tuples. This currently supports only non-kwargs for methods, and kwargs with somewhat slow approach (converting from PyDict) for functions. This can be improved, but that will require additional API. We may consider adding more impls IntoPy<Py<PyTuple>> that specialize (for example, for arrays and `Vec`), but this i a good start.
1 parent 07da500 commit f5aa30a

File tree

5 files changed

+270
-28
lines changed

5 files changed

+270
-28
lines changed

newsfragments/4456.changed.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve performance of calls to Python by using the vectorcall calling convention where possible.

pyo3-ffi/src/cpython/abstract_.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ extern "C" {
4040
}
4141

4242
#[cfg(Py_3_8)]
43-
const PY_VECTORCALL_ARGUMENTS_OFFSET: size_t =
43+
pub const PY_VECTORCALL_ARGUMENTS_OFFSET: size_t =
4444
1 << (8 * std::mem::size_of::<size_t>() as size_t - 1);
4545

4646
#[cfg(Py_3_8)]

src/conversion.rs

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
//! Defines conversions between Rust and Python types.
22
use crate::err::PyResult;
3+
use crate::ffi_ptr_ext::FfiPtrExt;
34
#[cfg(feature = "experimental-inspect")]
45
use crate::inspect::types::TypeInfo;
56
use crate::pyclass::boolean_struct::False;
67
use crate::types::any::PyAnyMethods;
7-
use crate::types::PyTuple;
8+
use crate::types::{PyDict, PyString, PyTuple};
89
use crate::{
910
ffi, Borrowed, Bound, BoundObject, Py, PyAny, PyClass, PyErr, PyObject, PyRef, PyRefMut, Python,
1011
};
@@ -172,6 +173,93 @@ pub trait IntoPy<T>: Sized {
172173
fn type_output() -> TypeInfo {
173174
TypeInfo::Any
174175
}
176+
177+
// The following methods are helpers to use the vectorcall API where possible.
178+
// They are overridden on tuples to perform a vectorcall.
179+
// Be careful when you're implementing these: they can never refer to `Bound` call methods,
180+
// as those refer to these methods, so this will create an infinite recursion.
181+
#[doc(hidden)]
182+
#[inline]
183+
fn __py_call_vectorcall1<'py>(
184+
self,
185+
py: Python<'py>,
186+
function: Borrowed<'_, 'py, PyAny>,
187+
_: private::Token,
188+
) -> PyResult<Bound<'py, PyAny>>
189+
where
190+
Self: IntoPy<Py<PyTuple>>,
191+
{
192+
#[inline]
193+
fn inner<'py>(
194+
py: Python<'py>,
195+
function: Borrowed<'_, 'py, PyAny>,
196+
args: Bound<'py, PyTuple>,
197+
) -> PyResult<Bound<'py, PyAny>> {
198+
unsafe {
199+
ffi::PyObject_Call(function.as_ptr(), args.as_ptr(), std::ptr::null_mut())
200+
.assume_owned_or_err(py)
201+
}
202+
}
203+
inner(
204+
py,
205+
function,
206+
<Self as IntoPy<Py<PyTuple>>>::into_py(self, py).into_bound(py),
207+
)
208+
}
209+
210+
#[doc(hidden)]
211+
#[inline]
212+
fn __py_call_vectorcall<'py>(
213+
self,
214+
py: Python<'py>,
215+
function: Borrowed<'_, 'py, PyAny>,
216+
kwargs: Option<Borrowed<'_, '_, PyDict>>,
217+
_: private::Token,
218+
) -> PyResult<Bound<'py, PyAny>>
219+
where
220+
Self: IntoPy<Py<PyTuple>>,
221+
{
222+
#[inline]
223+
fn inner<'py>(
224+
py: Python<'py>,
225+
function: Borrowed<'_, 'py, PyAny>,
226+
args: Bound<'py, PyTuple>,
227+
kwargs: Option<Borrowed<'_, '_, PyDict>>,
228+
) -> PyResult<Bound<'py, PyAny>> {
229+
unsafe {
230+
ffi::PyObject_Call(
231+
function.as_ptr(),
232+
args.as_ptr(),
233+
kwargs.map_or_else(std::ptr::null_mut, |kwargs| kwargs.as_ptr()),
234+
)
235+
.assume_owned_or_err(py)
236+
}
237+
}
238+
inner(
239+
py,
240+
function,
241+
<Self as IntoPy<Py<PyTuple>>>::into_py(self, py).into_bound(py),
242+
kwargs,
243+
)
244+
}
245+
246+
#[doc(hidden)]
247+
#[inline]
248+
fn __py_call_method_vectorcall1<'py>(
249+
self,
250+
_py: Python<'py>,
251+
object: Borrowed<'_, 'py, PyAny>,
252+
method_name: Bound<'py, PyString>,
253+
_: private::Token,
254+
) -> PyResult<Bound<'py, PyAny>>
255+
where
256+
Self: IntoPy<Py<PyTuple>>,
257+
{
258+
// Don't `self.into_py()`! This will lose the optimization of vectorcall.
259+
object
260+
.getattr(method_name)
261+
.and_then(|method| method.call1(self))
262+
}
175263
}
176264

177265
/// Defines a conversion from a Rust type to a Python object, which may fail.
@@ -502,6 +590,52 @@ impl IntoPy<Py<PyTuple>> for () {
502590
fn into_py(self, py: Python<'_>) -> Py<PyTuple> {
503591
PyTuple::empty(py).unbind()
504592
}
593+
594+
#[inline]
595+
fn __py_call_vectorcall1<'py>(
596+
self,
597+
py: Python<'py>,
598+
function: Borrowed<'_, 'py, PyAny>,
599+
_: private::Token,
600+
) -> PyResult<Bound<'py, PyAny>> {
601+
unsafe { ffi::compat::PyObject_CallNoArgs(function.as_ptr()).assume_owned_or_err(py) }
602+
}
603+
604+
#[inline]
605+
fn __py_call_vectorcall<'py>(
606+
self,
607+
py: Python<'py>,
608+
function: Borrowed<'_, 'py, PyAny>,
609+
kwargs: Option<Borrowed<'_, '_, PyDict>>,
610+
_: private::Token,
611+
) -> PyResult<Bound<'py, PyAny>> {
612+
unsafe {
613+
match kwargs {
614+
Some(kwargs) => ffi::PyObject_Call(
615+
function.as_ptr(),
616+
PyTuple::empty(py).as_ptr(),
617+
kwargs.as_ptr(),
618+
)
619+
.assume_owned_or_err(py),
620+
None => ffi::compat::PyObject_CallNoArgs(function.as_ptr()).assume_owned_or_err(py),
621+
}
622+
}
623+
}
624+
625+
#[inline]
626+
#[allow(clippy::used_underscore_binding)]
627+
fn __py_call_method_vectorcall1<'py>(
628+
self,
629+
py: Python<'py>,
630+
object: Borrowed<'_, 'py, PyAny>,
631+
method_name: Bound<'py, PyString>,
632+
_: private::Token,
633+
) -> PyResult<Bound<'py, PyAny>> {
634+
unsafe {
635+
ffi::compat::PyObject_CallMethodNoArgs(object.as_ptr(), method_name.as_ptr())
636+
.assume_owned_or_err(py)
637+
}
638+
}
505639
}
506640

507641
impl<'py> IntoPyObject<'py> for () {

src/types/any.rs

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::class::basic::CompareOp;
2-
use crate::conversion::{AsPyPointer, FromPyObjectBound, IntoPy, ToPyObject};
2+
use crate::conversion::{private, AsPyPointer, FromPyObjectBound, IntoPy, ToPyObject};
33
use crate::err::{DowncastError, DowncastIntoError, PyErr, PyResult};
44
use crate::exceptions::{PyAttributeError, PyTypeError};
55
use crate::ffi_ptr_ext::FfiPtrExt;
@@ -1160,33 +1160,24 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
11601160
args: impl IntoPy<Py<PyTuple>>,
11611161
kwargs: Option<&Bound<'_, PyDict>>,
11621162
) -> PyResult<Bound<'py, PyAny>> {
1163-
fn inner<'py>(
1164-
any: &Bound<'py, PyAny>,
1165-
args: Bound<'_, PyTuple>,
1166-
kwargs: Option<&Bound<'_, PyDict>>,
1167-
) -> PyResult<Bound<'py, PyAny>> {
1168-
unsafe {
1169-
ffi::PyObject_Call(
1170-
any.as_ptr(),
1171-
args.as_ptr(),
1172-
kwargs.map_or(std::ptr::null_mut(), |dict| dict.as_ptr()),
1173-
)
1174-
.assume_owned_or_err(any.py())
1175-
}
1176-
}
1177-
1178-
let py = self.py();
1179-
inner(self, args.into_py(py).into_bound(py), kwargs)
1163+
args.__py_call_vectorcall(
1164+
self.py(),
1165+
self.as_borrowed(),
1166+
kwargs.map(Bound::as_borrowed),
1167+
private::Token,
1168+
)
11801169
}
11811170

1171+
#[inline]
11821172
fn call0(&self) -> PyResult<Bound<'py, PyAny>> {
11831173
unsafe { ffi::compat::PyObject_CallNoArgs(self.as_ptr()).assume_owned_or_err(self.py()) }
11841174
}
11851175

11861176
fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<Bound<'py, PyAny>> {
1187-
self.call(args, None)
1177+
args.__py_call_vectorcall1(self.py(), self.as_borrowed(), private::Token)
11881178
}
11891179

1180+
#[inline]
11901181
fn call_method<N, A>(
11911182
&self,
11921183
name: N,
@@ -1197,10 +1188,16 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
11971188
N: IntoPy<Py<PyString>>,
11981189
A: IntoPy<Py<PyTuple>>,
11991190
{
1200-
self.getattr(name)
1201-
.and_then(|method| method.call(args, kwargs))
1191+
// Don't `args.into_py()`! This will lose the optimization of vectorcall.
1192+
match kwargs {
1193+
Some(_) => self
1194+
.getattr(name)
1195+
.and_then(|method| method.call(args, kwargs)),
1196+
None => self.call_method1(name, args),
1197+
}
12021198
}
12031199

1200+
#[inline]
12041201
fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
12051202
where
12061203
N: IntoPy<Py<PyString>>,
@@ -1218,7 +1215,12 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
12181215
N: IntoPy<Py<PyString>>,
12191216
A: IntoPy<Py<PyTuple>>,
12201217
{
1221-
self.call_method(name, args, None)
1218+
args.__py_call_method_vectorcall1(
1219+
self.py(),
1220+
self.as_borrowed(),
1221+
name.into_py(self.py()).into_bound(self.py()),
1222+
private::Token,
1223+
)
12221224
}
12231225

12241226
fn is_truthy(&self) -> PyResult<bool> {

0 commit comments

Comments
 (0)