if_else_expr.pyx 1.36 KB
Newer Older
1
# mode: run
2 3 4
# tag: condexpr

cimport cython
5 6

cdef class Foo:
7 8
    cdef dict data

9 10 11
    def __repr__(self):
        return '<Foo>'

Stefan Behnel's avatar
Stefan Behnel committed
12

13 14 15 16 17 18 19 20 21
cpdef test_type_cast(Foo obj, cond):
    """
    # Regression test: obj must be cast to (PyObject *) here
    >>> test_type_cast(Foo(), True)
    [<Foo>]
    >>> test_type_cast(Foo(), False)
    <Foo>
    """
    return [obj] if cond else obj
22 23 24 25 26 27 28 29 30 31 32 33 34


cdef func(Foo foo, dict data):
    return foo, data


@cython.test_fail_if_path_exists('//PyTypeTestNode')
def test_cpp_pyobject_cast(Foo obj1, Foo obj2, cond):
    """
    >>> test_cpp_pyobject_cast(Foo(), Foo(), True)
    (<Foo>, None)
    """
    return func(obj1 if cond else obj2, obj1.data if cond else obj2.data)
35 36 37 38 39 40 41 42 43


def test_charptr_coercion(x):
    """
    >>> print(test_charptr_coercion(True))
    abc
    >>> print(test_charptr_coercion(False))
    def
    """
44
    cdef char* s = b'abc' if x else b'def'
45
    return s.decode('ascii')
Stefan Behnel's avatar
Stefan Behnel committed
46 47 48 49 50 51 52 53 54 55 56 57


def test_syntax():
    """
    >>> test_syntax()
    (0, 0, 0)
    """
    # Py3 allows the 'else' keyword to directly follow a number
    x = 0 if 1else 1
    y = 0 if 1.0else 1
    z = 0 if 1.else 1
    return x, y, z
58 59 60 61 62 63 64 65 66 67 68 69


from libc cimport math

def test_cfunc_ptrs(double x, bint round_down):
    """
    >>> test_cfunc_ptrs(2.5, round_down=True)
    2.0
    >>> test_cfunc_ptrs(2.5, round_down=False)
    3.0
    """
    return (math.floor if round_down else math.ceil)(x)