Skip to content

Support for multiple inheritance in create_exception #4979

Description

@kylebarron

create_exception allows taking a base, which the new exception subclasses from.

Is there some way to create a new exception which uses multiple inheritance from two parents?

Activity

  1. lukasbindreiter commented on Jun 24, 2025

    @lukasbindreiter

    create_exception eventually ends up here:

    pyo3/src/err/mod.rs

    Lines 388 to 400 in e486930

    /// This function returns an error if `name` is not of the form `<module>.<ExceptionName>`.
    pub fn new_type<'py>(
    py: Python<'py>,
    name: &CStr,
    doc: Option<&CStr>,
    base: Option<&Bound<'py, PyType>>,
    dict: Option<PyObject>,
    ) -> PyResult<Py<PyType>> {
    let base: *mut ffi::PyObject = match base {
    None => std::ptr::null_mut(),
    Some(obj) => obj.as_ptr(),
    };

    which then in turn calls this C function:

    pub fn PyErr_NewExceptionWithDoc(
    name: *const c_char,
    doc: *const c_char,
    base: *mut PyObject,
    dict: *mut PyObject,
    ) -> *mut PyObject;

    The python docs for this function mentions that:

    The base argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes

    So I think multiple base classes for exceptions should in theory be possible.

  2. kylebarron commented on Jun 24, 2025

    @kylebarron
    ContributorAuthor

    Yes it should be possible if you using the Python C FFI bindings, but that's too easy to misuse if you don't know Python's C API well, so I'd prefer waiting for a safe wrapper to exist.

  3. lukasbindreiter commented on Jun 25, 2025

    @lukasbindreiter

    Yeah, I was just checking out of curiosity how hard it would be to add support for them in PyO3 (by adapting create_exception or offering a separate function for it) - didn't mean for users of PyO3 to bypass this and go directly to the C API in unsafe rust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions