From 78b216f520c7bf2f94f47bfcaf2a110e71a510a2 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Thu, 25 Nov 2010 07:03:10 +0100 Subject: [PATCH] fix 'bool(x)' to always return 0 or 1 instead of plain 'x' --- Cython/Compiler/Optimize.py | 8 ++++++-- tests/run/boolean_context.pyx | 11 ++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py index c8abd0d4..c39c9e74 100644 --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -1860,8 +1860,12 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform): self._error_wrong_arg_count('bool', node, pos_args, '0 or 1') return node else: - return pos_args[0].coerce_to_boolean( - self.current_env()).coerce_to_pyobject(self.current_env()) + # => !!(x) to make sure it's exactly 0 or 1 + operand = pos_args[0].coerce_to_boolean(self.current_env()) + operand = ExprNodes.NotNode(node.pos, operand = operand) + operand = ExprNodes.NotNode(node.pos, operand = operand) + # coerce back to Python object as that's the result we are expecting + return operand.coerce_to_pyobject(self.current_env()) ### builtin functions diff --git a/tests/run/boolean_context.pyx b/tests/run/boolean_context.pyx index f6d59e1b..21269f22 100644 --- a/tests/run/boolean_context.pyx +++ b/tests/run/boolean_context.pyx @@ -5,4 +5,13 @@ def test(): True """ cdef int x = 5 - print bool(x) + return bool(x) + +def test_bool_and_int(): + """ + >>> test_bool_and_int() + 1 + """ + cdef int x = 5 + cdef int b = bool(x) + return b -- 2.26.2