From b4aa6d3f283a0eca2d269395a704fbe593c53560 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Thu, 15 Apr 2010 16:00:47 +0200 Subject: [PATCH] transform bool(x) into a type coercion --- Cython/Compiler/Optimize.py | 9 ++++++ tests/run/builtins_truth_test.pyx | 47 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py index 03688bbf..78a81063 100644 --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -1264,6 +1264,15 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform): utility_code = pyobject_as_double_utility_code, py_name = "float") + def _handle_simple_function_bool(self, node, pos_args): + """Transform bool(x) into a type coercion to a boolean. + """ + if len(pos_args) != 1: + self._error_wrong_arg_count('bool', node, pos_args, 1) + return node + return pos_args[0].coerce_to_boolean( + self.current_env()).coerce_to_pyobject(self.current_env()) + ### builtin functions PyObject_GetAttr2_func_type = PyrexTypes.CFuncType( diff --git a/tests/run/builtins_truth_test.pyx b/tests/run/builtins_truth_test.pyx index 6d4b5b12..b30f581f 100644 --- a/tests/run/builtins_truth_test.pyx +++ b/tests/run/builtins_truth_test.pyx @@ -1,4 +1,15 @@ +def bool_list(list obj): + """ + >>> bool_list( [] ) + False + >>> bool_list( [1] ) + True + >>> bool_list(None) + False + """ + return bool(obj) + def if_list(list obj): """ >>> if_list( [] ) @@ -31,6 +42,18 @@ def if_list_literal(t): else: return False + +def bool_tuple(tuple obj): + """ + >>> bool_tuple( () ) + False + >>> bool_tuple( (1,) ) + True + >>> bool_tuple(None) + False + """ + return bool(obj) + def if_tuple(tuple obj): """ >>> if_tuple( () ) @@ -63,9 +86,21 @@ def if_tuple_literal(t): else: return False + b0 = b'' b1 = b'abc' +def bool_bytes(bytes obj): + """ + >>> bool_bytes(b0) + False + >>> bool_bytes(b1) + True + >>> bool_bytes(None) + False + """ + return bool(obj) + def if_bytes(bytes obj): """ >>> if_bytes(b0) @@ -98,9 +133,21 @@ def if_bytes_literal(t): else: return False + u0 = u'' u1 = u'abc' +def bool_unicode(unicode obj): + """ + >>> bool_unicode(u0) + False + >>> bool_unicode(u1) + True + >>> bool_unicode(None) + False + """ + return bool(obj) + def if_unicode(unicode obj): """ >>> if_unicode(u0) -- 2.26.2