1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
# mode: run
# tag: pep484, numpy, pure3.7
##, warnings
from __future__ import annotations # object[:] cannot be evaluated
import cython
import numpy
def one_dim(a: cython.double[:]):
"""
>>> a = numpy.ones((10,), numpy.double)
>>> one_dim(a)
(2.0, 1)
"""
a[0] *= 2
return a[0], a.ndim
def one_dim_ccontig(a: cython.double[::1]):
"""
>>> a = numpy.ones((10,), numpy.double)
>>> one_dim_ccontig(a)
(2.0, 1)
"""
a[0] *= 2
return a[0], a.ndim
def two_dim(a: cython.double[:,:]):
"""
>>> a = numpy.ones((10, 10), numpy.double)
>>> two_dim(a)
(3.0, 1.0, 2)
"""
a[0,0] *= 3
return a[0,0], a[0,1], a.ndim
@cython.nogil
@cython.cfunc
def _one_dim_nogil_cfunc(a: cython.double[:]) -> cython.double:
a[0] *= 2
return a[0]
def one_dim_nogil_cfunc(a: cython.double[:]):
"""
>>> a = numpy.ones((10,), numpy.double)
>>> one_dim_nogil_cfunc(a)
2.0
"""
with cython.nogil:
result = _one_dim_nogil_cfunc(a)
return result
def generic_object_memoryview(a: object[:]):
"""
>>> a = numpy.ones((10,), dtype=object)
>>> generic_object_memoryview(a)
10
"""
sum = 0
for ai in a:
sum += ai
if cython.compiled:
assert cython.typeof(a) == "object[:]", cython.typeof(a)
return sum
def generic_object_memoryview_contig(a: object[::1]):
"""
>>> a = numpy.ones((10,), dtype=object)
>>> generic_object_memoryview_contig(a)
10
"""
sum = 0
for ai in a:
sum += ai
if cython.compiled:
assert cython.typeof(a) == "object[::1]", cython.typeof(a)
return sum
@cython.cclass
class C:
x: cython.int
def __init__(self, value):
self.x = value
def ext_type_object_memoryview(a: C[:]):
"""
>>> a = numpy.array([C(i) for i in range(10)], dtype=object)
>>> ext_type_object_memoryview(a)
45
"""
sum = 0
for ai in a:
sum += ai.x
if cython.compiled:
assert cython.typeof(a) == "C[:]", cython.typeof(a)
return sum
def ext_type_object_memoryview_contig(a: C[::1]):
"""
>>> a = numpy.array([C(i) for i in range(10)], dtype=object)
>>> ext_type_object_memoryview_contig(a)
45
"""
sum = 0
for ai in a:
sum += ai.x
if cython.compiled:
assert cython.typeof(a) == "C[::1]", cython.typeof(a)
return sum
|