Skip to content

Commit

Permalink
Merge #2979
Browse files Browse the repository at this point in the history
2979: allow `create_exception!` to place the exception in a `dotted.module` r=adamreichold a=davidhewitt

Closes #2946 

Credit fully to `@BlueGlassBlock`

Co-authored-by: David Hewitt <[email protected]>
  • Loading branch information
bors[bot] and davidhewitt authored Feb 22, 2023
2 parents 12ce8d2 + f239d2d commit 7cffc92
Show file tree
Hide file tree
Showing 2 changed files with 22 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.
24 changes: 21 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,24 @@ 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 7cffc92

Please sign in to comment.