Skip to content

Commit ff13fd8

Browse files
committed
Align error message when no method __bool__ is defined with CPython's general style.
1 parent b1b4410 commit ff13fd8

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/types/boolobject.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,13 @@ impl<'source> FromPyObject<'source> for bool {
8181
return Ok(obj.is_true());
8282
}
8383

84+
let missing_conversion = |obj: &PyAny| {
85+
PyTypeError::new_err(format!(
86+
"object of type '{}' does not define a '__bool__' conversion",
87+
obj.get_type()
88+
))
89+
};
90+
8491
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
8592
unsafe {
8693
let ptr = obj.as_ptr();
@@ -95,14 +102,14 @@ impl<'source> FromPyObject<'source> for bool {
95102
}
96103
}
97104

98-
Err(PyTypeError::new_err("object has no __bool__ magic method"))
105+
Err(missing_conversion(obj))
99106
}
100107

101108
#[cfg(any(Py_LIMITED_API, PyPy))]
102109
{
103110
let meth = obj
104111
.lookup_special(crate::intern!(obj.py(), "__bool__"))?
105-
.ok_or_else(|| PyTypeError::new_err("object has no __bool__ magic method"))?;
112+
.ok_or_else(|| missing_conversion(obj))?;
106113

107114
let obj = meth.call0()?.downcast::<PyBool>()?;
108115
Ok(obj.is_true())
@@ -174,13 +181,13 @@ class D:
174181
let c = module.getattr("C").unwrap().call0().unwrap();
175182
assert_eq!(
176183
c.extract::<bool>().unwrap_err().to_string(),
177-
"TypeError: object has no __bool__ magic method",
184+
"TypeError: object of type '<class 'test.C'>' does not define a '__bool__' conversion",
178185
);
179186

180187
let d = module.getattr("D").unwrap().call0().unwrap();
181188
assert_eq!(
182189
d.extract::<bool>().unwrap_err().to_string(),
183-
"TypeError: object has no __bool__ magic method",
190+
"TypeError: object of type '<class 'test.D'>' does not define a '__bool__' conversion",
184191
);
185192
});
186193
}

0 commit comments

Comments
 (0)