23 def h(double a, double b):
33 from libc cimport stdlib
40 cdef char* buf = <char*>stdlib.malloc(10)
74 print a.attr, a.attr2, b.attr
77 cdef int identity(int value): return value
84 cdef char* buf = <char*>stdlib.malloc(10)
87 a.buf[identity(1)] = 0
88 (a.buf + identity(4) - <int>(2*get_2() - 1))[get_2() - 2*identity(1)] += 10
94 print u"side effect", x
97 cdef int c_side_effect(int x):
98 print u"c side effect", x
101 def test_side_effects():
103 >>> test_side_effects()
108 ([0, 11, 102, 3, 4], [0, 1, 2, 13, 104])
110 cdef object a = list(range(5))
111 a[side_effect(1)] += 10
112 a[c_side_effect(2)] += 100
115 for i from 0 <= i < 5:
117 b[side_effect(3)] += 10
118 b[c_side_effect(4)] += 100
119 return a, [b[i] for i from 0 <= i < 5]
121 @cython.cdivision(True)
122 def test_inplace_cdivision(int a, int b):
124 >>> test_inplace_cdivision(13, 10)
126 >>> test_inplace_cdivision(13, -10)
128 >>> test_inplace_cdivision(-13, 10)
130 >>> test_inplace_cdivision(-13, -10)
136 @cython.cdivision(False)
137 def test_inplace_pydivision(int a, int b):
139 >>> test_inplace_pydivision(13, 10)
141 >>> test_inplace_pydivision(13, -10)
143 >>> test_inplace_pydivision(-13, 10)
145 >>> test_inplace_pydivision(-13, -10)
151 def test_complex_inplace(double complex x, double complex y):
153 >>> test_complex_inplace(1, 1)
155 >>> test_complex_inplace(2, 3)
157 >>> test_complex_inplace(2+3j, 4+5j)
165 # The following is more subtle than one might expect.
177 cdef struct ArrayOfA:
180 def nested_struct_assignment():
182 >>> nested_struct_assignment()
187 assert nested.a.value == 5
190 nested.a.inner.x += 10
191 assert nested.a.inner.x == 15
193 def nested_array_assignment():
195 >>> nested_array_assignment()
201 array.a[c_side_effect(0)].value += 3
202 assert array.a[0].value == 5
204 array.a[1].inner.x = 5
205 array.a[c_side_effect(1)].inner.x += 10
206 assert array.a[1].inner.x == 15
208 cdef class VerboseDict(object):
211 def __init__(self, name, **kwds):
214 def __getitem__(self, key):
215 print self.name, "__getitem__", key
216 return self.dict[key]
217 def __setitem__(self, key, value):
218 print self.name, "__setitem__", key, value
219 self.dict[key] = value
221 return repr(self.name)
223 def deref_and_increment(o, key):
225 >>> deref_and_increment({'a': 1}, 'a')
227 >>> v = VerboseDict('v', a=10)
228 >>> deref_and_increment(v, 'a')
233 o[side_effect(key)] += 1
235 def double_deref_and_increment(o, key1, key2):
237 >>> v = VerboseDict('v', a=10)
238 >>> w = VerboseDict('w', vkey=v)
239 >>> double_deref_and_increment(w, 'vkey', 'a')
246 o[side_effect(key1)][side_effect(key2)] += 1
248 def conditional_inplace(value, a, condition, b):
250 >>> conditional_inplace([1, 2, 3], [100], True, [200])
252 >>> conditional_inplace([1, 2, 3], [100], False, [200])
255 value += a if condition else b