transform bool(x) into a type coercion
authorStefan Behnel <scoder@users.berlios.de>
Thu, 15 Apr 2010 14:00:47 +0000 (16:00 +0200)
committerStefan Behnel <scoder@users.berlios.de>
Thu, 15 Apr 2010 14:00:47 +0000 (16:00 +0200)
Cython/Compiler/Optimize.py
tests/run/builtins_truth_test.pyx

index 03688bbfda70d6bd8edcfc95ee7f9189f47611cb..78a8106352f2366f23cb5113d80b72f9bee373dd 100644 (file)
@@ -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(
index 6d4b5b12fe5c3f65a4e63a41f584ffc08f86e1f8..b30f581ff19954dd62155c323575ce041d19dcb8 100644 (file)
@@ -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)