3b2c175f8d
2947: change PyModule::add_class to return an error if class creation fails r=adamreichold a=davidhewitt Related to #2942 At the moment there are panics deep in the `#[pyclass]` machinery when initialising the type fails. This PR adjusts a number of these functions to return `PyResult` instead, so that we can handle the error more appropriately further down the pipeline. For example, take the following snippet: ```rust #[pyclass(extends = PyBool)] struct ExtendsBool; #[pymodule] fn pyo3_scratch(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<ExtendsBool>()?; Ok(()) } ``` Currently, importing this module will fail with a panic: ``` TypeError: type 'bool' is not an acceptable base type thread '<unnamed>' panicked at 'An error occurred while initializing class ExtendsBool', /Users/david/Dev/pyo3/src/pyclass.rs:412:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Traceback (most recent call last): File "<string>", line 1, in <module> File "/Users/david/.virtualenvs/pyo3/lib/python3.10/site-packages/pyo3_scratch/__init__.py", line 1, in <module> from .pyo3_scratch import * pyo3_runtime.PanicException: An error occurred while initializing class ExtendsBool ``` After this PR, this import still fails, but with a slightly cleaner, more Pythonic error: ``` TypeError: type 'bool' is not an acceptable base type The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<string>", line 1, in <module> File "/Users/david/.virtualenvs/pyo3/lib/python3.10/site-packages/pyo3_scratch/__init__.py", line 1, in <module> from .pyo3_scratch import * RuntimeError: An error occurred while initializing class ExtendsBool ``` Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com> Co-authored-by: Adam Reichold <adam.reichold@t-online.de> |
||
---|---|---|
.. | ||
bench_call.rs | ||
bench_dict.rs | ||
bench_err.rs | ||
bench_frompyobject.rs | ||
bench_gil.rs | ||
bench_intern.rs | ||
bench_list.rs | ||
bench_pyclass.rs | ||
bench_pyobject.rs | ||
bench_set.rs | ||
bench_tuple.rs |