Skip to content

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

Open
@Person-93

Description

@Person-93

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions