@@ -12,6 +12,7 @@ use crate::{
12
12
PyRefMut , PyTypeInfo , Python ,
13
13
} ;
14
14
use crate :: { internal:: state, PyTypeCheck } ;
15
+ use std:: borrow:: Cow ;
15
16
use std:: marker:: PhantomData ;
16
17
use std:: mem:: ManuallyDrop ;
17
18
use std:: ops:: Deref ;
@@ -264,7 +265,7 @@ impl<'py, T> Bound<'py, T> {
264
265
// Safety: is_exact_instance_of is responsible for ensuring that the type is correct
265
266
Ok ( unsafe { any. cast_unchecked ( ) } )
266
267
} else {
267
- Err ( DowncastError :: new ( any, U :: NAME ) )
268
+ Err ( DowncastError :: new ( any, type_name :: < U > ( any . py ( ) ) ) )
268
269
}
269
270
}
270
271
@@ -286,7 +287,8 @@ impl<'py, T> Bound<'py, T> {
286
287
// Safety: is_exact_instance_of is responsible for ensuring that the type is correct
287
288
Ok ( unsafe { any. cast_into_unchecked ( ) } )
288
289
} else {
289
- Err ( DowncastIntoError :: new ( any, U :: NAME ) )
290
+ let to = type_name :: < U > ( any. py ( ) ) ;
291
+ Err ( DowncastIntoError :: new ( any, to) )
290
292
}
291
293
}
292
294
@@ -2217,6 +2219,13 @@ impl<T> Py<T> {
2217
2219
}
2218
2220
}
2219
2221
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
+
2220
2229
#[ cfg( test) ]
2221
2230
mod tests {
2222
2231
use super :: { Bound , IntoPyObject , Py } ;
0 commit comments