MCPcopy Index your code
hub / github.com/RustPython/RustPython / try_to_bool

Method try_to_bool

crates/vm/src/builtins/bool.rs:37–66  ·  view source on GitHub ↗

Convert Python bool into Rust bool.

(self, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

35impl PyObjectRef {
36 /// Convert Python bool into Rust bool.
37 pub fn try_to_bool(self, vm: &VirtualMachine) -> PyResult<bool> {
38 if self.is(&vm.ctx.true_value) {
39 return Ok(true);
40 }
41 if self.is(&vm.ctx.false_value) {
42 return Ok(false);
43 }
44
45 let slots = &self.class().slots;
46
47 // 1. Try nb_bool slot first
48 if let Some(nb_bool) = slots.as_number.boolean.load() {
49 return nb_bool(self.as_object().number(), vm);
50 }
51
52 // 2. Try mp_length slot (mapping protocol)
53 if let Some(mp_length) = slots.as_mapping.length.load() {
54 let len = mp_length(self.as_object().mapping_unchecked(), vm)?;
55 return Ok(len != 0);
56 }
57
58 // 3. Try sq_length slot (sequence protocol)
59 if let Some(sq_length) = slots.as_sequence.length.load() {
60 let len = sq_length(self.as_object().sequence_unchecked(), vm)?;
61 return Ok(len != 0);
62 }
63
64 // 4. Default: objects without __bool__ or __len__ are truthy
65 Ok(true)
66 }
67}
68
69#[pyclass(name = "bool", module = false, base = PyInt, ctx = "bool_type")]

Callers 15

acquireMethod · 0.80
py_initMethod · 0.80
sendMethod · 0.80
cancelMethod · 0.80
task_step_handle_resultFunction · 0.80
all_tasksFunction · 0.80
is_coroutineFunction · 0.80
stack_effectFunction · 0.80
py_newMethod · 0.80
try_from_objectMethod · 0.80
from_argsMethod · 0.80
try_read_close_notifyMethod · 0.80

Calls 7

isMethod · 0.80
numberMethod · 0.80
mapping_uncheckedMethod · 0.80
sequence_uncheckedMethod · 0.80
classMethod · 0.45
loadMethod · 0.45
as_objectMethod · 0.45

Tested by

no test coverage detected