Skip to content

Improve __bool__ #1354

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion tests/snippets/bools.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,39 @@ def __len__(self):


with assertRaises(TypeError):
bool(TestLenThrowError())
bool(TestLenThrowError())

# Verify that TypeError occurs when bad things are returned
# from __bool__(). This isn't really a bool test, but
# it's related.
def check(o):
with assertRaises(TypeError):
bool(o)

class Foo(object):
def __bool__(self):
return self
check(Foo())

class Bar(object):
def __bool__(self):
return "Yes"
check(Bar())

class Baz(int):
def __bool__(self):
return self
check(Baz())

# __bool__() must return a bool not an int
class Spam(int):
def __bool__(self):
return 1
check(Spam())

class Eggs:
def __len__(self):
return -1

with assertRaises(ValueError):
bool(Eggs())
27 changes: 18 additions & 9 deletions vm/src/obj/objbool.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use num_bigint::Sign;
use num_traits::Zero;

use crate::function::PyFuncArgs;
Expand Down Expand Up @@ -29,22 +30,30 @@ pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
// If descriptor returns Error, propagate it further
let method = method_or_err?;
let bool_obj = vm.invoke(&method, PyFuncArgs::default())?;
match bool_obj.payload::<PyInt>() {
Some(int_obj) => !int_obj.as_bigint().is_zero(),
None => {
return Err(vm.new_type_error(format!(
"__bool__ should return bool, returned type {}",
bool_obj.class().name
)))
}
if !objtype::isinstance(&bool_obj, &vm.ctx.bool_type()) {
return Err(vm.new_type_error(format!(
"__bool__ should return bool, returned type {}",
bool_obj.class().name
)));
}

get_value(&bool_obj)
}
None => match vm.get_method(obj.clone(), "__len__") {
Some(method_or_err) => {
let method = method_or_err?;
let bool_obj = vm.invoke(&method, PyFuncArgs::default())?;
match bool_obj.payload::<PyInt>() {
Some(int_obj) => !int_obj.as_bigint().is_zero(),
Some(int_obj) => {
let len_val = int_obj.as_bigint();
if len_val.sign() == Sign::Minus {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we prefer to have if-else block than this pattern?

if len_val.sign() == Sign::Minus {
   Err(
      vm.new_value_error("__len__() should return >= 0".to_string())
    )
} else {
    !len_val.is_zero()
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would still have to return the error, as the result of that expression is a bool and not a Result.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, it must escape from the function, i got it.

return Err(
vm.new_value_error("__len__() should return >= 0".to_string())
);
}

!len_val.is_zero()
}
None => {
return Err(vm.new_type_error(format!(
"{} object cannot be interpreted as integer",
Expand Down