Skip to content

Commit

Permalink
allow create_exception! to place the exception in a dotted.module
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Feb 22, 2023
1 parent 064e52a commit 9fb6a66
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions newsfragments/2979.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow `create_exception!` to take a `dotted.module` to place the exception in a submodule.
21 changes: 18 additions & 3 deletions src/exceptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ macro_rules! import_exception {
///
#[macro_export]
macro_rules! create_exception {
($module: ident, $name: ident, $base: ty) => {
($module: expr, $name: ident, $base: ty) => {
#[repr(transparent)]
#[allow(non_camel_case_types)] // E.g. `socket.herror`
pub struct $name($crate::PyAny);
Expand All @@ -210,7 +210,7 @@ macro_rules! create_exception {

$crate::create_exception_type_object!($module, $name, $base, ::std::option::Option::None);
};
($module: ident, $name: ident, $base: ty, $doc: expr) => {
($module: expr, $name: ident, $base: ty, $doc: expr) => {
#[repr(transparent)]
#[allow(non_camel_case_types)] // E.g. `socket.herror`
#[doc = $doc]
Expand All @@ -232,7 +232,7 @@ macro_rules! create_exception {
#[doc(hidden)]
#[macro_export]
macro_rules! create_exception_type_object {
($module: ident, $name: ident, $base: ty, $doc: expr) => {
($module: expr, $name: ident, $base: ty, $doc: expr) => {
$crate::pyobject_native_type_core!(
$name,
*$name::type_object_raw($crate::Python::assume_gil_acquired()),
Expand Down Expand Up @@ -876,6 +876,21 @@ mod tests {
});
}

#[test]
fn custom_exception_dotted_module() {
create_exception!(mymodule.exceptions, CustomError, PyException);
Python::with_gil(|py| {
let error_type = py.get_type::<CustomError>();
let ctx = [("CustomError", error_type)].into_py_dict(py);
let type_description: String = py
.eval("str(CustomError)", None, Some(ctx))
.unwrap()
.extract()
.unwrap();
assert_eq!(type_description, "<class 'mymodule.exceptions.CustomError'>");
});
}

#[test]
fn custom_exception_doc() {
create_exception!(mymodule, CustomError, PyException, "Some docs");
Expand Down

0 comments on commit 9fb6a66

Please sign in to comment.