pub trait Constructor: PyPayload + Debug {
type Args: FromArgs;
const __OWN_METHOD_DEFS: &'static [PyMethodDef] = _;
// Required method
fn py_new(
cls: &Py<PyType>,
args: Self::Args,
vm: &VirtualMachine,
) -> PyResult<Self>;
// Provided methods
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { ... }
fn __extend_py_class(ctx: &'static Context, class: &'static Py<PyType>) { ... }
fn __extend_slots(slots: &mut PyTypeSlots) { ... }
}Expand description
Trait for types that can be constructed via Python’s __new__ method.
slot_new corresponds to the __new__ type slot.
In most cases, __new__ simply initializes the payload and assigns a type,
so you only need to override py_new. The default slot_new implementation
will call py_new and then wrap the result with into_ref_with_type.
However, if a subtype requires more than just payload initialization
(e.g., returning an existing object for optimization, setting attributes
after creation, or special handling of the class type), you should override
slot_new directly instead of py_new.
§When to use py_new only (most common case):
- Simple payload initialization that just creates
Self - The type doesn’t need special handling for subtypes
§When to override slot_new:
- Returning existing objects (e.g.,
PyInt,PyStr,PyBoolfor optimization) - Setting attributes or dict entries after object creation
- Special class type handling (e.g.,
PyTypeand its metaclasses) - Post-creation mutations that require
PyRef
Provided Associated Constants§
const __OWN_METHOD_DEFS: &'static [PyMethodDef] = _
Required Associated Types§
Required Methods§
Provided Methods§
Sourcefn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult
The type slot for __new__. Override this only when you need special
behavior beyond simple payload creation.
fn __extend_py_class(ctx: &'static Context, class: &'static Py<PyType>)
fn __extend_slots(slots: &mut PyTypeSlots)
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.