-
Notifications
You must be signed in to change notification settings - Fork 849
Improve native object initialization #4798
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mbway
wants to merge
5
commits into
PyO3:main
Choose a base branch
from
mbway:improve_native_new
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f428981
Improve native object initialization
mbway 57128c0
add option to override tp_new to handle PyBaseObject_Type
mbway d051c86
Merge branch 'main' into improve_native_new
mbway 0d291af
fix uses of unsafe
mbway ed39f0a
fix typo
mbway File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
fixes several limitations with base native type initialization. Required for extending native base types | ||
with the limited API and extending base native types that require arguments passed to `__new__`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,13 @@ | ||
//! Contains initialization utilities for `#[pyclass]`. | ||
use crate::exceptions::PyTypeError; | ||
use crate::ffi_ptr_ext::FfiPtrExt; | ||
use crate::internal::get_slot::TP_ALLOC; | ||
use crate::types::PyType; | ||
use crate::{ffi, Borrowed, PyErr, PyResult, Python}; | ||
use crate::internal::get_slot::TP_NEW; | ||
use crate::types::{PyDict, PyTuple, PyType}; | ||
use crate::{ffi, Bound, PyErr, PyResult, Python}; | ||
use crate::{ffi::PyTypeObject, sealed::Sealed, type_object::PyTypeInfo}; | ||
use std::marker::PhantomData; | ||
use std::ptr; | ||
|
||
use super::pyclass::PyClassBaseType; | ||
|
||
/// Initializer for Python types. | ||
/// | ||
|
@@ -18,72 +20,76 @@ pub trait PyObjectInit<T>: Sized + Sealed { | |
self, | ||
py: Python<'_>, | ||
subtype: *mut PyTypeObject, | ||
args: &Bound<'_, PyTuple>, | ||
kwargs: Option<&Bound<'_, PyDict>>, | ||
) -> PyResult<*mut ffi::PyObject>; | ||
|
||
#[doc(hidden)] | ||
fn can_be_subclassed(&self) -> bool; | ||
} | ||
|
||
/// Initializer for Python native types, like `PyDict`. | ||
pub struct PyNativeTypeInitializer<T: PyTypeInfo>(pub PhantomData<T>); | ||
/// Initializer for Python native types, like [PyDict]. | ||
pub struct PyNativeTypeInitializer<T: PyTypeInfo + PyClassBaseType>(pub PhantomData<T>); | ||
|
||
impl<T: PyTypeInfo> PyObjectInit<T> for PyNativeTypeInitializer<T> { | ||
impl<T: PyTypeInfo + PyClassBaseType> PyObjectInit<T> for PyNativeTypeInitializer<T> { | ||
/// call `__new__` ([ffi::PyTypeObject::tp_new]) for the native base type. | ||
/// This will allocate a new python object and initialize the part relating to the native base type. | ||
unsafe fn into_new_object( | ||
self, | ||
py: Python<'_>, | ||
subtype: *mut PyTypeObject, | ||
args: &Bound<'_, PyTuple>, | ||
kwargs: Option<&Bound<'_, PyDict>>, | ||
) -> PyResult<*mut ffi::PyObject> { | ||
unsafe fn inner( | ||
fn inner( | ||
py: Python<'_>, | ||
type_object: *mut PyTypeObject, | ||
native_base_type: *mut PyTypeObject, | ||
subtype: *mut PyTypeObject, | ||
args: &Bound<'_, PyTuple>, | ||
kwargs: Option<&Bound<'_, PyDict>>, | ||
override_tp_new: Option<ffi::newfunc>, | ||
) -> PyResult<*mut ffi::PyObject> { | ||
// HACK (due to FIXME below): PyBaseObject_Type's tp_new isn't happy with NULL arguments | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think there was a misunderstanding here, calling |
||
let is_base_object = ptr::eq(type_object, ptr::addr_of!(ffi::PyBaseObject_Type)); | ||
let subtype_borrowed: Borrowed<'_, '_, PyType> = unsafe { | ||
subtype | ||
.cast::<ffi::PyObject>() | ||
.assume_borrowed_unchecked(py) | ||
.downcast_unchecked() | ||
let tp_new = if let Some(tp_new) = override_tp_new { | ||
tp_new | ||
} else { | ||
unsafe { | ||
native_base_type | ||
.cast::<ffi::PyObject>() | ||
.assume_borrowed_unchecked(py) | ||
.downcast_unchecked::<PyType>() | ||
.get_slot(TP_NEW) | ||
.ok_or_else(|| { | ||
PyTypeError::new_err( | ||
"cannot construct type that does not define __new__", | ||
) | ||
})? | ||
} | ||
}; | ||
|
||
if is_base_object { | ||
let alloc = subtype_borrowed | ||
.get_slot(TP_ALLOC) | ||
.unwrap_or(ffi::PyType_GenericAlloc); | ||
|
||
let obj = unsafe { alloc(subtype, 0) }; | ||
return if obj.is_null() { | ||
Err(PyErr::fetch(py)) | ||
} else { | ||
Ok(obj) | ||
}; | ||
} | ||
|
||
#[cfg(Py_LIMITED_API)] | ||
unreachable!("subclassing native types is not possible with the `abi3` feature"); | ||
let obj = unsafe { | ||
tp_new( | ||
subtype, | ||
args.as_ptr(), | ||
kwargs | ||
.map(|obj| obj.as_ptr()) | ||
.unwrap_or(std::ptr::null_mut()), | ||
) | ||
}; | ||
|
||
#[cfg(not(Py_LIMITED_API))] | ||
{ | ||
match unsafe { (*type_object).tp_new } { | ||
// FIXME: Call __new__ with actual arguments | ||
Some(newfunc) => { | ||
let obj = | ||
unsafe { newfunc(subtype, std::ptr::null_mut(), std::ptr::null_mut()) }; | ||
if obj.is_null() { | ||
Err(PyErr::fetch(py)) | ||
} else { | ||
Ok(obj) | ||
} | ||
} | ||
None => Err(crate::exceptions::PyTypeError::new_err( | ||
"base type without tp_new", | ||
)), | ||
} | ||
if obj.is_null() { | ||
Err(PyErr::fetch(py)) | ||
} else { | ||
Ok(obj) | ||
} | ||
} | ||
let type_object = T::type_object_raw(py); | ||
unsafe { inner(py, type_object, subtype) } | ||
inner( | ||
py, | ||
T::type_object_raw(py), | ||
subtype, | ||
args, | ||
kwargs, | ||
T::OVERRIDE_TP_NEW, | ||
) | ||
} | ||
|
||
#[inline] | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I assume these are named with underscores because sometimes the generated code uses them and sometimes it doesn't?