pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Subclass defined in Python does not run `__init__` if `new` returns `PyResult<Py<Self>>`

Open Person-93 opened this issue 9 months ago • 0 comments

Bug Description

When a pyclass's new function returns PyResult<Py<Self>>, subclasses defined in python do not run their __init__ functions.

Steps to Reproduce

Write the base class in rust:

#[pyclass(subclass)]
struct BaseClass;

#[pymethods]
impl BaseClass {
    #[new]
    fn py_new(py: Python) -> PyResult<Py<Self>> {
        Ok(Bound::new(py, Self)?.unbind())
    }
}

#[pymodule]
fn some_module(m: &Bound<PyModule>) -> PyResult<()> {
    m.add_class::<BaseClass>()?;

    Ok(())
}

Write a subclass in python:

from some_module import BaseClass


class SubClass(BaseClass):
    def __new__(cls, *args):
        return super().__new__(cls)

    def __init__(self):
        print("in init") 


obj = SubClass()

Backtrace


Your operating system and version

Debian 12

Your Python version (python --version)

Python 3.12.9

Your Rust version (rustc --version)

rustc 1.85.0 (4d91de4e4 2025-02-17)

Your PyO3 version

0.24.0

How did you install python? Did you use a virtualenv?

pyenv

Additional Info

I am not sure if this is related, but if I add print(type(obj)) to the end of the python code, it says that it's an instance of BaseClass not SubClass.

Person-93 avatar Mar 24 '25 16:03 Person-93