Skip to content

Commit d3fedec

Browse files
committed
Adding 'int.__bool__' method
1 parent 2b22cd4 commit d3fedec

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

tests/snippets/numbers.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,7 @@ class A(int):
88
x = A(7)
99
assert x == 7
1010
assert type(x) is A
11+
12+
assert int(2).__bool__() == True
13+
assert int(0.5).__bool__() == False
14+
assert int(-1).__bool__() == True

vm/src/obj/objint.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ impl FromPyObjectRef for BigInt {
9090
}
9191
}
9292

93+
fn int_bool(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
94+
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.int_type()))]);
95+
let result = !BigInt::from_pyobj(zelf).is_zero();
96+
Ok(vm.ctx.new_bool(result))
97+
}
9398
fn int_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
9499
arg_check!(
95100
vm,
@@ -527,6 +532,7 @@ pub fn init(context: &PyContext) {
527532
context.set_attr(&int_type, "__format__", context.new_rustfunc(int_format));
528533
context.set_attr(&int_type, "__truediv__", context.new_rustfunc(int_truediv));
529534
context.set_attr(&int_type, "__xor__", context.new_rustfunc(int_xor));
535+
context.set_attr(&int_type, "__bool__", context.new_rustfunc(int_bool));
530536
context.set_attr(
531537
&int_type,
532538
"bit_length",

0 commit comments

Comments
 (0)