Skip to content

Commit c2ca9a7

Browse files
prefer nb_bool slot in try_to_bool instead of __bool__ (RustPython#6328)
Fixed: RustPython#6113 --------- Signed-off-by: Yash Suthar <[email protected]>
1 parent 2b90e82 commit c2ca9a7

File tree

1 file changed

+32
-27
lines changed

1 file changed

+32
-27
lines changed

crates/vm/src/builtins/bool.rs

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -39,39 +39,44 @@ impl PyObjectRef {
3939
if self.is(&vm.ctx.false_value) {
4040
return Ok(false);
4141
}
42-
let rs_bool = match vm.get_method(self.clone(), identifier!(vm, __bool__)) {
43-
Some(method_or_err) => {
44-
// If descriptor returns Error, propagate it further
45-
let method = method_or_err?;
46-
let bool_obj = method.call((), vm)?;
47-
if !bool_obj.fast_isinstance(vm.ctx.types.bool_type) {
48-
return Err(vm.new_type_error(format!(
49-
"__bool__ should return bool, returned type {}",
50-
bool_obj.class().name()
51-
)));
52-
}
53-
54-
get_value(&bool_obj)
55-
}
56-
None => match vm.get_method(self, identifier!(vm, __len__)) {
42+
let rs_bool = if let Some(nb_bool) = self.class().slots.as_number.boolean.load() {
43+
nb_bool(self.as_object().to_number(), vm)?
44+
} else {
45+
// TODO: Fully implement AsNumber and remove this block
46+
match vm.get_method(self.clone(), identifier!(vm, __bool__)) {
5747
Some(method_or_err) => {
48+
// If descriptor returns Error, propagate it further
5849
let method = method_or_err?;
5950
let bool_obj = method.call((), vm)?;
60-
let int_obj = bool_obj.downcast_ref::<PyInt>().ok_or_else(|| {
61-
vm.new_type_error(format!(
62-
"'{}' object cannot be interpreted as an integer",
51+
if !bool_obj.fast_isinstance(vm.ctx.types.bool_type) {
52+
return Err(vm.new_type_error(format!(
53+
"__bool__ should return bool, returned type {}",
6354
bool_obj.class().name()
64-
))
65-
})?;
66-
67-
let len_val = int_obj.as_bigint();
68-
if len_val.sign() == Sign::Minus {
69-
return Err(vm.new_value_error("__len__() should return >= 0"));
55+
)));
7056
}
71-
!len_val.is_zero()
57+
58+
get_value(&bool_obj)
7259
}
73-
None => true,
74-
},
60+
None => match vm.get_method(self, identifier!(vm, __len__)) {
61+
Some(method_or_err) => {
62+
let method = method_or_err?;
63+
let bool_obj = method.call((), vm)?;
64+
let int_obj = bool_obj.downcast_ref::<PyInt>().ok_or_else(|| {
65+
vm.new_type_error(format!(
66+
"'{}' object cannot be interpreted as an integer",
67+
bool_obj.class().name()
68+
))
69+
})?;
70+
71+
let len_val = int_obj.as_bigint();
72+
if len_val.sign() == Sign::Minus {
73+
return Err(vm.new_value_error("__len__() should return >= 0"));
74+
}
75+
!len_val.is_zero()
76+
}
77+
None => true,
78+
},
79+
}
7580
};
7681
Ok(rs_bool)
7782
}

0 commit comments

Comments
 (0)