🌐 AI搜索 & 代理 主页
Skip to content
Draft
Prev Previous commit
Next Next commit
New signature for py_new
  • Loading branch information
youknowone committed Dec 11, 2025
commit 19d5b67406813f91718316153a429d4fa727a837
10 changes: 5 additions & 5 deletions crates/stdlib/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ mod array {
atomic_func,
builtins::{
PositionIterInternal, PyByteArray, PyBytes, PyBytesRef, PyDictRef, PyFloat,
PyGenericAlias, PyInt, PyList, PyListRef, PyStr, PyStrRef, PyTupleRef, PyTypeRef,
PyGenericAlias, PyInt, PyList, PyListRef, PyStr, PyStrRef, PyTupleRef, PyType,
PyTypeRef,
},
class_or_notimplemented,
convert::{ToPyObject, ToPyResult, TryFromBorrowedObject, TryFromObject},
Expand Down Expand Up @@ -651,10 +652,10 @@ mod array {
type Args = (ArrayNewArgs, KwArgs);

fn py_new(
cls: PyTypeRef,
cls: &Py<PyType>,
(ArrayNewArgs { spec, init }, kwargs): Self::Args,
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<Self> {
let spec = spec.as_str().chars().exactly_one().map_err(|_| {
vm.new_type_error("array() argument 1 must be a unicode character, not str")
})?;
Expand Down Expand Up @@ -701,8 +702,7 @@ mod array {
}
}

let zelf = Self::from(array).into_ref_with_type(vm, cls)?;
Ok(zelf.into())
Ok(Self::from(array))
}
}

Expand Down
20 changes: 8 additions & 12 deletions crates/stdlib/src/bz2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ mod _bz2 {
DecompressArgs, DecompressError, DecompressState, DecompressStatus, Decompressor,
};
use crate::vm::{
VirtualMachine,
builtins::{PyBytesRef, PyTypeRef},
Py, VirtualMachine,
builtins::{PyBytesRef, PyType, PyTypeRef},
common::lock::PyMutex,
function::{ArgBytesLike, OptionalArg},
object::{PyPayload, PyResult},
Expand Down Expand Up @@ -61,12 +61,10 @@ mod _bz2 {
impl Constructor for BZ2Decompressor {
type Args = ();

fn py_new(cls: PyTypeRef, _: Self::Args, vm: &VirtualMachine) -> PyResult {
Self {
fn py_new(_cls: &Py<PyType>, _: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
Ok(Self {
state: PyMutex::new(DecompressState::new(Decompress::new(false), vm)),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
})
}
}

Expand Down Expand Up @@ -132,7 +130,7 @@ mod _bz2 {
impl Constructor for BZ2Compressor {
type Args = (OptionalArg<i32>,);

fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
let (compresslevel,) = args;
// TODO: seriously?
// compresslevel.unwrap_or(bzip2::Compression::best().level().try_into().unwrap());
Expand All @@ -144,14 +142,12 @@ mod _bz2 {
}
};

Self {
Ok(Self {
state: PyMutex::new(CompressorState {
flushed: false,
encoder: Some(BzEncoder::new(Vec::new(), level)),
}),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
})
}
}

Expand Down
24 changes: 15 additions & 9 deletions crates/stdlib/src/contextvars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ thread_local! {
mod _contextvars {
use crate::vm::{
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func,
builtins::{PyGenericAlias, PyStrRef, PyTypeRef},
builtins::{PyGenericAlias, PyStrRef, PyType, PyTypeRef},
class::StaticType,
common::hash::PyHash,
function::{ArgCallable, FuncArgs, OptionalArg},
Expand Down Expand Up @@ -244,8 +244,8 @@ mod _contextvars {

impl Constructor for PyContext {
type Args = ();
fn py_new(_cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
Ok(Self::empty(vm).into_pyobject(vm))
fn py_new(_cls: &Py<PyType>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
Ok(Self::empty(vm))
}
}

Expand Down Expand Up @@ -488,22 +488,28 @@ mod _contextvars {

impl Constructor for ContextVar {
type Args = ContextVarOptions;
fn py_new(_cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {

fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let options: ContextVarOptions = args.bind(vm)?;
let var = Self {
name: args.name.to_string(),
default: args.default.into_option(),
name: options.name.to_string(),
default: options.default.into_option(),
cached_id: 0.into(),
cached: AtomicCell::new(None),
hash: UnsafeCell::new(0),
};
let py_var = var.into_ref(&vm.ctx);
let py_var = var.into_ref_with_type(vm, cls)?;

unsafe {
// SAFETY: py_var is not exposed to python memory model yet
*py_var.hash.get() = Self::generate_hash(&py_var, vm)
};
Ok(py_var.into())
}

fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
unreachable!("use slot_new")
}
}

impl std::hash::Hash for ContextVar {
Expand Down Expand Up @@ -578,8 +584,8 @@ mod _contextvars {
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Err(vm.new_runtime_error("Tokens can only be created by ContextVars"))
}
fn py_new(_cls: PyTypeRef, _args: Self::Args, _vm: &VirtualMachine) -> PyResult {
unreachable!()
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
unreachable!("use slot_new")
}
}

Expand Down
6 changes: 2 additions & 4 deletions crates/stdlib/src/csv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,8 @@ mod _csv {
impl Constructor for PyDialect {
type Args = PyObjectRef;

fn py_new(cls: PyTypeRef, ctx: Self::Args, vm: &VirtualMachine) -> PyResult {
Self::try_from_object(vm, ctx)?
.into_ref_with_type(vm, cls)
.map(Into::into)
fn py_new(_cls: &Py<PyType>, ctx: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
Self::try_from_object(vm, ctx)
}
}
#[pyclass(with(Constructor))]
Expand Down
8 changes: 3 additions & 5 deletions crates/stdlib/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ mod _json {
impl Constructor for JsonScanner {
type Args = PyObjectRef;

fn py_new(cls: PyTypeRef, ctx: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(_cls: &Py<PyType>, ctx: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
let strict = ctx.get_attr("strict", vm)?.try_to_bool(vm)?;
let object_hook = vm.option_if_none(ctx.get_attr("object_hook", vm)?);
let object_pairs_hook = vm.option_if_none(ctx.get_attr("object_pairs_hook", vm)?);
Expand All @@ -52,17 +52,15 @@ mod _json {
};
let parse_constant = ctx.get_attr("parse_constant", vm)?;

Self {
Ok(Self {
strict,
object_hook,
object_pairs_hook,
parse_float,
parse_int,
parse_constant,
ctx,
}
.into_ref_with_type(vm, cls)
.map(Into::into)
})
}
}

Expand Down
17 changes: 7 additions & 10 deletions crates/stdlib/src/lzma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ mod _lzma {
LZMA_PRESET_LEVEL_MASK as PRESET_LEVEL_MASK,
};
use rustpython_common::lock::PyMutex;
use rustpython_vm::builtins::{PyBaseExceptionRef, PyBytesRef, PyTypeRef};
use rustpython_vm::builtins::{PyBaseExceptionRef, PyBytesRef, PyType, PyTypeRef};
use rustpython_vm::convert::ToPyException;
use rustpython_vm::function::ArgBytesLike;
use rustpython_vm::types::Constructor;
use rustpython_vm::{PyObjectRef, PyPayload, PyResult, VirtualMachine};
use rustpython_vm::{Py, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use std::fmt;
use xz2::stream::{Action, Check, Error, Filters, LzmaOptions, Status, Stream};

Expand Down Expand Up @@ -148,7 +148,7 @@ mod _lzma {
impl Constructor for LZMADecompressor {
type Args = LZMADecompressorConstructorArgs;

fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
if args.format == FORMAT_RAW && args.mem_limit.is_some() {
return Err(vm.new_value_error("Cannot specify memory limit with FORMAT_RAW"));
}
Expand All @@ -161,15 +161,13 @@ mod _lzma {
// TODO: FORMAT_RAW
_ => return Err(new_lzma_error("Invalid format", vm)),
};
Self {
Ok(Self {
state: PyMutex::new(DecompressState::new(
stream_result
.map_err(|_| new_lzma_error("Failed to initialize decoder", vm))?,
vm,
)),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
})
}
}

Expand Down Expand Up @@ -366,7 +364,7 @@ mod _lzma {
impl Constructor for LZMACompressor {
type Args = LZMACompressorConstructorArgs;

fn py_new(_cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
let preset = args.preset.unwrap_or(PRESET_DEFAULT);
#[allow(clippy::unnecessary_cast)]
if args.format != FORMAT_XZ as i32
Expand All @@ -392,8 +390,7 @@ mod _lzma {
};
Ok(Self {
state: PyMutex::new(CompressState::new(CompressorInner::new(stream))),
}
.into_pyobject(vm))
})
}
}

Expand Down
10 changes: 4 additions & 6 deletions crates/stdlib/src/mmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ mod mmap {
use crate::vm::{
AsObject, FromArgs, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
TryFromBorrowedObject, VirtualMachine, atomic_func,
builtins::{PyBytes, PyBytesRef, PyInt, PyIntRef, PyTypeRef},
builtins::{PyBytes, PyBytesRef, PyInt, PyIntRef, PyType, PyTypeRef},
byte::{bytes_from_object, value_from_object},
convert::ToPyException,
function::{ArgBytesLike, FuncArgs, OptionalArg},
Expand Down Expand Up @@ -388,7 +388,7 @@ mod mmap {
type Args = MmapNewArgs;

#[cfg(unix)]
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
use libc::{MAP_PRIVATE, MAP_SHARED, PROT_READ, PROT_WRITE};

let mut map_size = args.validate_new_args(vm)?;
Expand Down Expand Up @@ -477,7 +477,7 @@ mod mmap {
}()
.map_err(|e| e.to_pyexception(vm))?;

let m_obj = Self {
Ok(Self {
closed: AtomicCell::new(false),
mmap: PyMutex::new(Some(mmap)),
fd: AtomicCell::new(fd.map_or(-1, |fd| fd.into_raw())),
Expand All @@ -486,9 +486,7 @@ mod mmap {
pos: AtomicCell::new(0),
exports: AtomicCell::new(0),
access,
};

m_obj.into_ref_with_type(vm, cls).map(Into::into)
})
}

#[cfg(windows)]
Expand Down
8 changes: 3 additions & 5 deletions crates/stdlib/src/pystruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub(crate) mod _struct {
use crate::vm::{
AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
buffer::{FormatSpec, new_struct_error, struct_error_type},
builtins::{PyBytes, PyStr, PyStrRef, PyTupleRef, PyTypeRef},
builtins::{PyBytes, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef},
function::{ArgBytesLike, ArgMemoryBuffer, PosArgs},
match_class,
protocol::PyIterReturn,
Expand Down Expand Up @@ -241,12 +241,10 @@ pub(crate) mod _struct {
impl Constructor for PyStruct {
type Args = IntoStructFormatBytes;

fn py_new(cls: PyTypeRef, fmt: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(_cls: &Py<PyType>, fmt: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
let spec = fmt.format_spec(vm)?;
let format = fmt.0;
Self { spec, format }
.into_ref_with_type(vm, cls)
.map(Into::into)
Ok(Self { spec, format })
}
}

Expand Down
24 changes: 12 additions & 12 deletions crates/stdlib/src/ssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ mod _ssl {
vm::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
builtins::{PyBaseExceptionRef, PyBytesRef, PyListRef, PyStrRef, PyTypeRef},
builtins::{PyBaseExceptionRef, PyBytesRef, PyListRef, PyStrRef, PyType, PyTypeRef},
convert::IntoPyException,
function::{ArgBytesLike, ArgMemoryBuffer, OptionalArg, PyComparisonValue},
stdlib::warnings,
Expand Down Expand Up @@ -2288,7 +2288,11 @@ mod _ssl {
impl Constructor for PySSLContext {
type Args = (i32,);

fn py_new(cls: PyTypeRef, (protocol,): Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(
_cls: &Py<PyType>,
(protocol,): Self::Args,
vm: &VirtualMachine,
) -> PyResult<Self> {
// Validate protocol
match protocol {
PROTOCOL_TLS | PROTOCOL_TLS_CLIENT | PROTOCOL_TLS_SERVER | PROTOCOL_TLSv1_2
Expand Down Expand Up @@ -2353,7 +2357,7 @@ mod _ssl {
session_cache: shared_session_cache.clone(),
});

PySSLContext {
Ok(PySSLContext {
protocol,
check_hostname: PyRwLock::new(protocol == PROTOCOL_TLS_CLIENT),
verify_mode: PyRwLock::new(default_verify_mode),
Expand Down Expand Up @@ -2388,9 +2392,7 @@ mod _ssl {
accept_count: AtomicUsize::new(0),
session_hits: AtomicUsize::new(0),
selected_ciphers: PyRwLock::new(None),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
})
}
}

Expand Down Expand Up @@ -4107,7 +4109,7 @@ mod _ssl {
impl Constructor for PySSLSocket {
type Args = ();

fn py_new(_cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
fn py_new(_cls: &Py<PyType>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
Err(vm.new_type_error(
"Cannot directly instantiate SSLSocket, use SSLContext.wrap_socket()",
))
Expand Down Expand Up @@ -4204,13 +4206,11 @@ mod _ssl {
impl Constructor for PyMemoryBIO {
type Args = ();

fn py_new(cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
let obj = PyMemoryBIO {
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
Ok(PyMemoryBIO {
buffer: PyMutex::new(Vec::new()),
eof: PyRwLock::new(false),
}
.into_ref_with_type(vm, cls)?;
Ok(obj.into())
})
}
}

Expand Down
Loading