🌐 AI搜索 & 代理 主页
Skip to content

Commit 8db2660

Browse files
committed
PyBool downcastable_from
1 parent 88634de commit 8db2660

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

crates/vm/src/builtins/bool.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::common::format::FormatSpec;
33
use crate::{
44
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject,
55
VirtualMachine,
6-
class::PyClassImpl,
6+
class::{PyClassImpl, StaticType},
77
convert::{IntoPyException, ToPyObject, ToPyResult},
88
function::OptionalArg,
99
identifier,
@@ -22,10 +22,15 @@ impl ToPyObject for bool {
2222

2323
impl<'a> TryFromBorrowedObject<'a> for bool {
2424
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
25-
if obj.fast_isinstance(vm.ctx.types.int_type) {
26-
Ok(get_value(obj))
27-
} else {
28-
Err(vm.new_type_error(format!("Expected type bool, not {}", obj.class().name())))
25+
// Python takes integers as a legit bool value
26+
match obj.downcast_ref::<PyInt>() {
27+
Some(int_obj) => {
28+
let int_val = int_obj.as_bigint();
29+
Ok(!int_val.is_zero())
30+
}
31+
None => {
32+
Err(vm.new_type_error(format!("Expected type bool, not {}", obj.class().name())))
33+
}
2934
}
3035
}
3136
}
@@ -93,6 +98,10 @@ impl PyPayload for PyBool {
9398
std::any::TypeId::of::<PyInt>()
9499
}
95100

101+
fn downcastable_from(obj: &PyObject) -> bool {
102+
obj.class().is(PyBool::static_type())
103+
}
104+
96105
fn try_downcast_from(obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
97106
if obj.class().is(vm.ctx.types.bool_type) {
98107
return Ok(());

0 commit comments

Comments
 (0)