Skip to content

Commit 7b921c9

Browse files
committed
Fetch type name dynamically on cast errors
1 parent 55d379c commit 7b921c9

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

newsfragments/5387.changed.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fetch type name dynamically on cast errors instead of using `PyTypeInfo::NAME`

src/instance.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use crate::{
1212
PyRefMut, PyTypeInfo, Python,
1313
};
1414
use crate::{internal::state, PyTypeCheck};
15+
use std::borrow::Cow;
1516
use std::marker::PhantomData;
1617
use std::mem::ManuallyDrop;
1718
use std::ops::Deref;
@@ -264,7 +265,7 @@ impl<'py, T> Bound<'py, T> {
264265
// Safety: is_exact_instance_of is responsible for ensuring that the type is correct
265266
Ok(unsafe { any.cast_unchecked() })
266267
} else {
267-
Err(DowncastError::new(any, U::NAME))
268+
Err(DowncastError::new(any, type_name::<U>(any.py())))
268269
}
269270
}
270271

@@ -286,7 +287,8 @@ impl<'py, T> Bound<'py, T> {
286287
// Safety: is_exact_instance_of is responsible for ensuring that the type is correct
287288
Ok(unsafe { any.cast_into_unchecked() })
288289
} else {
289-
Err(DowncastIntoError::new(any, U::NAME))
290+
let to = type_name::<U>(any.py());
291+
Err(DowncastIntoError::new(any, to))
290292
}
291293
}
292294

@@ -2217,6 +2219,13 @@ impl<T> Py<T> {
22172219
}
22182220
}
22192221

2222+
fn type_name<T: PyTypeInfo>(py: Python<'_>) -> Cow<'static, str> {
2223+
T::type_object(py)
2224+
.name()
2225+
.map(|name| Cow::Owned(name.to_string_lossy().into_owned()))
2226+
.unwrap_or(Cow::Borrowed("unknown type"))
2227+
}
2228+
22202229
#[cfg(test)]
22212230
mod tests {
22222231
use super::{Bound, IntoPyObject, Py};

0 commit comments

Comments
 (0)