Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/6209.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved introspection for `create_exception!` types, and stub generation now works for them.
65 changes: 65 additions & 0 deletions pyo3-macros-backend/src/exception.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use proc_macro2::TokenStream;
use syn::parse::Parse;
use syn::{Expr, Ident, Path, Token};

use crate::introspection::class_introspection_code;
use crate::py_expr::PyExpr;
use crate::utils::{PyO3CratePath, PythonDoc, StrOrExpr};

pub struct ExceptionIntrospectionArgs {
crate_path: Path,
name: Ident,
base: Path, // the super class of this exception
doc: Option<Expr>,
}

impl Parse for ExceptionIntrospectionArgs {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let crate_path = input.parse()?;
input.parse::<Token![,]>()?;
let name = input.parse()?;
input.parse::<Token![,]>()?;
let base = input.parse()?;
let doc = if input.parse::<Option<Token![,]>>()?.is_some() {
Some(input.parse()?)
} else {
None
};

Ok(Self {
crate_path,
name,
base,
doc,
})
}
}

pub fn build_exception_introspection(
ExceptionIntrospectionArgs {
crate_path,
name,
base,
doc,
}: ExceptionIntrospectionArgs,
) -> TokenStream {
let doc = doc.map(|doc| PythonDoc {
parts: vec![StrOrExpr::Expr(doc)],
});
class_introspection_code(
&PyO3CratePath::Given(crate_path),
&name,
&name.to_string(),
Some(PyExpr::from_type(
syn::TypePath {
qself: None,
path: base,
}
.into(),
None,
)),
false,
None,
doc.as_ref(),
)
}
4 changes: 4 additions & 0 deletions pyo3-macros-backend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ mod utils;
mod attributes;
mod combine_errors;
mod derive_attributes;
#[cfg(feature = "experimental-inspect")]
mod exception;
mod frompyobject;
mod intopyobject;
#[cfg(feature = "experimental-inspect")]
Expand All @@ -27,6 +29,8 @@ mod pyimpl;
mod pymethod;
mod quotes;

#[cfg(feature = "experimental-inspect")]
pub use exception::{build_exception_introspection, ExceptionIntrospectionArgs};
pub use frompyobject::build_derive_from_pyobject;
pub use intopyobject::build_derive_into_pyobject;
pub use module::{pymodule_function_impl, pymodule_module_impl, PyModuleOptions};
Expand Down
8 changes: 8 additions & 0 deletions pyo3-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ pub fn pymethods(attr: TokenStream, input: TokenStream) -> TokenStream {
pymethods_impl(attr, input, methods_type)
}

#[doc(hidden)]
#[proc_macro]
#[cfg(feature = "experimental-inspect")]
pub fn exception_introspection_impl(input: TokenStream) -> TokenStream {
let args = parse_macro_input!(input as pyo3_macros_backend::ExceptionIntrospectionArgs);
pyo3_macros_backend::build_exception_introspection(args).into()
}

/// A proc macro used to expose Rust functions to Python.
///
/// Functions annotated with `#[pyfunction]` can also be annotated with the following `#[pyo3]`
Expand Down
6 changes: 2 additions & 4 deletions pytests/stubs/exception.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from _typeshed import Incomplete
from typing import Any
class MyValueError(ValueError): ...

def raise_my_value_error() -> None: ...
def return_my_value_error() -> Any: ...
def return_my_value_error() -> MyValueError: ...
def return_pyerr() -> BaseException: ...
def return_value_error() -> ValueError: ...
def __getattr__(name: str) -> Incomplete: ...
20 changes: 20 additions & 0 deletions src/exceptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ macro_rules! create_exception {
$crate::impl_exception_boilerplate!($name);

$crate::create_exception_type_object!($module, $name, $base, None);

$crate::create_exception_introspection!($name, $base);
};
($module: expr, $name: ident, $base: ty, $doc: expr) => {
#[repr(transparent)]
Expand All @@ -180,6 +182,8 @@ macro_rules! create_exception {
$crate::impl_exception_boilerplate!($name);

$crate::create_exception_type_object!($module, $name, $base, Some($doc));

$crate::create_exception_introspection!($name, $base, $doc);
};
}

Expand Down Expand Up @@ -249,6 +253,22 @@ macro_rules! create_exception_type_object {
};
}

#[cfg(not(all(feature = "experimental-inspect", feature = "macros")))]
#[doc(hidden)]
#[macro_export]
macro_rules! create_exception_introspection(
($name: ident, $base: ty $(, $doc: expr)?) => {};
);

#[cfg(all(feature = "experimental-inspect", feature = "macros"))]
#[doc(hidden)]
#[macro_export]
macro_rules! create_exception_introspection(
($name: ident, $base: ty $(, $doc: expr)?) => {
$crate::exception_introspection_impl!($crate, $name, $base $(, $doc)?);
};
);

/// Adds a TYPE_HINT constant if the `experimental-inspect` feature is enabled.
#[cfg(not(feature = "experimental-inspect"))]
#[doc(hidden)]
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,10 @@ pub use pyo3_macros::{
#[cfg(feature = "macros")]
pub use pyo3_macros::pyclass;

#[doc(hidden)]
#[cfg(all(feature = "macros", feature = "experimental-inspect"))]
pub use pyo3_macros::exception_introspection_impl;

#[cfg(feature = "macros")]
#[macro_use]
mod macros;
Expand Down