Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Gwenaël Samain
cython
Commits
b67e5567
Commit
b67e5567
authored
Feb 15, 2019
by
Stefan Behnel
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Fix line endings.
parent
e6a49ace
Changes
133
Hide whitespace changes
Inline
Side-by-side
Showing
133 changed files
with
1724 additions
and
1724 deletions
+1724
-1724
docs/examples/README.rst
docs/examples/README.rst
+3
-3
docs/examples/quickstart/build/hello.pyx
docs/examples/quickstart/build/hello.pyx
+2
-2
docs/examples/quickstart/build/setup.py
docs/examples/quickstart/build/setup.py
+5
-5
docs/examples/quickstart/cythonize/cdef_keyword.pyx
docs/examples/quickstart/cythonize/cdef_keyword.pyx
+2
-2
docs/examples/quickstart/cythonize/integrate.py
docs/examples/quickstart/cythonize/integrate.py
+10
-10
docs/examples/quickstart/cythonize/integrate_cy.pyx
docs/examples/quickstart/cythonize/integrate_cy.pyx
+12
-12
docs/examples/tutorial/array/clone.pyx
docs/examples/tutorial/array/clone.pyx
+8
-8
docs/examples/tutorial/array/overhead.pyx
docs/examples/tutorial/array/overhead.pyx
+15
-15
docs/examples/tutorial/array/resize.pyx
docs/examples/tutorial/array/resize.pyx
+10
-10
docs/examples/tutorial/array/safe_usage.pyx
docs/examples/tutorial/array/safe_usage.pyx
+6
-6
docs/examples/tutorial/array/unsafe_usage.pyx
docs/examples/tutorial/array/unsafe_usage.pyx
+11
-11
docs/examples/tutorial/cdef_classes/integrate.pyx
docs/examples/tutorial/cdef_classes/integrate.pyx
+14
-14
docs/examples/tutorial/cdef_classes/math_function.py
docs/examples/tutorial/cdef_classes/math_function.py
+7
-7
docs/examples/tutorial/cdef_classes/math_function_2.pyx
docs/examples/tutorial/cdef_classes/math_function_2.pyx
+3
-3
docs/examples/tutorial/cdef_classes/nonecheck.pyx
docs/examples/tutorial/cdef_classes/nonecheck.pyx
+19
-19
docs/examples/tutorial/cdef_classes/sin_of_square.pyx
docs/examples/tutorial/cdef_classes/sin_of_square.pyx
+9
-9
docs/examples/tutorial/cdef_classes/wave_function.pyx
docs/examples/tutorial/cdef_classes/wave_function.pyx
+21
-21
docs/examples/tutorial/clibraries/queue.pyx
docs/examples/tutorial/clibraries/queue.pyx
+9
-9
docs/examples/tutorial/clibraries/queue2.pyx
docs/examples/tutorial/clibraries/queue2.pyx
+11
-11
docs/examples/tutorial/clibraries/test_queue.py
docs/examples/tutorial/clibraries/test_queue.py
+36
-36
docs/examples/tutorial/cython_tutorial/primes_cpp.pyx
docs/examples/tutorial/cython_tutorial/primes_cpp.pyx
+21
-21
docs/examples/tutorial/external/atoi.pyx
docs/examples/tutorial/external/atoi.pyx
+5
-5
docs/examples/tutorial/external/cpdef_sin.pyx
docs/examples/tutorial/external/cpdef_sin.pyx
+7
-7
docs/examples/tutorial/external/keyword_args.pyx
docs/examples/tutorial/external/keyword_args.pyx
+2
-2
docs/examples/tutorial/external/keyword_args_call.pyx
docs/examples/tutorial/external/keyword_args_call.pyx
+7
-7
docs/examples/tutorial/external/libc_sin.pyx
docs/examples/tutorial/external/libc_sin.pyx
+4
-4
docs/examples/tutorial/external/py_version_hex.pyx
docs/examples/tutorial/external/py_version_hex.pyx
+4
-4
docs/examples/tutorial/external/setup.py
docs/examples/tutorial/external/setup.py
+13
-13
docs/examples/tutorial/memory_allocation/malloc.pyx
docs/examples/tutorial/memory_allocation/malloc.pyx
+23
-23
docs/examples/tutorial/memory_allocation/some_memory.pyx
docs/examples/tutorial/memory_allocation/some_memory.pyx
+25
-25
docs/examples/tutorial/numpy/convolve_py.py
docs/examples/tutorial/numpy/convolve_py.py
+43
-43
docs/examples/tutorial/profiling_tutorial/calc_pi.py
docs/examples/tutorial/profiling_tutorial/calc_pi.py
+10
-10
docs/examples/tutorial/profiling_tutorial/calc_pi_2.pyx
docs/examples/tutorial/profiling_tutorial/calc_pi_2.pyx
+13
-13
docs/examples/tutorial/profiling_tutorial/calc_pi_3.pyx
docs/examples/tutorial/profiling_tutorial/calc_pi_3.pyx
+13
-13
docs/examples/tutorial/profiling_tutorial/calc_pi_4.pyx
docs/examples/tutorial/profiling_tutorial/calc_pi_4.pyx
+16
-16
docs/examples/tutorial/profiling_tutorial/often_called.pyx
docs/examples/tutorial/profiling_tutorial/often_called.pyx
+5
-5
docs/examples/tutorial/profiling_tutorial/profile.py
docs/examples/tutorial/profiling_tutorial/profile.py
+10
-10
docs/examples/tutorial/profiling_tutorial/profile_2.py
docs/examples/tutorial/profiling_tutorial/profile_2.py
+13
-13
docs/examples/tutorial/pure/A.py
docs/examples/tutorial/pure/A.py
+14
-14
docs/examples/tutorial/pure/A_equivalent.pyx
docs/examples/tutorial/pure/A_equivalent.pyx
+15
-15
docs/examples/tutorial/pure/annotations.py
docs/examples/tutorial/pure/annotations.py
+5
-5
docs/examples/tutorial/pure/c_arrays.py
docs/examples/tutorial/pure/c_arrays.py
+15
-15
docs/examples/tutorial/pure/cclass.py
docs/examples/tutorial/pure/cclass.py
+16
-16
docs/examples/tutorial/pure/compiled_switch.py
docs/examples/tutorial/pure/compiled_switch.py
+6
-6
docs/examples/tutorial/pure/cython_declare.py
docs/examples/tutorial/pure/cython_declare.py
+4
-4
docs/examples/tutorial/pure/cython_declare2.py
docs/examples/tutorial/pure/cython_declare2.py
+3
-3
docs/examples/tutorial/pure/dostuff.py
docs/examples/tutorial/pure/dostuff.py
+5
-5
docs/examples/tutorial/pure/exceptval.py
docs/examples/tutorial/pure/exceptval.py
+7
-7
docs/examples/tutorial/pure/locals.py
docs/examples/tutorial/pure/locals.py
+6
-6
docs/examples/tutorial/pure/mymodule.py
docs/examples/tutorial/pure/mymodule.py
+10
-10
docs/examples/tutorial/pure/pep_526.py
docs/examples/tutorial/pure/pep_526.py
+22
-22
docs/examples/tutorial/string/api_func.pyx
docs/examples/tutorial/string/api_func.pyx
+5
-5
docs/examples/tutorial/string/arg_memview.pyx
docs/examples/tutorial/string/arg_memview.pyx
+5
-5
docs/examples/tutorial/string/auto_conversion_1.pyx
docs/examples/tutorial/string/auto_conversion_1.pyx
+9
-9
docs/examples/tutorial/string/auto_conversion_2.pyx
docs/examples/tutorial/string/auto_conversion_2.pyx
+12
-12
docs/examples/tutorial/string/auto_conversion_3.pyx
docs/examples/tutorial/string/auto_conversion_3.pyx
+6
-6
docs/examples/tutorial/string/c_func.pyx
docs/examples/tutorial/string/c_func.pyx
+22
-22
docs/examples/tutorial/string/const.pyx
docs/examples/tutorial/string/const.pyx
+4
-4
docs/examples/tutorial/string/cpp_string.pyx
docs/examples/tutorial/string/cpp_string.pyx
+12
-12
docs/examples/tutorial/string/decode.pyx
docs/examples/tutorial/string/decode.pyx
+9
-9
docs/examples/tutorial/string/decode_cpp_string.pyx
docs/examples/tutorial/string/decode_cpp_string.pyx
+10
-10
docs/examples/tutorial/string/for_bytes.pyx
docs/examples/tutorial/string/for_bytes.pyx
+6
-6
docs/examples/tutorial/string/for_char.pyx
docs/examples/tutorial/string/for_char.pyx
+6
-6
docs/examples/tutorial/string/for_unicode.pyx
docs/examples/tutorial/string/for_unicode.pyx
+6
-6
docs/examples/tutorial/string/if_char_in.pyx
docs/examples/tutorial/string/if_char_in.pyx
+5
-5
docs/examples/tutorial/string/naive_decode.pyx
docs/examples/tutorial/string/naive_decode.pyx
+4
-4
docs/examples/tutorial/string/return_memview.pyx
docs/examples/tutorial/string/return_memview.pyx
+9
-9
docs/examples/tutorial/string/slicing_c_string.pyx
docs/examples/tutorial/string/slicing_c_string.pyx
+15
-15
docs/examples/tutorial/string/to_char.pyx
docs/examples/tutorial/string/to_char.pyx
+8
-8
docs/examples/tutorial/string/to_unicode.pyx
docs/examples/tutorial/string/to_unicode.pyx
+22
-22
docs/examples/tutorial/string/try_finally.pyx
docs/examples/tutorial/string/try_finally.pyx
+9
-9
docs/examples/tutorial/string/utf_eight.pyx
docs/examples/tutorial/string/utf_eight.pyx
+14
-14
docs/examples/userguide/buffer/matrix.pyx
docs/examples/userguide/buffer/matrix.pyx
+16
-16
docs/examples/userguide/buffer/matrix_with_buffer.pyx
docs/examples/userguide/buffer/matrix_with_buffer.pyx
+45
-45
docs/examples/userguide/buffer/view_count.pyx
docs/examples/userguide/buffer/view_count.pyx
+28
-28
docs/examples/userguide/early_binding_for_speed/rectangle.pyx
.../examples/userguide/early_binding_for_speed/rectangle.pyx
+19
-19
docs/examples/userguide/early_binding_for_speed/rectangle_cdef.pyx
...ples/userguide/early_binding_for_speed/rectangle_cdef.pyx
+22
-22
docs/examples/userguide/early_binding_for_speed/rectangle_cpdef.pyx
...les/userguide/early_binding_for_speed/rectangle_cpdef.pyx
+19
-19
docs/examples/userguide/extension_types/dict_animal.pyx
docs/examples/userguide/extension_types/dict_animal.pyx
+11
-11
docs/examples/userguide/extension_types/extendable_animal.pyx
.../examples/userguide/extension_types/extendable_animal.pyx
+13
-13
docs/examples/userguide/extension_types/my_module.pyx
docs/examples/userguide/extension_types/my_module.pyx
+11
-11
docs/examples/userguide/extension_types/python_access.pyx
docs/examples/userguide/extension_types/python_access.pyx
+3
-3
docs/examples/userguide/extension_types/shrubbery.pyx
docs/examples/userguide/extension_types/shrubbery.pyx
+12
-12
docs/examples/userguide/extension_types/shrubbery_2.pyx
docs/examples/userguide/extension_types/shrubbery_2.pyx
+8
-8
docs/examples/userguide/extension_types/widen_shrubbery.pyx
docs/examples/userguide/extension_types/widen_shrubbery.pyx
+4
-4
docs/examples/userguide/external_C_code/c_code_docstring.pyx
docs/examples/userguide/external_C_code/c_code_docstring.pyx
+9
-9
docs/examples/userguide/external_C_code/delorean.pyx
docs/examples/userguide/external_C_code/delorean.pyx
+8
-8
docs/examples/userguide/fusedtypes/char_or_float.pyx
docs/examples/userguide/fusedtypes/char_or_float.pyx
+17
-17
docs/examples/userguide/language_basics/casting_python.pyx
docs/examples/userguide/language_basics/casting_python.pyx
+19
-19
docs/examples/userguide/language_basics/cdef_block.pyx
docs/examples/userguide/language_basics/cdef_block.pyx
+12
-12
docs/examples/userguide/language_basics/compile_time.pyx
docs/examples/userguide/language_basics/compile_time.pyx
+8
-8
docs/examples/userguide/language_basics/kwargs_1.pyx
docs/examples/userguide/language_basics/kwargs_1.pyx
+6
-6
docs/examples/userguide/language_basics/kwargs_2.pyx
docs/examples/userguide/language_basics/kwargs_2.pyx
+5
-5
docs/examples/userguide/language_basics/open_file.pyx
docs/examples/userguide/language_basics/open_file.pyx
+18
-18
docs/examples/userguide/language_basics/optional_subclassing.pyx
...amples/userguide/language_basics/optional_subclassing.pyx
+13
-13
docs/examples/userguide/language_basics/override.pyx
docs/examples/userguide/language_basics/override.pyx
+13
-13
docs/examples/userguide/language_basics/struct_union_enum.pyx
.../examples/userguide/language_basics/struct_union_enum.pyx
+16
-16
docs/examples/userguide/memoryviews/add_one.pyx
docs/examples/userguide/memoryviews/add_one.pyx
+12
-12
docs/examples/userguide/memoryviews/copy.pyx
docs/examples/userguide/memoryviews/copy.pyx
+12
-12
docs/examples/userguide/memoryviews/memory_layout.pyx
docs/examples/userguide/memoryviews/memory_layout.pyx
+11
-11
docs/examples/userguide/memoryviews/memory_layout_2.pyx
docs/examples/userguide/memoryviews/memory_layout_2.pyx
+6
-6
docs/examples/userguide/memoryviews/memview_to_c.pyx
docs/examples/userguide/memoryviews/memview_to_c.pyx
+28
-28
docs/examples/userguide/memoryviews/not_none.pyx
docs/examples/userguide/memoryviews/not_none.pyx
+11
-11
docs/examples/userguide/memoryviews/np_flag_const.pyx
docs/examples/userguide/memoryviews/np_flag_const.pyx
+7
-7
docs/examples/userguide/memoryviews/slicing.pyx
docs/examples/userguide/memoryviews/slicing.pyx
+10
-10
docs/examples/userguide/memoryviews/transpose.pyx
docs/examples/userguide/memoryviews/transpose.pyx
+6
-6
docs/examples/userguide/memoryviews/view_string.pyx
docs/examples/userguide/memoryviews/view_string.pyx
+9
-9
docs/examples/userguide/numpy_tutorial/compute_fused_types.pyx
...examples/userguide/numpy_tutorial/compute_fused_types.pyx
+44
-44
docs/examples/userguide/numpy_tutorial/compute_infer_types.pyx
...examples/userguide/numpy_tutorial/compute_infer_types.pyx
+34
-34
docs/examples/userguide/numpy_tutorial/compute_memview.pyx
docs/examples/userguide/numpy_tutorial/compute_memview.pyx
+34
-34
docs/examples/userguide/numpy_tutorial/compute_prange.pyx
docs/examples/userguide/numpy_tutorial/compute_prange.pyx
+53
-53
docs/examples/userguide/numpy_tutorial/compute_py.py
docs/examples/userguide/numpy_tutorial/compute_py.py
+28
-28
docs/examples/userguide/numpy_tutorial/compute_typed.pyx
docs/examples/userguide/numpy_tutorial/compute_typed.pyx
+50
-50
docs/examples/userguide/parallelism/breaking_loop.pyx
docs/examples/userguide/parallelism/breaking_loop.pyx
+13
-13
docs/examples/userguide/parallelism/cimport_openmp.pyx
docs/examples/userguide/parallelism/cimport_openmp.pyx
+13
-13
docs/examples/userguide/parallelism/setup.py
docs/examples/userguide/parallelism/setup.py
+17
-17
docs/examples/userguide/parallelism/simple_sum.pyx
docs/examples/userguide/parallelism/simple_sum.pyx
+10
-10
docs/examples/userguide/sharing_declarations/landscaping.pyx
docs/examples/userguide/sharing_declarations/landscaping.pyx
+7
-7
docs/examples/userguide/sharing_declarations/lunch.pyx
docs/examples/userguide/sharing_declarations/lunch.pyx
+4
-4
docs/examples/userguide/sharing_declarations/restaurant.pyx
docs/examples/userguide/sharing_declarations/restaurant.pyx
+12
-12
docs/examples/userguide/sharing_declarations/setup.py
docs/examples/userguide/sharing_declarations/setup.py
+4
-4
docs/examples/userguide/sharing_declarations/shrubbing.pyx
docs/examples/userguide/sharing_declarations/shrubbing.pyx
+7
-7
docs/examples/userguide/sharing_declarations/spammery.pyx
docs/examples/userguide/sharing_declarations/spammery.pyx
+11
-11
docs/examples/userguide/sharing_declarations/volume.pyx
docs/examples/userguide/sharing_declarations/volume.pyx
+2
-2
docs/examples/userguide/wrapping_CPlusPlus/cython_usage.pyx
docs/examples/userguide/wrapping_CPlusPlus/cython_usage.pyx
+12
-12
docs/examples/userguide/wrapping_CPlusPlus/function_templates.pyx
...mples/userguide/wrapping_CPlusPlus/function_templates.pyx
+7
-7
docs/examples/userguide/wrapping_CPlusPlus/iterate.pyx
docs/examples/userguide/wrapping_CPlusPlus/iterate.pyx
+12
-12
docs/examples/userguide/wrapping_CPlusPlus/nested_class.pyx
docs/examples/userguide/wrapping_CPlusPlus/nested_class.pyx
+17
-17
docs/examples/userguide/wrapping_CPlusPlus/python_to_cpp.pyx
docs/examples/userguide/wrapping_CPlusPlus/python_to_cpp.pyx
+19
-19
docs/examples/userguide/wrapping_CPlusPlus/rect_ptr.pyx
docs/examples/userguide/wrapping_CPlusPlus/rect_ptr.pyx
+12
-12
docs/examples/userguide/wrapping_CPlusPlus/templates.pyx
docs/examples/userguide/wrapping_CPlusPlus/templates.pyx
+30
-30
docs/examples/userguide/wrapping_CPlusPlus/vector_demo.pyx
docs/examples/userguide/wrapping_CPlusPlus/vector_demo.pyx
+15
-15
docs/examples/userguide/wrapping_CPlusPlus/wrapper_vector.pyx
.../examples/userguide/wrapping_CPlusPlus/wrapper_vector.pyx
+17
-17
No files found.
docs/examples/README.rst
View file @
b67e5567
This example directory is organized like the ``Cython/docs/src/`` directory,
with one directory per ``.rst`` file. All files in this directory are tested
in the :file:`runtests.py` with the mode `compile`.
This example directory is organized like the ``Cython/docs/src/`` directory,
with one directory per ``.rst`` file. All files in this directory are tested
in the :file:`runtests.py` with the mode `compile`.
docs/examples/quickstart/build/hello.pyx
View file @
b67e5567
def
say_hello_to
(
name
):
print
(
"Hello %s!"
%
name
)
def
say_hello_to
(
name
):
print
(
"Hello %s!"
%
name
)
docs/examples/quickstart/build/setup.py
View file @
b67e5567
from
distutils.core
import
setup
from
Cython.Build
import
cythonize
setup
(
name
=
'Hello world app'
,
ext_modules
=
cythonize
(
"hello.pyx"
))
from
distutils.core
import
setup
from
Cython.Build
import
cythonize
setup
(
name
=
'Hello world app'
,
ext_modules
=
cythonize
(
"hello.pyx"
))
docs/examples/quickstart/cythonize/cdef_keyword.pyx
View file @
b67e5567
cdef
double
f
(
double
x
)
except
?
-
2
:
return
x
**
2
-
x
cdef
double
f
(
double
x
)
except
?
-
2
:
return
x
**
2
-
x
docs/examples/quickstart/cythonize/integrate.py
View file @
b67e5567
def
f
(
x
):
return
x
**
2
-
x
def
integrate_f
(
a
,
b
,
N
):
s
=
0
dx
=
(
b
-
a
)
/
N
for
i
in
range
(
N
):
s
+=
f
(
a
+
i
*
dx
)
return
s
*
dx
def
f
(
x
):
return
x
**
2
-
x
def
integrate_f
(
a
,
b
,
N
):
s
=
0
dx
=
(
b
-
a
)
/
N
for
i
in
range
(
N
):
s
+=
f
(
a
+
i
*
dx
)
return
s
*
dx
docs/examples/quickstart/cythonize/integrate_cy.pyx
View file @
b67e5567
def
f
(
double
x
):
return
x
**
2
-
x
def
integrate_f
(
double
a
,
double
b
,
int
N
):
cdef
int
i
cdef
double
s
,
dx
s
=
0
dx
=
(
b
-
a
)
/
N
for
i
in
range
(
N
):
s
+=
f
(
a
+
i
*
dx
)
return
s
*
dx
def
f
(
double
x
):
return
x
**
2
-
x
def
integrate_f
(
double
a
,
double
b
,
int
N
):
cdef
int
i
cdef
double
s
,
dx
s
=
0
dx
=
(
b
-
a
)
/
N
for
i
in
range
(
N
):
s
+=
f
(
a
+
i
*
dx
)
return
s
*
dx
docs/examples/tutorial/array/clone.pyx
View file @
b67e5567
from
cpython
cimport
array
import
array
cdef
array
.
array
int_array_template
=
array
.
array
(
'i'
,
[])
cdef
array
.
array
newarray
# create an array with 3 elements with same type as template
newarray
=
array
.
clone
(
int_array_template
,
3
,
zero
=
False
)
from
cpython
cimport
array
import
array
cdef
array
.
array
int_array_template
=
array
.
array
(
'i'
,
[])
cdef
array
.
array
newarray
# create an array with 3 elements with same type as template
newarray
=
array
.
clone
(
int_array_template
,
3
,
zero
=
False
)
docs/examples/tutorial/array/overhead.pyx
View file @
b67e5567
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
cdef
int
[:]
ca
=
a
cdef
int
overhead
(
object
a
):
cdef
int
[:]
ca
=
a
return
ca
[
0
]
cdef
int
no_overhead
(
int
[:]
ca
):
return
ca
[
0
]
print
(
overhead
(
a
))
# new memory view will be constructed, overhead
print
(
no_overhead
(
ca
))
# ca is already a memory view, so no overhead
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
cdef
int
[:]
ca
=
a
cdef
int
overhead
(
object
a
):
cdef
int
[:]
ca
=
a
return
ca
[
0
]
cdef
int
no_overhead
(
int
[:]
ca
):
return
ca
[
0
]
print
(
overhead
(
a
))
# new memory view will be constructed, overhead
print
(
no_overhead
(
ca
))
# ca is already a memory view, so no overhead
docs/examples/tutorial/array/resize.pyx
View file @
b67e5567
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
cdef
array
.
array
b
=
array
.
array
(
'i'
,
[
4
,
5
,
6
])
# extend a with b, resize as needed
array
.
extend
(
a
,
b
)
# resize a, leaving just original three elements
array
.
resize
(
a
,
len
(
a
)
-
len
(
b
))
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
cdef
array
.
array
b
=
array
.
array
(
'i'
,
[
4
,
5
,
6
])
# extend a with b, resize as needed
array
.
extend
(
a
,
b
)
# resize a, leaving just original three elements
array
.
resize
(
a
,
len
(
a
)
-
len
(
b
))
docs/examples/tutorial/array/safe_usage.pyx
View file @
b67e5567
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
cdef
int
[:]
ca
=
a
print
(
ca
[
0
])
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
cdef
int
[:]
ca
=
a
print
(
ca
[
0
])
docs/examples/tutorial/array/unsafe_usage.pyx
View file @
b67e5567
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
# access underlying pointer:
print
(
a
.
data
.
as_ints
[
0
])
from
libc.string
cimport
memset
memset
(
a
.
data
.
as_voidptr
,
0
,
len
(
a
)
*
sizeof
(
int
))
from
cpython
cimport
array
import
array
cdef
array
.
array
a
=
array
.
array
(
'i'
,
[
1
,
2
,
3
])
# access underlying pointer:
print
(
a
.
data
.
as_ints
[
0
])
from
libc.string
cimport
memset
memset
(
a
.
data
.
as_voidptr
,
0
,
len
(
a
)
*
sizeof
(
int
))
docs/examples/tutorial/cdef_classes/integrate.pyx
View file @
b67e5567
from
sin_of_square
cimport
Function
,
SinOfSquareFunction
def
integrate
(
Function
f
,
double
a
,
double
b
,
int
N
):
cdef
int
i
cdef
double
s
,
dx
if
f
is
None
:
raise
ValueError
(
"f cannot be None"
)
s
=
0
dx
=
(
b
-
a
)
/
N
for
i
in
range
(
N
):
s
+=
f
.
evaluate
(
a
+
i
*
dx
)
return
s
*
dx
print
(
integrate
(
SinOfSquareFunction
(),
0
,
1
,
10000
))
from
sin_of_square
cimport
Function
,
SinOfSquareFunction
def
integrate
(
Function
f
,
double
a
,
double
b
,
int
N
):
cdef
int
i
cdef
double
s
,
dx
if
f
is
None
:
raise
ValueError
(
"f cannot be None"
)
s
=
0
dx
=
(
b
-
a
)
/
N
for
i
in
range
(
N
):
s
+=
f
.
evaluate
(
a
+
i
*
dx
)
return
s
*
dx
print
(
integrate
(
SinOfSquareFunction
(),
0
,
1
,
10000
))
docs/examples/tutorial/cdef_classes/math_function.py
View file @
b67e5567
class
MathFunction
(
object
):
def
__init__
(
self
,
name
,
operator
):
self
.
name
=
name
self
.
operator
=
operator
def
__call__
(
self
,
*
operands
):
return
self
.
operator
(
*
operands
)
class
MathFunction
(
object
):
def
__init__
(
self
,
name
,
operator
):
self
.
name
=
name
self
.
operator
=
operator
def
__call__
(
self
,
*
operands
):
return
self
.
operator
(
*
operands
)
docs/examples/tutorial/cdef_classes/math_function_2.pyx
View file @
b67e5567
cdef
class
Function
:
cpdef
double
evaluate
(
self
,
double
x
)
except
*
:
return
0
cdef
class
Function
:
cpdef
double
evaluate
(
self
,
double
x
)
except
*
:
return
0
docs/examples/tutorial/cdef_classes/nonecheck.pyx
View file @
b67e5567
# cython: nonecheck=True
# ^^^ Turns on nonecheck globally
import
cython
cdef
class
MyClass
:
pass
# Turn off nonecheck locally for the function
@
cython
.
nonecheck
(
False
)
def
func
():
cdef
MyClass
obj
=
None
try
:
# Turn nonecheck on again for a block
with
cython
.
nonecheck
(
True
):
print
(
obj
.
myfunc
())
# Raises exception
except
AttributeError
:
pass
print
(
obj
.
myfunc
())
# Hope for a crash!
# cython: nonecheck=True
# ^^^ Turns on nonecheck globally
import
cython
cdef
class
MyClass
:
pass
# Turn off nonecheck locally for the function
@
cython
.
nonecheck
(
False
)
def
func
():
cdef
MyClass
obj
=
None
try
:
# Turn nonecheck on again for a block
with
cython
.
nonecheck
(
True
):
print
(
obj
.
myfunc
())
# Raises exception
except
AttributeError
:
pass
print
(
obj
.
myfunc
())
# Hope for a crash!
docs/examples/tutorial/cdef_classes/sin_of_square.pyx
View file @
b67e5567
from
libc.math
cimport
sin
cdef
class
Function
:
cpdef
double
evaluate
(
self
,
double
x
)
except
*
:
return
0
cdef
class
SinOfSquareFunction
(
Function
):
cpdef
double
evaluate
(
self
,
double
x
)
except
*
:
return
sin
(
x
**
2
)
from
libc.math
cimport
sin
cdef
class
Function
:
cpdef
double
evaluate
(
self
,
double
x
)
except
*
:
return
0
cdef
class
SinOfSquareFunction
(
Function
):
cpdef
double
evaluate
(
self
,
double
x
)
except
*
:
return
sin
(
x
**
2
)
docs/examples/tutorial/cdef_classes/wave_function.pyx
View file @
b67e5567
from
sin_of_square
cimport
Function
cdef
class
WaveFunction
(
Function
):
# Not available in Python-space:
cdef
double
offset
# Available in Python-space:
cdef
public
double
freq
# Available in Python-space, but only for reading:
cdef
readonly
double
scale
# Available in Python-space:
@
property
def
period
(
self
):
return
1.0
/
self
.
freq
@
period
.
setter
def
period
(
self
,
value
):
self
.
freq
=
1.0
/
value
from
sin_of_square
cimport
Function
cdef
class
WaveFunction
(
Function
):
# Not available in Python-space:
cdef
double
offset
# Available in Python-space:
cdef
public
double
freq
# Available in Python-space, but only for reading:
cdef
readonly
double
scale
# Available in Python-space:
@
property
def
period
(
self
):
return
1.0
/
self
.
freq
@
period
.
setter
def
period
(
self
,
value
):
self
.
freq
=
1.0
/
value
docs/examples/tutorial/clibraries/queue.pyx
View file @
b67e5567
# queue.pyx
cimport
cqueue
cdef
class
Queue
:
cdef
cqueue
.
Queue
*
_c_queue
def
__cinit__
(
self
):
self
.
_c_queue
=
cqueue
.
queue_new
()
# queue.pyx
cimport
cqueue
cdef
class
Queue
:
cdef
cqueue
.
Queue
*
_c_queue
def
__cinit__
(
self
):
self
.
_c_queue
=
cqueue
.
queue_new
()
docs/examples/tutorial/clibraries/queue2.pyx
View file @
b67e5567
# queue.pyx
cimport
cqueue
cdef
class
Queue
:
cdef
cqueue
.
Queue
*
_c_queue
def
__cinit__
(
self
):
self
.
_c_queue
=
cqueue
.
queue_new
()
if
self
.
_c_queue
is
NULL
:
raise
MemoryError
()
# queue.pyx
cimport
cqueue
cdef
class
Queue
:
cdef
cqueue
.
Queue
*
_c_queue
def
__cinit__
(
self
):
self
.
_c_queue
=
cqueue
.
queue_new
()
if
self
.
_c_queue
is
NULL
:
raise
MemoryError
()
docs/examples/tutorial/clibraries/test_queue.py
View file @
b67e5567
from
__future__
import
print_function
import
time
import
queue
Q
=
queue
.
Queue
()
Q
.
append
(
10
)
Q
.
append
(
20
)
print
(
Q
.
peek
())
print
(
Q
.
pop
())
print
(
Q
.
pop
())
try
:
print
(
Q
.
pop
())
except
IndexError
as
e
:
print
(
"Error message:"
,
e
)
# Prints "Queue is empty"
i
=
10000
values
=
range
(
i
)
start_time
=
time
.
time
()
Q
.
extend
(
values
)
end_time
=
time
.
time
()
-
start_time
print
(
"Adding {} items took {:1.3f} msecs."
.
format
(
i
,
1000
*
end_time
))
for
i
in
range
(
41
):
Q
.
pop
()
Q
.
pop
()
print
(
"The answer is:"
)
print
(
Q
.
pop
())
from
__future__
import
print_function
import
time
import
queue
Q
=
queue
.
Queue
()
Q
.
append
(
10
)
Q
.
append
(
20
)
print
(
Q
.
peek
())
print
(
Q
.
pop
())
print
(
Q
.
pop
())
try
:
print
(
Q
.
pop
())
except
IndexError
as
e
:
print
(
"Error message:"
,
e
)
# Prints "Queue is empty"
i
=
10000
values
=
range
(
i
)
start_time
=
time
.
time
()
Q
.
extend
(
values
)
end_time
=
time
.
time
()
-
start_time
print
(
"Adding {} items took {:1.3f} msecs."
.
format
(
i
,
1000
*
end_time
))
for
i
in
range
(
41
):
Q
.
pop
()
Q
.
pop
()
print
(
"The answer is:"
)
print
(
Q
.
pop
())
docs/examples/tutorial/cython_tutorial/primes_cpp.pyx
View file @
b67e5567
# distutils: language=c++
from
libcpp.vector
cimport
vector
def
primes
(
unsigned
int
nb_primes
):
cdef
int
n
,
i
cdef
vector
[
int
]
p
p
.
reserve
(
nb_primes
)
# allocate memory for 'nb_primes' elements.
n
=
2
while
p
.
size
()
<
nb_primes
:
# size() for vectors is similar to len()
for
i
in
p
:
if
n
%
i
==
0
:
break
else
:
p
.
push_back
(
n
)
# push_back is similar to append()
n
+=
1
# Vectors are automatically converted to Python
# lists when converted to Python objects.
return
p
# distutils: language=c++
from
libcpp.vector
cimport
vector
def
primes
(
unsigned
int
nb_primes
):
cdef
int
n
,
i
cdef
vector
[
int
]
p
p
.
reserve
(
nb_primes
)
# allocate memory for 'nb_primes' elements.
n
=
2
while
p
.
size
()
<
nb_primes
:
# size() for vectors is similar to len()
for
i
in
p
:
if
n
%
i
==
0
:
break
else
:
p
.
push_back
(
n
)
# push_back is similar to append()
n
+=
1
# Vectors are automatically converted to Python
# lists when converted to Python objects.
return
p
docs/examples/tutorial/external/atoi.pyx
View file @
b67e5567
from
libc.stdlib
cimport
atoi
cdef
parse_charptr_to_py_int
(
char
*
s
):
assert
s
is
not
NULL
,
"byte string value is NULL"
return
atoi
(
s
)
# note: atoi() has no error detection!
from
libc.stdlib
cimport
atoi
cdef
parse_charptr_to_py_int
(
char
*
s
):
assert
s
is
not
NULL
,
"byte string value is NULL"
return
atoi
(
s
)
# note: atoi() has no error detection!
docs/examples/tutorial/external/cpdef_sin.pyx
View file @
b67e5567
"""
>>> sin(0)
0.0
"""
cdef
extern
from
"math.h"
:
cpdef
double
sin
(
double
x
)
"""
>>> sin(0)
0.0
"""
cdef
extern
from
"math.h"
:
cpdef
double
sin
(
double
x
)
docs/examples/tutorial/external/keyword_args.pyx
View file @
b67e5567
cdef
extern
from
"string.h"
:
char
*
strstr
(
const
char
*
haystack
,
const
char
*
needle
)
cdef
extern
from
"string.h"
:
char
*
strstr
(
const
char
*
haystack
,
const
char
*
needle
)
docs/examples/tutorial/external/keyword_args_call.pyx
View file @
b67e5567
cdef
extern
from
"string.h"
:
char
*
strstr
(
const
char
*
haystack
,
const
char
*
needle
)
cdef
char
*
data
=
"hfvcakdfagbcffvschvxcdfgccbcfhvgcsnfxjh"
cdef
char
*
pos
=
strstr
(
needle
=
'akd'
,
haystack
=
data
)
print
(
pos
is
not
NULL
)
cdef
extern
from
"string.h"
:
char
*
strstr
(
const
char
*
haystack
,
const
char
*
needle
)
cdef
char
*
data
=
"hfvcakdfagbcffvschvxcdfgccbcfhvgcsnfxjh"
cdef
char
*
pos
=
strstr
(
needle
=
'akd'
,
haystack
=
data
)
print
(
pos
is
not
NULL
)
docs/examples/tutorial/external/libc_sin.pyx
View file @
b67e5567
from
libc.math
cimport
sin
cdef
double
f
(
double
x
):
return
sin
(
x
*
x
)
from
libc.math
cimport
sin
cdef
double
f
(
double
x
):
return
sin
(
x
*
x
)
docs/examples/tutorial/external/py_version_hex.pyx
View file @
b67e5567
from
cpython.version
cimport
PY_VERSION_HEX
# Python version >= 3.2 final ?
print
(
PY_VERSION_HEX
>=
0x030200F0
)
from
cpython.version
cimport
PY_VERSION_HEX
# Python version >= 3.2 final ?
print
(
PY_VERSION_HEX
>=
0x030200F0
)
docs/examples/tutorial/external/setup.py
View file @
b67e5567
from
distutils.core
import
setup
from
distutils.extension
import
Extension
from
Cython.Build
import
cythonize
ext_modules
=
[
Extension
(
"demo"
,
sources
=
[
"demo.pyx"
],
libraries
=
[
"m"
]
# Unix-like specific
)
]
setup
(
name
=
"Demos"
,
ext_modules
=
cythonize
(
ext_modules
))
from
distutils.core
import
setup
from
distutils.extension
import
Extension
from
Cython.Build
import
cythonize
ext_modules
=
[
Extension
(
"demo"
,
sources
=
[
"demo.pyx"
],
libraries
=
[
"m"
]
# Unix-like specific
)
]
setup
(
name
=
"Demos"
,
ext_modules
=
cythonize
(
ext_modules
))
docs/examples/tutorial/memory_allocation/malloc.pyx
View file @
b67e5567
import
random
from
libc.stdlib
cimport
malloc
,
free
def
random_noise
(
int
number
=
1
):
cdef
int
i
# allocate number * sizeof(double) bytes of memory
cdef
double
*
my_array
=
<
double
*>
malloc
(
number
*
sizeof
(
double
))
if
not
my_array
:
raise
MemoryError
()
try
:
ran
=
random
.
normalvariate
for
i
in
range
(
number
):
my_array
[
i
]
=
ran
(
0
,
1
)
# ... let's just assume we do some more heavy C calculations here to make up
# for the work that it takes to pack the C double values into Python float
# objects below, right after throwing away the existing objects above.
return
[
x
for
x
in
my_array
[:
number
]]
finally
:
# return the previously allocated memory to the system
free
(
my_array
)
import
random
from
libc.stdlib
cimport
malloc
,
free
def
random_noise
(
int
number
=
1
):
cdef
int
i
# allocate number * sizeof(double) bytes of memory
cdef
double
*
my_array
=
<
double
*>
malloc
(
number
*
sizeof
(
double
))
if
not
my_array
:
raise
MemoryError
()
try
:
ran
=
random
.
normalvariate
for
i
in
range
(
number
):
my_array
[
i
]
=
ran
(
0
,
1
)
# ... let's just assume we do some more heavy C calculations here to make up
# for the work that it takes to pack the C double values into Python float
# objects below, right after throwing away the existing objects above.
return
[
x
for
x
in
my_array
[:
number
]]
finally
:
# return the previously allocated memory to the system
free
(
my_array
)
docs/examples/tutorial/memory_allocation/some_memory.pyx
View file @
b67e5567
from
cpython.mem
cimport
PyMem_Malloc
,
PyMem_Realloc
,
PyMem_Free
cdef
class
SomeMemory
:
cdef
double
*
data
def
__cinit__
(
self
,
size_t
number
):
# allocate some memory (uninitialised, may contain arbitrary data)
self
.
data
=
<
double
*>
PyMem_Malloc
(
number
*
sizeof
(
double
))
if
not
self
.
data
:
raise
MemoryError
()
def
resize
(
self
,
size_t
new_number
):
# Allocates new_number * sizeof(double) bytes,
# preserving the current content and making a best-effort to
# re-use the original data location.
mem
=
<
double
*>
PyMem_Realloc
(
self
.
data
,
new_number
*
sizeof
(
double
))
if
not
mem
:
raise
MemoryError
()
# Only overwrite the pointer if the memory was really reallocated.
# On error (mem is NULL), the originally memory has not been freed.
self
.
data
=
mem
def
__dealloc__
(
self
):
PyMem_Free
(
self
.
data
)
# no-op if self.data is NULL
from
cpython.mem
cimport
PyMem_Malloc
,
PyMem_Realloc
,
PyMem_Free
cdef
class
SomeMemory
:
cdef
double
*
data
def
__cinit__
(
self
,
size_t
number
):
# allocate some memory (uninitialised, may contain arbitrary data)
self
.
data
=
<
double
*>
PyMem_Malloc
(
number
*
sizeof
(
double
))
if
not
self
.
data
:
raise
MemoryError
()
def
resize
(
self
,
size_t
new_number
):
# Allocates new_number * sizeof(double) bytes,
# preserving the current content and making a best-effort to
# re-use the original data location.
mem
=
<
double
*>
PyMem_Realloc
(
self
.
data
,
new_number
*
sizeof
(
double
))
if
not
mem
:
raise
MemoryError
()
# Only overwrite the pointer if the memory was really reallocated.
# On error (mem is NULL), the originally memory has not been freed.
self
.
data
=
mem
def
__dealloc__
(
self
):
PyMem_Free
(
self
.
data
)
# no-op if self.data is NULL
docs/examples/tutorial/numpy/convolve_py.py
View file @
b67e5567
import
numpy
as
np
def
naive_convolve
(
f
,
g
):
# f is an image and is indexed by (v, w)
# g is a filter kernel and is indexed by (s, t),
# it needs odd dimensions
# h is the output image and is indexed by (x, y),
# it is not cropped
if
g
.
shape
[
0
]
%
2
!=
1
or
g
.
shape
[
1
]
%
2
!=
1
:
raise
ValueError
(
"Only odd dimensions on filter supported"
)
# smid and tmid are number of pixels between the center pixel
# and the edge, ie for a 5x5 filter they will be 2.
#
# The output size is calculated by adding smid, tmid to each
# side of the dimensions of the input image.
vmax
=
f
.
shape
[
0
]
wmax
=
f
.
shape
[
1
]
smax
=
g
.
shape
[
0
]
tmax
=
g
.
shape
[
1
]
smid
=
smax
//
2
tmid
=
tmax
//
2
xmax
=
vmax
+
2
*
smid
ymax
=
wmax
+
2
*
tmid
# Allocate result image.
h
=
np
.
zeros
([
xmax
,
ymax
],
dtype
=
f
.
dtype
)
# Do convolution
for
x
in
range
(
xmax
):
for
y
in
range
(
ymax
):
# Calculate pixel value for h at (x,y). Sum one component
# for each pixel (s, t) of the filter g.
s_from
=
max
(
smid
-
x
,
-
smid
)
s_to
=
min
((
xmax
-
x
)
-
smid
,
smid
+
1
)
t_from
=
max
(
tmid
-
y
,
-
tmid
)
t_to
=
min
((
ymax
-
y
)
-
tmid
,
tmid
+
1
)
value
=
0
for
s
in
range
(
s_from
,
s_to
):
for
t
in
range
(
t_from
,
t_to
):
v
=
x
-
smid
+
s
w
=
y
-
tmid
+
t
value
+=
g
[
smid
-
s
,
tmid
-
t
]
*
f
[
v
,
w
]
h
[
x
,
y
]
=
value
return
h
import
numpy
as
np
def
naive_convolve
(
f
,
g
):
# f is an image and is indexed by (v, w)
# g is a filter kernel and is indexed by (s, t),
# it needs odd dimensions
# h is the output image and is indexed by (x, y),
# it is not cropped
if
g
.
shape
[
0
]
%
2
!=
1
or
g
.
shape
[
1
]
%
2
!=
1
:
raise
ValueError
(
"Only odd dimensions on filter supported"
)
# smid and tmid are number of pixels between the center pixel
# and the edge, ie for a 5x5 filter they will be 2.
#
# The output size is calculated by adding smid, tmid to each
# side of the dimensions of the input image.
vmax
=
f
.
shape
[
0
]
wmax
=
f
.
shape
[
1
]
smax
=
g
.
shape
[
0
]
tmax
=
g
.
shape
[
1
]
smid
=
smax
//
2
tmid
=
tmax
//
2
xmax
=
vmax
+
2
*
smid
ymax
=
wmax
+
2
*
tmid
# Allocate result image.
h
=
np
.
zeros
([
xmax
,
ymax
],
dtype
=
f
.
dtype
)
# Do convolution
for
x
in
range
(
xmax
):
for
y
in
range
(
ymax
):
# Calculate pixel value for h at (x,y). Sum one component
# for each pixel (s, t) of the filter g.
s_from
=
max
(
smid
-
x
,
-
smid
)
s_to
=
min
((
xmax
-
x
)
-
smid
,
smid
+
1
)
t_from
=
max
(
tmid
-
y
,
-
tmid
)
t_to
=
min
((
ymax
-
y
)
-
tmid
,
tmid
+
1
)
value
=
0
for
s
in
range
(
s_from
,
s_to
):
for
t
in
range
(
t_from
,
t_to
):
v
=
x
-
smid
+
s
w
=
y
-
tmid
+
t
value
+=
g
[
smid
-
s
,
tmid
-
t
]
*
f
[
v
,
w
]
h
[
x
,
y
]
=
value
return
h
docs/examples/tutorial/profiling_tutorial/calc_pi.py
View file @
b67e5567
# calc_pi.py
def
recip_square
(
i
):
return
1.
/
i
**
2
def
approx_pi
(
n
=
10000000
):
val
=
0.
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
# calc_pi.py
def
recip_square
(
i
):
return
1.
/
i
**
2
def
approx_pi
(
n
=
10000000
):
val
=
0.
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
docs/examples/tutorial/profiling_tutorial/calc_pi_2.pyx
View file @
b67e5567
# cython: profile=True
# calc_pi.pyx
def
recip_square
(
int
i
):
return
1.
/
i
**
2
def
approx_pi
(
int
n
=
10000000
):
cdef
double
val
=
0.
cdef
int
k
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
# cython: profile=True
# calc_pi.pyx
def
recip_square
(
int
i
):
return
1.
/
i
**
2
def
approx_pi
(
int
n
=
10000000
):
cdef
double
val
=
0.
cdef
int
k
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
docs/examples/tutorial/profiling_tutorial/calc_pi_3.pyx
View file @
b67e5567
# cython: profile=True
# calc_pi.pyx
cdef
inline
double
recip_square
(
int
i
):
return
1.
/
(
i
*
i
)
def
approx_pi
(
int
n
=
10000000
):
cdef
double
val
=
0.
cdef
int
k
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
# cython: profile=True
# calc_pi.pyx
cdef
inline
double
recip_square
(
int
i
):
return
1.
/
(
i
*
i
)
def
approx_pi
(
int
n
=
10000000
):
cdef
double
val
=
0.
cdef
int
k
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
docs/examples/tutorial/profiling_tutorial/calc_pi_4.pyx
View file @
b67e5567
# cython: profile=True
# calc_pi.pyx
cimport
cython
@
cython
.
profile
(
False
)
cdef
inline
double
recip_square
(
int
i
):
return
1.
/
(
i
*
i
)
def
approx_pi
(
int
n
=
10000000
):
cdef
double
val
=
0.
cdef
int
k
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
# cython: profile=True
# calc_pi.pyx
cimport
cython
@
cython
.
profile
(
False
)
cdef
inline
double
recip_square
(
int
i
):
return
1.
/
(
i
*
i
)
def
approx_pi
(
int
n
=
10000000
):
cdef
double
val
=
0.
cdef
int
k
for
k
in
range
(
1
,
n
+
1
):
val
+=
recip_square
(
k
)
return
(
6
*
val
)
**
.
5
docs/examples/tutorial/profiling_tutorial/often_called.pyx
View file @
b67e5567
cimport
cython
@
cython
.
profile
(
False
)
def
my_often_called_function
():
pass
cimport
cython
@
cython
.
profile
(
False
)
def
my_often_called_function
():
pass
docs/examples/tutorial/profiling_tutorial/profile.py
View file @
b67e5567
# profile.py
import
pstats
,
cProfile
import
calc_pi
cProfile
.
runctx
(
"calc_pi.approx_pi()"
,
globals
(),
locals
(),
"Profile.prof"
)
s
=
pstats
.
Stats
(
"Profile.prof"
)
s
.
strip_dirs
().
sort_stats
(
"time"
).
print_stats
()
# profile.py
import
pstats
,
cProfile
import
calc_pi
cProfile
.
runctx
(
"calc_pi.approx_pi()"
,
globals
(),
locals
(),
"Profile.prof"
)
s
=
pstats
.
Stats
(
"Profile.prof"
)
s
.
strip_dirs
().
sort_stats
(
"time"
).
print_stats
()
docs/examples/tutorial/profiling_tutorial/profile_2.py
View file @
b67e5567
# profile.py
import
pstats
,
cProfile
import
pyximport
pyximport
.
install
()
import
calc_pi
cProfile
.
runctx
(
"calc_pi.approx_pi()"
,
globals
(),
locals
(),
"Profile.prof"
)
s
=
pstats
.
Stats
(
"Profile.prof"
)
s
.
strip_dirs
().
sort_stats
(
"time"
).
print_stats
()
# profile.py
import
pstats
,
cProfile
import
pyximport
pyximport
.
install
()
import
calc_pi
cProfile
.
runctx
(
"calc_pi.approx_pi()"
,
globals
(),
locals
(),
"Profile.prof"
)
s
=
pstats
.
Stats
(
"Profile.prof"
)
s
.
strip_dirs
().
sort_stats
(
"time"
).
print_stats
()
docs/examples/tutorial/pure/A.py
View file @
b67e5567
def
myfunction
(
x
,
y
=
2
):
a
=
x
-
y
return
a
+
x
*
y
def
_helper
(
a
):
return
a
+
1
class
A
:
def
__init__
(
self
,
b
=
0
):
self
.
a
=
3
self
.
b
=
b
def
foo
(
self
,
x
):
print
(
x
+
_helper
(
1.0
))
def
myfunction
(
x
,
y
=
2
):
a
=
x
-
y
return
a
+
x
*
y
def
_helper
(
a
):
return
a
+
1
class
A
:
def
__init__
(
self
,
b
=
0
):
self
.
a
=
3
self
.
b
=
b
def
foo
(
self
,
x
):
print
(
x
+
_helper
(
1.0
))
docs/examples/tutorial/pure/A_equivalent.pyx
View file @
b67e5567
cpdef
int
myfunction
(
int
x
,
int
y
=
2
):
a
=
x
-
y
return
a
+
x
*
y
cdef
double
_helper
(
double
a
):
return
a
+
1
cdef
class
A
:
cdef
public
int
a
,
b
def
__init__
(
self
,
b
=
0
):
self
.
a
=
3
self
.
b
=
b
cpdef
foo
(
self
,
double
x
):
print
(
x
+
_helper
(
1.0
))
cpdef
int
myfunction
(
int
x
,
int
y
=
2
):
a
=
x
-
y
return
a
+
x
*
y
cdef
double
_helper
(
double
a
):
return
a
+
1
cdef
class
A
:
cdef
public
int
a
,
b
def
__init__
(
self
,
b
=
0
):
self
.
a
=
3
self
.
b
=
b
cpdef
foo
(
self
,
double
x
):
print
(
x
+
_helper
(
1.0
))
docs/examples/tutorial/pure/annotations.py
View file @
b67e5567
import
cython
def
func
(
foo
:
dict
,
bar
:
cython
.
int
)
->
tuple
:
foo
[
"hello world"
]
=
3
+
bar
return
foo
,
5
import
cython
def
func
(
foo
:
dict
,
bar
:
cython
.
int
)
->
tuple
:
foo
[
"hello world"
]
=
3
+
bar
return
foo
,
5
docs/examples/tutorial/pure/c_arrays.py
View file @
b67e5567
import
cython
@
cython
.
locals
(
counts
=
cython
.
int
[
10
],
digit
=
cython
.
int
)
def
count_digits
(
digits
):
"""
>>> digits = '01112222333334445667788899'
>>> count_digits(map(int, digits))
[1, 3, 4, 5, 3, 1, 2, 2, 3, 2]
"""
counts
=
[
0
]
*
10
for
digit
in
digits
:
assert
0
<=
digit
<=
9
counts
[
digit
]
+=
1
return
counts
import
cython
@
cython
.
locals
(
counts
=
cython
.
int
[
10
],
digit
=
cython
.
int
)
def
count_digits
(
digits
):
"""
>>> digits = '01112222333334445667788899'
>>> count_digits(map(int, digits))
[1, 3, 4, 5, 3, 1, 2, 2, 3, 2]
"""
counts
=
[
0
]
*
10
for
digit
in
digits
:
assert
0
<=
digit
<=
9
counts
[
digit
]
+=
1
return
counts
docs/examples/tutorial/pure/cclass.py
View file @
b67e5567
import
cython
@
cython
.
cclass
class
A
:
cython
.
declare
(
a
=
cython
.
int
,
b
=
cython
.
int
)
c
=
cython
.
declare
(
cython
.
int
,
visibility
=
'public'
)
d
=
cython
.
declare
(
cython
.
int
)
# private by default.
e
=
cython
.
declare
(
cython
.
int
,
visibility
=
'readonly'
)
def
__init__
(
self
,
a
,
b
,
c
,
d
=
5
,
e
=
3
):
self
.
a
=
a
self
.
b
=
b
self
.
c
=
c
self
.
d
=
d
self
.
e
=
e
import
cython
@
cython
.
cclass
class
A
:
cython
.
declare
(
a
=
cython
.
int
,
b
=
cython
.
int
)
c
=
cython
.
declare
(
cython
.
int
,
visibility
=
'public'
)
d
=
cython
.
declare
(
cython
.
int
)
# private by default.
e
=
cython
.
declare
(
cython
.
int
,
visibility
=
'readonly'
)
def
__init__
(
self
,
a
,
b
,
c
,
d
=
5
,
e
=
3
):
self
.
a
=
a
self
.
b
=
b
self
.
c
=
c
self
.
d
=
d
self
.
e
=
e
docs/examples/tutorial/pure/compiled_switch.py
View file @
b67e5567
import
cython
if
cython
.
compiled
:
print
(
"Yep, I'm compiled."
)
else
:
print
(
"Just a lowly interpreted script."
)
import
cython
if
cython
.
compiled
:
print
(
"Yep, I'm compiled."
)
else
:
print
(
"Just a lowly interpreted script."
)
docs/examples/tutorial/pure/cython_declare.py
View file @
b67e5567
import
cython
x
=
cython
.
declare
(
cython
.
int
)
# cdef int x
y
=
cython
.
declare
(
cython
.
double
,
0.57721
)
# cdef double y = 0.57721
import
cython
x
=
cython
.
declare
(
cython
.
int
)
# cdef int x
y
=
cython
.
declare
(
cython
.
double
,
0.57721
)
# cdef double y = 0.57721
docs/examples/tutorial/pure/cython_declare2.py
View file @
b67e5567
import
cython
cython
.
declare
(
x
=
cython
.
int
,
y
=
cython
.
double
)
# cdef int x; cdef double y
import
cython
cython
.
declare
(
x
=
cython
.
int
,
y
=
cython
.
double
)
# cdef int x; cdef double y
docs/examples/tutorial/pure/dostuff.py
View file @
b67e5567
def
dostuff
(
n
):
t
=
0
for
i
in
range
(
n
):
t
+=
i
return
t
def
dostuff
(
n
):
t
=
0
for
i
in
range
(
n
):
t
+=
i
return
t
docs/examples/tutorial/pure/exceptval.py
View file @
b67e5567
import
cython
@
cython
.
exceptval
(
-
1
)
def
func
(
x
:
cython
.
int
)
->
cython
.
int
:
if
x
<
0
:
raise
ValueError
(
"need integer >= 0"
)
return
x
+
1
import
cython
@
cython
.
exceptval
(
-
1
)
def
func
(
x
:
cython
.
int
)
->
cython
.
int
:
if
x
<
0
:
raise
ValueError
(
"need integer >= 0"
)
return
x
+
1
docs/examples/tutorial/pure/locals.py
View file @
b67e5567
import
cython
@
cython
.
locals
(
a
=
cython
.
long
,
b
=
cython
.
long
,
n
=
cython
.
longlong
)
def
foo
(
a
,
b
,
x
,
y
):
n
=
a
*
b
# ...
import
cython
@
cython
.
locals
(
a
=
cython
.
long
,
b
=
cython
.
long
,
n
=
cython
.
longlong
)
def
foo
(
a
,
b
,
x
,
y
):
n
=
a
*
b
# ...
docs/examples/tutorial/pure/mymodule.py
View file @
b67e5567
# mymodule.py
import
cython
# override with Python import if not in compiled code
if
not
cython
.
compiled
:
from
math
import
sin
# calls sin() from math.h when compiled with Cython and math.sin() in Python
print
(
sin
(
0
))
# mymodule.py
import
cython
# override with Python import if not in compiled code
if
not
cython
.
compiled
:
from
math
import
sin
# calls sin() from math.h when compiled with Cython and math.sin() in Python
print
(
sin
(
0
))
docs/examples/tutorial/pure/pep_526.py
View file @
b67e5567
import
cython
def
func
():
# Cython types are evaluated as for cdef declarations
x
:
cython
.
int
# cdef int x
y
:
cython
.
double
=
0.57721
# cdef double y = 0.57721
z
:
cython
.
float
=
0.57721
# cdef float z = 0.57721
# Python types shadow Cython types for compatibility reasons
a
:
float
=
0.54321
# cdef double a = 0.54321
b
:
int
=
5
# cdef object b = 5
c
:
long
=
6
# cdef object c = 6
pass
@
cython
.
cclass
class
A
:
a
:
cython
.
int
b
:
cython
.
int
def
__init__
(
self
,
b
=
0
):
self
.
a
=
3
self
.
b
=
b
import
cython
def
func
():
# Cython types are evaluated as for cdef declarations
x
:
cython
.
int
# cdef int x
y
:
cython
.
double
=
0.57721
# cdef double y = 0.57721
z
:
cython
.
float
=
0.57721
# cdef float z = 0.57721
# Python types shadow Cython types for compatibility reasons
a
:
float
=
0.54321
# cdef double a = 0.54321
b
:
int
=
5
# cdef object b = 5
c
:
long
=
6
# cdef object c = 6
pass
@
cython
.
cclass
class
A
:
a
:
cython
.
int
b
:
cython
.
int
def
__init__
(
self
,
b
=
0
):
self
.
a
=
3
self
.
b
=
b
docs/examples/tutorial/string/api_func.pyx
View file @
b67e5567
from
to_unicode
cimport
_text
def
api_func
(
s
):
text_input
=
_text
(
s
)
# ...
from
to_unicode
cimport
_text
def
api_func
(
s
):
text_input
=
_text
(
s
)
# ...
docs/examples/tutorial/string/arg_memview.pyx
View file @
b67e5567
def
process_byte_data
(
unsigned
char
[:]
data
):
length
=
data
.
shape
[
0
]
first_byte
=
data
[
0
]
slice_view
=
data
[
1
:
-
1
]
# ...
def
process_byte_data
(
unsigned
char
[:]
data
):
length
=
data
.
shape
[
0
]
first_byte
=
data
[
0
]
slice_view
=
data
[
1
:
-
1
]
# ...
docs/examples/tutorial/string/auto_conversion_1.pyx
View file @
b67e5567
# cython: c_string_type=unicode, c_string_encoding=utf8
cdef
char
*
c_string
=
'abcdefg'
# implicit decoding:
cdef
object
py_unicode_object
=
c_string
# explicit conversion to Python bytes:
py_bytes_object
=
<
bytes
>
c_string
# cython: c_string_type=unicode, c_string_encoding=utf8
cdef
char
*
c_string
=
'abcdefg'
# implicit decoding:
cdef
object
py_unicode_object
=
c_string
# explicit conversion to Python bytes:
py_bytes_object
=
<
bytes
>
c_string
docs/examples/tutorial/string/auto_conversion_2.pyx
View file @
b67e5567
# cython: c_string_type=str, c_string_encoding=ascii
cdef
char
*
c_string
=
'abcdefg'
# implicit decoding in Py3, bytes conversion in Py2:
cdef
object
py_str_object
=
c_string
# explicit conversion to Python bytes:
py_bytes_object
=
<
bytes
>
c_string
# explicit conversion to Python unicode:
py_bytes_object
=
<
unicode
>
c_string
# cython: c_string_type=str, c_string_encoding=ascii
cdef
char
*
c_string
=
'abcdefg'
# implicit decoding in Py3, bytes conversion in Py2:
cdef
object
py_str_object
=
c_string
# explicit conversion to Python bytes:
py_bytes_object
=
<
bytes
>
c_string
# explicit conversion to Python unicode:
py_bytes_object
=
<
unicode
>
c_string
docs/examples/tutorial/string/auto_conversion_3.pyx
View file @
b67e5567
# cython: c_string_type=unicode, c_string_encoding=ascii
def
func
():
ustring
=
u'abc'
cdef
char
*
s
=
ustring
return
s
[
0
]
# returns u'a'
# cython: c_string_type=unicode, c_string_encoding=ascii
def
func
():
ustring
=
u'abc'
cdef
char
*
s
=
ustring
return
s
[
0
]
# returns u'a'
docs/examples/tutorial/string/c_func.pyx
View file @
b67e5567
from
libc.stdlib
cimport
malloc
from
libc.string
cimport
strcpy
,
strlen
cdef
char
*
hello_world
=
'hello world'
cdef
Py_ssize_t
n
=
strlen
(
hello_world
)
cdef
char
*
c_call_returning_a_c_string
():
cdef
char
*
c_string
=
<
char
*>
malloc
((
n
+
1
)
*
sizeof
(
char
))
if
not
c_string
:
raise
MemoryError
()
strcpy
(
c_string
,
hello_world
)
return
c_string
cdef
void
get_a_c_string
(
char
**
c_string_ptr
,
Py_ssize_t
*
length
):
c_string_ptr
[
0
]
=
<
char
*>
malloc
((
n
+
1
)
*
sizeof
(
char
))
if
not
c_string_ptr
[
0
]:
raise
MemoryError
()
strcpy
(
c_string_ptr
[
0
],
hello_world
)
length
[
0
]
=
n
from
libc.stdlib
cimport
malloc
from
libc.string
cimport
strcpy
,
strlen
cdef
char
*
hello_world
=
'hello world'
cdef
Py_ssize_t
n
=
strlen
(
hello_world
)
cdef
char
*
c_call_returning_a_c_string
():
cdef
char
*
c_string
=
<
char
*>
malloc
((
n
+
1
)
*
sizeof
(
char
))
if
not
c_string
:
raise
MemoryError
()
strcpy
(
c_string
,
hello_world
)
return
c_string
cdef
void
get_a_c_string
(
char
**
c_string_ptr
,
Py_ssize_t
*
length
):
c_string_ptr
[
0
]
=
<
char
*>
malloc
((
n
+
1
)
*
sizeof
(
char
))
if
not
c_string_ptr
[
0
]:
raise
MemoryError
()
strcpy
(
c_string_ptr
[
0
],
hello_world
)
length
[
0
]
=
n
docs/examples/tutorial/string/const.pyx
View file @
b67e5567
cdef
extern
from
"someheader.h"
:
ctypedef
const
char
specialChar
int
process_string
(
const
char
*
s
)
const
unsigned
char
*
look_up_cached_string
(
const
unsigned
char
*
key
)
cdef
extern
from
"someheader.h"
:
ctypedef
const
char
specialChar
int
process_string
(
const
char
*
s
)
const
unsigned
char
*
look_up_cached_string
(
const
unsigned
char
*
key
)
docs/examples/tutorial/string/cpp_string.pyx
View file @
b67e5567
# distutils: language = c++
from
libcpp.string
cimport
string
def
get_bytes
():
py_bytes_object
=
b'hello world'
cdef
string
s
=
py_bytes_object
s
.
append
(
'abc'
)
py_bytes_object
=
s
return
py_bytes_object
# distutils: language = c++
from
libcpp.string
cimport
string
def
get_bytes
():
py_bytes_object
=
b'hello world'
cdef
string
s
=
py_bytes_object
s
.
append
(
'abc'
)
py_bytes_object
=
s
return
py_bytes_object
docs/examples/tutorial/string/decode.pyx
View file @
b67e5567
from
c_func
cimport
get_a_c_string
cdef
char
*
c_string
=
NULL
cdef
Py_ssize_t
length
=
0
# get pointer and length from a C function
get_a_c_string
(
&
c_string
,
&
length
)
ustring
=
c_string
[:
length
].
decode
(
'UTF-8'
)
from
c_func
cimport
get_a_c_string
cdef
char
*
c_string
=
NULL
cdef
Py_ssize_t
length
=
0
# get pointer and length from a C function
get_a_c_string
(
&
c_string
,
&
length
)
ustring
=
c_string
[:
length
].
decode
(
'UTF-8'
)
docs/examples/tutorial/string/decode_cpp_string.pyx
View file @
b67e5567
# distutils: language = c++
from
libcpp.string
cimport
string
def
get_ustrings
():
cdef
string
s
=
string
(
b'abcdefg'
)
ustring1
=
s
.
decode
(
'UTF-8'
)
ustring2
=
s
[
2
:
-
2
].
decode
(
'UTF-8'
)
return
ustring1
,
ustring2
# distutils: language = c++
from
libcpp.string
cimport
string
def
get_ustrings
():
cdef
string
s
=
string
(
b'abcdefg'
)
ustring1
=
s
.
decode
(
'UTF-8'
)
ustring2
=
s
[
2
:
-
2
].
decode
(
'UTF-8'
)
return
ustring1
,
ustring2
docs/examples/tutorial/string/for_bytes.pyx
View file @
b67e5567
cdef
bytes
bytes_string
=
b"hello to A bytes' world"
cdef
char
c
for
c
in
bytes_string
:
if
c
==
'A'
:
print
(
"Found the letter A"
)
cdef
bytes
bytes_string
=
b"hello to A bytes' world"
cdef
char
c
for
c
in
bytes_string
:
if
c
==
'A'
:
print
(
"Found the letter A"
)
docs/examples/tutorial/string/for_char.pyx
View file @
b67e5567
cdef
char
*
c_string
=
"Hello to A C-string's world"
cdef
char
c
for
c
in
c_string
[:
11
]:
if
c
==
'A'
:
print
(
"Found the letter A"
)
cdef
char
*
c_string
=
"Hello to A C-string's world"
cdef
char
c
for
c
in
c_string
[:
11
]:
if
c
==
'A'
:
print
(
"Found the letter A"
)
docs/examples/tutorial/string/for_unicode.pyx
View file @
b67e5567
cdef
unicode
ustring
=
u'Hello world'
# NOTE: no typing required for 'uchar' !
for
uchar
in
ustring
:
if
uchar
==
u'A'
:
print
(
"Found the letter A"
)
cdef
unicode
ustring
=
u'Hello world'
# NOTE: no typing required for 'uchar' !
for
uchar
in
ustring
:
if
uchar
==
u'A'
:
print
(
"Found the letter A"
)
docs/examples/tutorial/string/if_char_in.pyx
View file @
b67e5567
cpdef
void
is_in
(
Py_UCS4
uchar_val
):
if
uchar_val
in
u'abcABCxY'
:
print
(
"The character is in the string."
)
else
:
print
(
"The character is not in the string"
)
cpdef
void
is_in
(
Py_UCS4
uchar_val
):
if
uchar_val
in
u'abcABCxY'
:
print
(
"The character is in the string."
)
else
:
print
(
"The character is not in the string"
)
docs/examples/tutorial/string/naive_decode.pyx
View file @
b67e5567
from
c_func
cimport
c_call_returning_a_c_string
cdef
char
*
some_c_string
=
c_call_returning_a_c_string
()
ustring
=
some_c_string
.
decode
(
'UTF-8'
)
from
c_func
cimport
c_call_returning_a_c_string
cdef
char
*
some_c_string
=
c_call_returning_a_c_string
()
ustring
=
some_c_string
.
decode
(
'UTF-8'
)
docs/examples/tutorial/string/return_memview.pyx
View file @
b67e5567
def
process_byte_data
(
unsigned
char
[:]
data
):
# ... process the data, here, dummy processing.
cdef
bint
return_all
=
(
data
[
0
]
==
108
)
if
return_all
:
return
bytes
(
data
)
else
:
# example for returning a slice
return
bytes
(
data
[
5
:
7
])
def
process_byte_data
(
unsigned
char
[:]
data
):
# ... process the data, here, dummy processing.
cdef
bint
return_all
=
(
data
[
0
]
==
108
)
if
return_all
:
return
bytes
(
data
)
else
:
# example for returning a slice
return
bytes
(
data
[
5
:
7
])
docs/examples/tutorial/string/slicing_c_string.pyx
View file @
b67e5567
from
libc.stdlib
cimport
free
from
c_func
cimport
get_a_c_string
def
main
():
cdef
char
*
c_string
=
NULL
cdef
Py_ssize_t
length
=
0
# get pointer and length from a C function
get_a_c_string
(
&
c_string
,
&
length
)
try
:
py_bytes_string
=
c_string
[:
length
]
# Performs a copy of the data
finally
:
free
(
c_string
)
from
libc.stdlib
cimport
free
from
c_func
cimport
get_a_c_string
def
main
():
cdef
char
*
c_string
=
NULL
cdef
Py_ssize_t
length
=
0
# get pointer and length from a C function
get_a_c_string
(
&
c_string
,
&
length
)
try
:
py_bytes_string
=
c_string
[:
length
]
# Performs a copy of the data
finally
:
free
(
c_string
)
docs/examples/tutorial/string/to_char.pyx
View file @
b67e5567
# define a global name for whatever char type is used in the module
ctypedef
unsigned
char
char_type
cdef
char_type
[:]
_chars
(
s
):
if
isinstance
(
s
,
unicode
):
# encode to the specific encoding used inside of the module
s
=
(
<
unicode
>
s
).
encode
(
'utf8'
)
return
s
# define a global name for whatever char type is used in the module
ctypedef
unsigned
char
char_type
cdef
char_type
[:]
_chars
(
s
):
if
isinstance
(
s
,
unicode
):
# encode to the specific encoding used inside of the module
s
=
(
<
unicode
>
s
).
encode
(
'utf8'
)
return
s
docs/examples/tutorial/string/to_unicode.pyx
View file @
b67e5567
# to_unicode.pyx
from
cpython.version
cimport
PY_MAJOR_VERSION
cdef
unicode
_text
(
s
):
if
type
(
s
)
is
unicode
:
# Fast path for most common case(s).
return
<
unicode
>
s
elif
PY_MAJOR_VERSION
<
3
and
isinstance
(
s
,
bytes
):
# Only accept byte strings as text input in Python 2.x, not in Py3.
return
(
<
bytes
>
s
).
decode
(
'ascii'
)
elif
isinstance
(
s
,
unicode
):
# We know from the fast path above that 's' can only be a subtype here.
# An evil cast to <unicode> might still work in some(!) cases,
# depending on what the further processing does. To be safe,
# we can always create a copy instead.
return
unicode
(
s
)
else
:
raise
TypeError
(
"Could not convert to unicode."
)
# to_unicode.pyx
from
cpython.version
cimport
PY_MAJOR_VERSION
cdef
unicode
_text
(
s
):
if
type
(
s
)
is
unicode
:
# Fast path for most common case(s).
return
<
unicode
>
s
elif
PY_MAJOR_VERSION
<
3
and
isinstance
(
s
,
bytes
):
# Only accept byte strings as text input in Python 2.x, not in Py3.
return
(
<
bytes
>
s
).
decode
(
'ascii'
)
elif
isinstance
(
s
,
unicode
):
# We know from the fast path above that 's' can only be a subtype here.
# An evil cast to <unicode> might still work in some(!) cases,
# depending on what the further processing does. To be safe,
# we can always create a copy instead.
return
unicode
(
s
)
else
:
raise
TypeError
(
"Could not convert to unicode."
)
docs/examples/tutorial/string/try_finally.pyx
View file @
b67e5567
from
libc.stdlib
cimport
free
from
c_func
cimport
c_call_returning_a_c_string
cdef
bytes
py_string
cdef
char
*
c_string
=
c_call_returning_a_c_string
()
try
:
py_string
=
c_string
finally
:
free
(
c_string
)
from
libc.stdlib
cimport
free
from
c_func
cimport
c_call_returning_a_c_string
cdef
bytes
py_string
cdef
char
*
c_string
=
c_call_returning_a_c_string
()
try
:
py_string
=
c_string
finally
:
free
(
c_string
)
docs/examples/tutorial/string/utf_eight.pyx
View file @
b67e5567
from
libc.stdlib
cimport
free
cdef
unicode
tounicode
(
char
*
s
):
return
s
.
decode
(
'UTF-8'
,
'strict'
)
cdef
unicode
tounicode_with_length
(
char
*
s
,
size_t
length
):
return
s
[:
length
].
decode
(
'UTF-8'
,
'strict'
)
cdef
unicode
tounicode_with_length_and_free
(
char
*
s
,
size_t
length
):
try
:
return
s
[:
length
].
decode
(
'UTF-8'
,
'strict'
)
finally
:
from
libc.stdlib
cimport
free
cdef
unicode
tounicode
(
char
*
s
):
return
s
.
decode
(
'UTF-8'
,
'strict'
)
cdef
unicode
tounicode_with_length
(
char
*
s
,
size_t
length
):
return
s
[:
length
].
decode
(
'UTF-8'
,
'strict'
)
cdef
unicode
tounicode_with_length_and_free
(
char
*
s
,
size_t
length
):
try
:
return
s
[:
length
].
decode
(
'UTF-8'
,
'strict'
)
finally
:
free
(
s
)
\ No newline at end of file
docs/examples/userguide/buffer/matrix.pyx
View file @
b67e5567
# distutils: language = c++
# matrix.pyx
from
libcpp.vector
cimport
vector
cdef
class
Matrix
:
cdef
unsigned
ncols
cdef
vector
[
float
]
v
def
__cinit__
(
self
,
unsigned
ncols
):
self
.
ncols
=
ncols
def
add_row
(
self
):
"""Adds a row, initially zero-filled."""
self
.
v
.
resize
(
self
.
v
.
size
()
+
self
.
ncols
)
# distutils: language = c++
# matrix.pyx
from
libcpp.vector
cimport
vector
cdef
class
Matrix
:
cdef
unsigned
ncols
cdef
vector
[
float
]
v
def
__cinit__
(
self
,
unsigned
ncols
):
self
.
ncols
=
ncols
def
add_row
(
self
):
"""Adds a row, initially zero-filled."""
self
.
v
.
resize
(
self
.
v
.
size
()
+
self
.
ncols
)
docs/examples/userguide/buffer/matrix_with_buffer.pyx
View file @
b67e5567
# distutils: language = c++
from
cpython
cimport
Py_buffer
from
libcpp.vector
cimport
vector
cdef
class
Matrix
:
cdef
Py_ssize_t
ncols
cdef
Py_ssize_t
shape
[
2
]
cdef
Py_ssize_t
strides
[
2
]
cdef
vector
[
float
]
v
def
__cinit__
(
self
,
Py_ssize_t
ncols
):
self
.
ncols
=
ncols
def
add_row
(
self
):
"""Adds a row, initially zero-filled."""
self
.
v
.
resize
(
self
.
v
.
size
()
+
self
.
ncols
)
def
__getbuffer__
(
self
,
Py_buffer
*
buffer
,
int
flags
):
cdef
Py_ssize_t
itemsize
=
sizeof
(
self
.
v
[
0
])
self
.
shape
[
0
]
=
self
.
v
.
size
()
/
self
.
ncols
self
.
shape
[
1
]
=
self
.
ncols
# Stride 1 is the distance, in bytes, between two items in a row;
# this is the distance between two adjacent items in the vector.
# Stride 0 is the distance between the first elements of adjacent rows.
self
.
strides
[
1
]
=
<
Py_ssize_t
>
(
<
char
*>&
(
self
.
v
[
1
])
-
<
char
*>&
(
self
.
v
[
0
]))
self
.
strides
[
0
]
=
self
.
ncols
*
self
.
strides
[
1
]
buffer
.
buf
=
<
char
*>&
(
self
.
v
[
0
])
buffer
.
format
=
'f'
# float
buffer
.
internal
=
NULL
# see References
buffer
.
itemsize
=
itemsize
buffer
.
len
=
self
.
v
.
size
()
*
itemsize
# product(shape) * itemsize
buffer
.
ndim
=
2
buffer
.
obj
=
self
buffer
.
readonly
=
0
buffer
.
shape
=
self
.
shape
buffer
.
strides
=
self
.
strides
buffer
.
suboffsets
=
NULL
# for pointer arrays only
def
__releasebuffer__
(
self
,
Py_buffer
*
buffer
):
pass
# distutils: language = c++
from
cpython
cimport
Py_buffer
from
libcpp.vector
cimport
vector
cdef
class
Matrix
:
cdef
Py_ssize_t
ncols
cdef
Py_ssize_t
shape
[
2
]
cdef
Py_ssize_t
strides
[
2
]
cdef
vector
[
float
]
v
def
__cinit__
(
self
,
Py_ssize_t
ncols
):
self
.
ncols
=
ncols
def
add_row
(
self
):
"""Adds a row, initially zero-filled."""
self
.
v
.
resize
(
self
.
v
.
size
()
+
self
.
ncols
)
def
__getbuffer__
(
self
,
Py_buffer
*
buffer
,
int
flags
):
cdef
Py_ssize_t
itemsize
=
sizeof
(
self
.
v
[
0
])
self
.
shape
[
0
]
=
self
.
v
.
size
()
/
self
.
ncols
self
.
shape
[
1
]
=
self
.
ncols
# Stride 1 is the distance, in bytes, between two items in a row;
# this is the distance between two adjacent items in the vector.
# Stride 0 is the distance between the first elements of adjacent rows.
self
.
strides
[
1
]
=
<
Py_ssize_t
>
(
<
char
*>&
(
self
.
v
[
1
])
-
<
char
*>&
(
self
.
v
[
0
]))
self
.
strides
[
0
]
=
self
.
ncols
*
self
.
strides
[
1
]
buffer
.
buf
=
<
char
*>&
(
self
.
v
[
0
])
buffer
.
format
=
'f'
# float
buffer
.
internal
=
NULL
# see References
buffer
.
itemsize
=
itemsize
buffer
.
len
=
self
.
v
.
size
()
*
itemsize
# product(shape) * itemsize
buffer
.
ndim
=
2
buffer
.
obj
=
self
buffer
.
readonly
=
0
buffer
.
shape
=
self
.
shape
buffer
.
strides
=
self
.
strides
buffer
.
suboffsets
=
NULL
# for pointer arrays only
def
__releasebuffer__
(
self
,
Py_buffer
*
buffer
):
pass
docs/examples/userguide/buffer/view_count.pyx
View file @
b67e5567
# distutils: language = c++
from
cpython
cimport
Py_buffer
from
libcpp.vector
cimport
vector
cdef
class
Matrix
:
cdef
int
view_count
cdef
Py_ssize_t
ncols
cdef
vector
[
float
]
v
# ...
def
__cinit__
(
self
,
Py_ssize_t
ncols
):
self
.
ncols
=
ncols
self
.
view_count
=
0
def
add_row
(
self
):
if
self
.
view_count
>
0
:
raise
ValueError
(
"can't add row while being viewed"
)
self
.
v
.
resize
(
self
.
v
.
size
()
+
self
.
ncols
)
def
__getbuffer__
(
self
,
Py_buffer
*
buffer
,
int
flags
):
# ... as before
self
.
view_count
+=
1
def
__releasebuffer__
(
self
,
Py_buffer
*
buffer
):
# distutils: language = c++
from
cpython
cimport
Py_buffer
from
libcpp.vector
cimport
vector
cdef
class
Matrix
:
cdef
int
view_count
cdef
Py_ssize_t
ncols
cdef
vector
[
float
]
v
# ...
def
__cinit__
(
self
,
Py_ssize_t
ncols
):
self
.
ncols
=
ncols
self
.
view_count
=
0
def
add_row
(
self
):
if
self
.
view_count
>
0
:
raise
ValueError
(
"can't add row while being viewed"
)
self
.
v
.
resize
(
self
.
v
.
size
()
+
self
.
ncols
)
def
__getbuffer__
(
self
,
Py_buffer
*
buffer
,
int
flags
):
# ... as before
self
.
view_count
+=
1
def
__releasebuffer__
(
self
,
Py_buffer
*
buffer
):
self
.
view_count
-=
1
\ No newline at end of file
docs/examples/userguide/early_binding_for_speed/rectangle.pyx
View file @
b67e5567
cdef
class
Rectangle
:
cdef
int
x0
,
y0
cdef
int
x1
,
y1
def
__init__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
x0
=
x0
self
.
y0
=
y0
self
.
x1
=
x1
self
.
y1
=
y1
def
area
(
self
):
area
=
(
self
.
x1
-
self
.
x0
)
*
(
self
.
y1
-
self
.
y0
)
if
area
<
0
:
area
=
-
area
return
area
def
rectArea
(
x0
,
y0
,
x1
,
y1
):
rect
=
Rectangle
(
x0
,
y0
,
x1
,
y1
)
return
rect
.
area
()
cdef
class
Rectangle
:
cdef
int
x0
,
y0
cdef
int
x1
,
y1
def
__init__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
x0
=
x0
self
.
y0
=
y0
self
.
x1
=
x1
self
.
y1
=
y1
def
area
(
self
):
area
=
(
self
.
x1
-
self
.
x0
)
*
(
self
.
y1
-
self
.
y0
)
if
area
<
0
:
area
=
-
area
return
area
def
rectArea
(
x0
,
y0
,
x1
,
y1
):
rect
=
Rectangle
(
x0
,
y0
,
x1
,
y1
)
return
rect
.
area
()
docs/examples/userguide/early_binding_for_speed/rectangle_cdef.pyx
View file @
b67e5567
cdef
class
Rectangle
:
cdef
int
x0
,
y0
cdef
int
x1
,
y1
def
__init__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
x0
=
x0
self
.
y0
=
y0
self
.
x1
=
x1
self
.
y1
=
y1
cdef
int
_area
(
self
):
area
=
(
self
.
x1
-
self
.
x0
)
*
(
self
.
y1
-
self
.
y0
)
if
area
<
0
:
area
=
-
area
return
area
def
area
(
self
):
return
self
.
_area
()
def
rectArea
(
x0
,
y0
,
x1
,
y1
):
cdef
Rectangle
rect
=
Rectangle
(
x0
,
y0
,
x1
,
y1
)
return
rect
.
_area
()
cdef
class
Rectangle
:
cdef
int
x0
,
y0
cdef
int
x1
,
y1
def
__init__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
x0
=
x0
self
.
y0
=
y0
self
.
x1
=
x1
self
.
y1
=
y1
cdef
int
_area
(
self
):
area
=
(
self
.
x1
-
self
.
x0
)
*
(
self
.
y1
-
self
.
y0
)
if
area
<
0
:
area
=
-
area
return
area
def
area
(
self
):
return
self
.
_area
()
def
rectArea
(
x0
,
y0
,
x1
,
y1
):
cdef
Rectangle
rect
=
Rectangle
(
x0
,
y0
,
x1
,
y1
)
return
rect
.
_area
()
docs/examples/userguide/early_binding_for_speed/rectangle_cpdef.pyx
View file @
b67e5567
cdef
class
Rectangle
:
cdef
int
x0
,
y0
cdef
int
x1
,
y1
def
__init__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
x0
=
x0
self
.
y0
=
y0
self
.
x1
=
x1
self
.
y1
=
y1
cpdef
int
area
(
self
):
area
=
(
self
.
x1
-
self
.
x0
)
*
(
self
.
y1
-
self
.
y0
)
if
area
<
0
:
area
=
-
area
return
area
def
rectArea
(
x0
,
y0
,
x1
,
y1
):
cdef
Rectangle
rect
=
Rectangle
(
x0
,
y0
,
x1
,
y1
)
return
rect
.
area
()
cdef
class
Rectangle
:
cdef
int
x0
,
y0
cdef
int
x1
,
y1
def
__init__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
x0
=
x0
self
.
y0
=
y0
self
.
x1
=
x1
self
.
y1
=
y1
cpdef
int
area
(
self
):
area
=
(
self
.
x1
-
self
.
x0
)
*
(
self
.
y1
-
self
.
y0
)
if
area
<
0
:
area
=
-
area
return
area
def
rectArea
(
x0
,
y0
,
x1
,
y1
):
cdef
Rectangle
rect
=
Rectangle
(
x0
,
y0
,
x1
,
y1
)
return
rect
.
area
()
docs/examples/userguide/extension_types/dict_animal.pyx
View file @
b67e5567
cdef
class
Animal
:
cdef
int
number_of_legs
cdef
dict
__dict__
def
__cinit__
(
self
,
int
number_of_legs
):
self
.
number_of_legs
=
number_of_legs
dog
=
Animal
(
4
)
dog
.
has_tail
=
True
cdef
class
Animal
:
cdef
int
number_of_legs
cdef
dict
__dict__
def
__cinit__
(
self
,
int
number_of_legs
):
self
.
number_of_legs
=
number_of_legs
dog
=
Animal
(
4
)
dog
.
has_tail
=
True
docs/examples/userguide/extension_types/extendable_animal.pyx
View file @
b67e5567
cdef
class
Animal
:
cdef
int
number_of_legs
def
__cinit__
(
self
,
int
number_of_legs
):
self
.
number_of_legs
=
number_of_legs
class
ExtendableAnimal
(
Animal
):
# Note that we use class, not cdef class
pass
dog
=
ExtendableAnimal
(
4
)
cdef
class
Animal
:
cdef
int
number_of_legs
def
__cinit__
(
self
,
int
number_of_legs
):
self
.
number_of_legs
=
number_of_legs
class
ExtendableAnimal
(
Animal
):
# Note that we use class, not cdef class
pass
dog
=
ExtendableAnimal
(
4
)
dog
.
has_tail
=
True
\ No newline at end of file
docs/examples/userguide/extension_types/my_module.pyx
View file @
b67e5567
from
__future__
import
print_function
cdef
class
Shrubbery
:
def
__init__
(
self
,
w
,
h
):
self
.
width
=
w
self
.
height
=
h
def
describe
(
self
):
print
(
"This shrubbery is"
,
self
.
width
,
"by"
,
self
.
height
,
"cubits."
)
from
__future__
import
print_function
cdef
class
Shrubbery
:
def
__init__
(
self
,
w
,
h
):
self
.
width
=
w
self
.
height
=
h
def
describe
(
self
):
print
(
"This shrubbery is"
,
self
.
width
,
"by"
,
self
.
height
,
"cubits."
)
docs/examples/userguide/extension_types/python_access.pyx
View file @
b67e5567
cdef
class
Shrubbery
:
cdef
public
int
width
,
height
cdef
readonly
float
depth
cdef
class
Shrubbery
:
cdef
public
int
width
,
height
cdef
readonly
float
depth
docs/examples/userguide/extension_types/shrubbery.pyx
View file @
b67e5567
from
__future__
import
print_function
cdef
class
Shrubbery
:
cdef
int
width
,
height
def
__init__
(
self
,
w
,
h
):
self
.
width
=
w
self
.
height
=
h
def
describe
(
self
):
print
(
"This shrubbery is"
,
self
.
width
,
"by"
,
self
.
height
,
"cubits."
)
from
__future__
import
print_function
cdef
class
Shrubbery
:
cdef
int
width
,
height
def
__init__
(
self
,
w
,
h
):
self
.
width
=
w
self
.
height
=
h
def
describe
(
self
):
print
(
"This shrubbery is"
,
self
.
width
,
"by"
,
self
.
height
,
"cubits."
)
docs/examples/userguide/extension_types/shrubbery_2.pyx
View file @
b67e5567
from
my_module
cimport
Shrubbery
cdef
Shrubbery
another_shrubbery
(
Shrubbery
sh1
):
cdef
Shrubbery
sh2
sh2
=
Shrubbery
()
sh2
.
width
=
sh1
.
width
sh2
.
height
=
sh1
.
height
return
sh2
from
my_module
cimport
Shrubbery
cdef
Shrubbery
another_shrubbery
(
Shrubbery
sh1
):
cdef
Shrubbery
sh2
sh2
=
Shrubbery
()
sh2
.
width
=
sh1
.
width
sh2
.
height
=
sh1
.
height
return
sh2
docs/examples/userguide/extension_types/widen_shrubbery.pyx
View file @
b67e5567
from
my_module
cimport
Shrubbery
cdef
widen_shrubbery
(
Shrubbery
sh
,
extra_width
):
sh
.
width
=
sh
.
width
+
extra_width
from
my_module
cimport
Shrubbery
cdef
widen_shrubbery
(
Shrubbery
sh
,
extra_width
):
sh
.
width
=
sh
.
width
+
extra_width
docs/examples/userguide/external_C_code/c_code_docstring.pyx
View file @
b67e5567
cdef
extern
from
*
:
"""
/* This is C code which will be put
* in the .c file output by Cython */
static long square(long x) {return x * x;}
#define assign(x, y) ((x) = (y))
"""
long
square
(
long
x
)
void
assign
(
long
&
x
,
long
y
)
cdef
extern
from
*
:
"""
/* This is C code which will be put
* in the .c file output by Cython */
static long square(long x) {return x * x;}
#define assign(x, y) ((x) = (y))
"""
long
square
(
long
x
)
void
assign
(
long
&
x
,
long
y
)
docs/examples/userguide/external_C_code/delorean.pyx
View file @
b67e5567
# delorean.pyx
cdef
public
struct
Vehicle
:
int
speed
float
power
cdef
api
void
activate
(
Vehicle
*
v
):
if
v
.
speed
>=
88
and
v
.
power
>=
1.21
:
# delorean.pyx
cdef
public
struct
Vehicle
:
int
speed
float
power
cdef
api
void
activate
(
Vehicle
*
v
):
if
v
.
speed
>=
88
and
v
.
power
>=
1.21
:
print
(
"Time travel achieved"
)
\ No newline at end of file
docs/examples/userguide/fusedtypes/char_or_float.pyx
View file @
b67e5567
from
__future__
import
print_function
ctypedef
fused
char_or_float
:
char
float
cpdef
char_or_float
plus_one
(
char_or_float
var
):
return
var
+
1
def
show_me
():
cdef
:
char
a
=
127
float
b
=
127
print
(
'char'
,
plus_one
(
a
))
print
(
'float'
,
plus_one
(
b
))
from
__future__
import
print_function
ctypedef
fused
char_or_float
:
char
float
cpdef
char_or_float
plus_one
(
char_or_float
var
):
return
var
+
1
def
show_me
():
cdef
:
char
a
=
127
float
b
=
127
print
(
'char'
,
plus_one
(
a
))
print
(
'float'
,
plus_one
(
b
))
docs/examples/userguide/language_basics/casting_python.pyx
View file @
b67e5567
from
cpython.ref
cimport
PyObject
cdef
extern
from
*
:
ctypedef
Py_ssize_t
Py_intptr_t
python_string
=
"foo"
cdef
void
*
ptr
=
<
void
*>
python_string
cdef
Py_intptr_t
adress_in_c
=
<
Py_intptr_t
>
ptr
address_from_void
=
adress_in_c
# address_from_void is a python int
cdef
PyObject
*
ptr2
=
<
PyObject
*>
python_string
cdef
Py_intptr_t
address_in_c2
=
<
Py_intptr_t
>
ptr2
address_from_PyObject
=
address_in_c2
# address_from_PyObject is a python int
assert
address_from_void
==
address_from_PyObject
==
id
(
python_string
)
print
(
<
object
>
ptr
)
# Prints "foo"
print
(
<
object
>
ptr2
)
# prints "foo"
from
cpython.ref
cimport
PyObject
cdef
extern
from
*
:
ctypedef
Py_ssize_t
Py_intptr_t
python_string
=
"foo"
cdef
void
*
ptr
=
<
void
*>
python_string
cdef
Py_intptr_t
adress_in_c
=
<
Py_intptr_t
>
ptr
address_from_void
=
adress_in_c
# address_from_void is a python int
cdef
PyObject
*
ptr2
=
<
PyObject
*>
python_string
cdef
Py_intptr_t
address_in_c2
=
<
Py_intptr_t
>
ptr2
address_from_PyObject
=
address_in_c2
# address_from_PyObject is a python int
assert
address_from_void
==
address_from_PyObject
==
id
(
python_string
)
print
(
<
object
>
ptr
)
# Prints "foo"
print
(
<
object
>
ptr2
)
# prints "foo"
docs/examples/userguide/language_basics/cdef_block.pyx
View file @
b67e5567
from
__future__
import
print_function
cdef
:
struct
Spam
:
int
tons
int
i
float
a
Spam
*
p
void
f
(
Spam
*
s
):
print
(
s
.
tons
,
"Tons of spam"
)
from
__future__
import
print_function
cdef
:
struct
Spam
:
int
tons
int
i
float
a
Spam
*
p
void
f
(
Spam
*
s
):
print
(
s
.
tons
,
"Tons of spam"
)
docs/examples/userguide/language_basics/compile_time.pyx
View file @
b67e5567
from
__future__
import
print_function
DEF
FavouriteFood
=
u"spam"
DEF
ArraySize
=
42
DEF
OtherArraySize
=
2
*
ArraySize
+
17
cdef
int
a1
[
ArraySize
]
cdef
int
a2
[
OtherArraySize
]
from
__future__
import
print_function
DEF
FavouriteFood
=
u"spam"
DEF
ArraySize
=
42
DEF
OtherArraySize
=
2
*
ArraySize
+
17
cdef
int
a1
[
ArraySize
]
cdef
int
a2
[
OtherArraySize
]
print
(
"I like"
,
FavouriteFood
)
\ No newline at end of file
docs/examples/userguide/language_basics/kwargs_1.pyx
View file @
b67e5567
def
f
(
a
,
b
,
*
args
,
c
,
d
=
42
,
e
,
**
kwds
):
...
# We cannot call f with less verbosity than this.
foo
=
f
(
4
,
"bar"
,
c
=
68
,
e
=
1.0
)
def
f
(
a
,
b
,
*
args
,
c
,
d
=
42
,
e
,
**
kwds
):
...
# We cannot call f with less verbosity than this.
foo
=
f
(
4
,
"bar"
,
c
=
68
,
e
=
1.0
)
docs/examples/userguide/language_basics/kwargs_2.pyx
View file @
b67e5567
def
g
(
a
,
b
,
*
,
c
,
d
):
...
# We cannot call g with less verbosity than this.
foo
=
g
(
4.0
,
"something"
,
c
=
68
,
d
=
"other"
)
def
g
(
a
,
b
,
*
,
c
,
d
):
...
# We cannot call g with less verbosity than this.
foo
=
g
(
4.0
,
"something"
,
c
=
68
,
d
=
"other"
)
docs/examples/userguide/language_basics/open_file.pyx
View file @
b67e5567
from
libc.stdio
cimport
FILE
,
fopen
from
libc.stdlib
cimport
malloc
,
free
from
cpython.exc
cimport
PyErr_SetFromErrnoWithFilenameObject
def
open_file
():
cdef
FILE
*
p
p
=
fopen
(
"spam.txt"
,
"r"
)
if
p
is
NULL
:
PyErr_SetFromErrnoWithFilenameObject
(
OSError
,
"spam.txt"
)
...
def
allocating_memory
(
number
=
10
):
cdef
double
*
my_array
=
<
double
*>
malloc
(
number
*
sizeof
(
double
))
if
not
my_array
:
# same as 'is NULL' above
raise
MemoryError
()
...
free
(
my_array
)
from
libc.stdio
cimport
FILE
,
fopen
from
libc.stdlib
cimport
malloc
,
free
from
cpython.exc
cimport
PyErr_SetFromErrnoWithFilenameObject
def
open_file
():
cdef
FILE
*
p
p
=
fopen
(
"spam.txt"
,
"r"
)
if
p
is
NULL
:
PyErr_SetFromErrnoWithFilenameObject
(
OSError
,
"spam.txt"
)
...
def
allocating_memory
(
number
=
10
):
cdef
double
*
my_array
=
<
double
*>
malloc
(
number
*
sizeof
(
double
))
if
not
my_array
:
# same as 'is NULL' above
raise
MemoryError
()
...
free
(
my_array
)
docs/examples/userguide/language_basics/optional_subclassing.pyx
View file @
b67e5567
from
__future__
import
print_function
cdef
class
A
:
cdef
foo
(
self
):
print
(
"A"
)
cdef
class
B
(
A
):
cdef
foo
(
self
,
x
=
None
):
print
(
"B"
,
x
)
cdef
class
C
(
B
):
cpdef
foo
(
self
,
x
=
True
,
int
k
=
3
):
print
(
"C"
,
x
,
k
)
from
__future__
import
print_function
cdef
class
A
:
cdef
foo
(
self
):
print
(
"A"
)
cdef
class
B
(
A
):
cdef
foo
(
self
,
x
=
None
):
print
(
"B"
,
x
)
cdef
class
C
(
B
):
cpdef
foo
(
self
,
x
=
True
,
int
k
=
3
):
print
(
"C"
,
x
,
k
)
docs/examples/userguide/language_basics/override.pyx
View file @
b67e5567
from
__future__
import
print_function
cdef
class
A
:
cdef
foo
(
self
):
print
(
"A"
)
cdef
class
B
(
A
):
cpdef
foo
(
self
):
print
(
"B"
)
class
C
(
B
):
# NOTE: not cdef class
def
foo
(
self
):
print
(
"C"
)
from
__future__
import
print_function
cdef
class
A
:
cdef
foo
(
self
):
print
(
"A"
)
cdef
class
B
(
A
):
cpdef
foo
(
self
):
print
(
"B"
)
class
C
(
B
):
# NOTE: not cdef class
def
foo
(
self
):
print
(
"C"
)
docs/examples/userguide/language_basics/struct_union_enum.pyx
View file @
b67e5567
cdef
struct
Grail
:
int
age
float
volume
cdef
union
Food
:
char
*
spam
float
*
eggs
cdef
enum
CheeseType
:
cheddar
,
edam
,
camembert
cdef
enum
CheeseState
:
hard
=
1
soft
=
2
runny
=
3
cdef
struct
Grail
:
int
age
float
volume
cdef
union
Food
:
char
*
spam
float
*
eggs
cdef
enum
CheeseType
:
cheddar
,
edam
,
camembert
cdef
enum
CheeseState
:
hard
=
1
soft
=
2
runny
=
3
docs/examples/userguide/memoryviews/add_one.pyx
View file @
b67e5567
import
numpy
as
np
def
add_one
(
int
[:,:]
buf
):
for
x
in
range
(
buf
.
shape
[
0
]):
for
y
in
range
(
buf
.
shape
[
1
]):
buf
[
x
,
y
]
+=
1
# exporting_object must be a Python object
# implementing the buffer interface, e.g. a numpy array.
exporting_object
=
np
.
zeros
((
10
,
20
),
dtype
=
np
.
intc
)
add_one
(
exporting_object
)
import
numpy
as
np
def
add_one
(
int
[:,:]
buf
):
for
x
in
range
(
buf
.
shape
[
0
]):
for
y
in
range
(
buf
.
shape
[
1
]):
buf
[
x
,
y
]
+=
1
# exporting_object must be a Python object
# implementing the buffer interface, e.g. a numpy array.
exporting_object
=
np
.
zeros
((
10
,
20
),
dtype
=
np
.
intc
)
add_one
(
exporting_object
)
docs/examples/userguide/memoryviews/copy.pyx
View file @
b67e5567
import
numpy
as
np
cdef
int
[:,
:,
:]
to_view
,
from_view
to_view
=
np
.
empty
((
20
,
15
,
30
),
dtype
=
np
.
intc
)
from_view
=
np
.
ones
((
20
,
15
,
30
),
dtype
=
np
.
intc
)
# copy the elements in from_view to to_view
to_view
[...]
=
from_view
# or
to_view
[:]
=
from_view
# or
to_view
[:,
:,
:]
=
from_view
import
numpy
as
np
cdef
int
[:,
:,
:]
to_view
,
from_view
to_view
=
np
.
empty
((
20
,
15
,
30
),
dtype
=
np
.
intc
)
from_view
=
np
.
ones
((
20
,
15
,
30
),
dtype
=
np
.
intc
)
# copy the elements in from_view to to_view
to_view
[...]
=
from_view
# or
to_view
[:]
=
from_view
# or
to_view
[:,
:,
:]
=
from_view
docs/examples/userguide/memoryviews/memory_layout.pyx
View file @
b67e5567
from
cython
cimport
view
# direct access in both dimensions, strided in the first dimension, contiguous in the last
cdef
int
[:,
::
view
.
contiguous
]
a
# contiguous list of pointers to contiguous lists of ints
cdef
int
[::
view
.
indirect_contiguous
,
::
1
]
b
# direct or indirect in the first dimension, direct in the second dimension
# strided in both dimensions
cdef
int
[::
view
.
generic
,
:]
c
from
cython
cimport
view
# direct access in both dimensions, strided in the first dimension, contiguous in the last
cdef
int
[:,
::
view
.
contiguous
]
a
# contiguous list of pointers to contiguous lists of ints
cdef
int
[::
view
.
indirect_contiguous
,
::
1
]
b
# direct or indirect in the first dimension, direct in the second dimension
# strided in both dimensions
cdef
int
[::
view
.
generic
,
:]
c
docs/examples/userguide/memoryviews/memory_layout_2.pyx
View file @
b67e5567
from
cython
cimport
view
# VALID
cdef
int
[::
view
.
indirect
,
::
1
,
:]
a
cdef
int
[::
view
.
indirect
,
:,
::
1
]
b
cdef
int
[::
view
.
indirect_contiguous
,
::
1
,
:]
c
from
cython
cimport
view
# VALID
cdef
int
[::
view
.
indirect
,
::
1
,
:]
a
cdef
int
[::
view
.
indirect
,
:,
::
1
]
b
cdef
int
[::
view
.
indirect_contiguous
,
::
1
,
:]
c
docs/examples/userguide/memoryviews/memview_to_c.pyx
View file @
b67e5567
cdef
extern
from
"C_func_file.c"
:
# C is include here so that it doesn't need to be compiled externally
pass
cdef
extern
from
"C_func_file.h"
:
void
multiply_by_10_in_C
(
double
*
,
unsigned
int
)
import
numpy
as
np
def
multiply_by_10
(
arr
):
# 'arr' is a one-dimensional numpy array
if
not
arr
.
flags
[
'C_CONTIGUOUS'
]:
arr
=
np
.
ascontiguousarray
(
arr
)
# Makes a contiguous copy of the numpy array.
cdef
double
[::
1
]
arr_memview
=
arr
multiply_by_10_in_C
(
&
arr_memview
[
0
],
arr_memview
.
shape
[
0
])
return
arr
a
=
np
.
ones
(
5
,
dtype
=
np
.
double
)
print
(
multiply_by_10
(
a
))
b
=
np
.
ones
(
10
,
dtype
=
np
.
double
)
b
=
b
[::
2
]
# b is not contiguous.
print
(
multiply_by_10
(
b
))
# but our function still works as expected.
cdef
extern
from
"C_func_file.c"
:
# C is include here so that it doesn't need to be compiled externally
pass
cdef
extern
from
"C_func_file.h"
:
void
multiply_by_10_in_C
(
double
*
,
unsigned
int
)
import
numpy
as
np
def
multiply_by_10
(
arr
):
# 'arr' is a one-dimensional numpy array
if
not
arr
.
flags
[
'C_CONTIGUOUS'
]:
arr
=
np
.
ascontiguousarray
(
arr
)
# Makes a contiguous copy of the numpy array.
cdef
double
[::
1
]
arr_memview
=
arr
multiply_by_10_in_C
(
&
arr_memview
[
0
],
arr_memview
.
shape
[
0
])
return
arr
a
=
np
.
ones
(
5
,
dtype
=
np
.
double
)
print
(
multiply_by_10
(
a
))
b
=
np
.
ones
(
10
,
dtype
=
np
.
double
)
b
=
b
[::
2
]
# b is not contiguous.
print
(
multiply_by_10
(
b
))
# but our function still works as expected.
docs/examples/userguide/memoryviews/not_none.pyx
View file @
b67e5567
import
numpy
as
np
def
process_buffer
(
int
[:,:]
input_view
not
None
,
int
[:,:]
output_view
=
None
):
if
output_view
is
None
:
# Creating a default view, e.g.
output_view
=
np
.
empty_like
(
input_view
)
# process 'input_view' into 'output_view'
return
output_view
import
numpy
as
np
def
process_buffer
(
int
[:,:]
input_view
not
None
,
int
[:,:]
output_view
=
None
):
if
output_view
is
None
:
# Creating a default view, e.g.
output_view
=
np
.
empty_like
(
input_view
)
# process 'input_view' into 'output_view'
return
output_view
docs/examples/userguide/memoryviews/np_flag_const.pyx
View file @
b67e5567
import
numpy
as
np
cdef
const
double
[:]
myslice
# const item type => read-only view
a
=
np
.
linspace
(
0
,
10
,
num
=
50
)
a
.
setflags
(
write
=
False
)
myslice
=
a
import
numpy
as
np
cdef
const
double
[:]
myslice
# const item type => read-only view
a
=
np
.
linspace
(
0
,
10
,
num
=
50
)
a
.
setflags
(
write
=
False
)
myslice
=
a
docs/examples/userguide/memoryviews/slicing.pyx
View file @
b67e5567
import
numpy
as
np
exporting_object
=
np
.
arange
(
0
,
15
*
10
*
20
,
dtype
=
np
.
intc
).
reshape
((
15
,
10
,
20
))
cdef
int
[:,
:,
:]
my_view
=
exporting_object
# These are all equivalent
my_view
[
10
]
my_view
[
10
,
:,
:]
my_view
[
10
,
...]
import
numpy
as
np
exporting_object
=
np
.
arange
(
0
,
15
*
10
*
20
,
dtype
=
np
.
intc
).
reshape
((
15
,
10
,
20
))
cdef
int
[:,
:,
:]
my_view
=
exporting_object
# These are all equivalent
my_view
[
10
]
my_view
[
10
,
:,
:]
my_view
[
10
,
...]
docs/examples/userguide/memoryviews/transpose.pyx
View file @
b67e5567
import
numpy
as
np
array
=
np
.
arange
(
20
,
dtype
=
np
.
intc
).
reshape
((
2
,
10
))
cdef
int
[:,
::
1
]
c_contig
=
array
cdef
int
[::
1
,
:]
f_contig
=
c_contig
.
T
import
numpy
as
np
array
=
np
.
arange
(
20
,
dtype
=
np
.
intc
).
reshape
((
2
,
10
))
cdef
int
[:,
::
1
]
c_contig
=
array
cdef
int
[::
1
,
:]
f_contig
=
c_contig
.
T
docs/examples/userguide/memoryviews/view_string.pyx
View file @
b67e5567
cdef
bint
is_y_in
(
const
unsigned
char
[:]
string_view
):
cdef
int
i
for
i
in
range
(
string_view
.
shape
[
0
]):
if
string_view
[
i
]
==
b'y'
:
return
True
return
False
print
(
is_y_in
(
b'hello world'
))
# False
print
(
is_y_in
(
b'hello Cython'
))
# True
cdef
bint
is_y_in
(
const
unsigned
char
[:]
string_view
):
cdef
int
i
for
i
in
range
(
string_view
.
shape
[
0
]):
if
string_view
[
i
]
==
b'y'
:
return
True
return
False
print
(
is_y_in
(
b'hello world'
))
# False
print
(
is_y_in
(
b'hello Cython'
))
# True
docs/examples/userguide/numpy_tutorial/compute_fused_types.pyx
View file @
b67e5567
# cython: infer_types=True
import
numpy
as
np
cimport
cython
ctypedef
fused
my_type
:
int
double
long
long
cdef
my_type
clip
(
my_type
a
,
my_type
min_value
,
my_type
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
@
cython
.
boundscheck
(
False
)
@
cython
.
wraparound
(
False
)
def
compute
(
my_type
[:,
::
1
]
array_1
,
my_type
[:,
::
1
]
array_2
,
my_type
a
,
my_type
b
,
my_type
c
):
x_max
=
array_1
.
shape
[
0
]
y_max
=
array_1
.
shape
[
1
]
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
if
my_type
is
int
:
dtype
=
np
.
intc
elif
my_type
is
double
:
dtype
=
np
.
double
elif
my_type
is
cython
.
longlong
:
dtype
=
np
.
longlong
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
dtype
)
cdef
my_type
[:,
::
1
]
result_view
=
result
cdef
my_type
tmp
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
# cython: infer_types=True
import
numpy
as
np
cimport
cython
ctypedef
fused
my_type
:
int
double
long
long
cdef
my_type
clip
(
my_type
a
,
my_type
min_value
,
my_type
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
@
cython
.
boundscheck
(
False
)
@
cython
.
wraparound
(
False
)
def
compute
(
my_type
[:,
::
1
]
array_1
,
my_type
[:,
::
1
]
array_2
,
my_type
a
,
my_type
b
,
my_type
c
):
x_max
=
array_1
.
shape
[
0
]
y_max
=
array_1
.
shape
[
1
]
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
if
my_type
is
int
:
dtype
=
np
.
intc
elif
my_type
is
double
:
dtype
=
np
.
double
elif
my_type
is
cython
.
longlong
:
dtype
=
np
.
longlong
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
dtype
)
cdef
my_type
[:,
::
1
]
result_view
=
result
cdef
my_type
tmp
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
docs/examples/userguide/numpy_tutorial/compute_infer_types.pyx
View file @
b67e5567
# cython: infer_types=True
import
numpy
as
np
cimport
cython
DTYPE
=
np
.
intc
cdef
int
clip
(
int
a
,
int
min_value
,
int
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
@
cython
.
boundscheck
(
False
)
@
cython
.
wraparound
(
False
)
def
compute
(
int
[:,
::
1
]
array_1
,
int
[:,
::
1
]
array_2
,
int
a
,
int
b
,
int
c
):
x_max
=
array_1
.
shape
[
0
]
y_max
=
array_1
.
shape
[
1
]
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
DTYPE
)
cdef
int
[:,
::
1
]
result_view
=
result
cdef
int
tmp
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
# cython: infer_types=True
import
numpy
as
np
cimport
cython
DTYPE
=
np
.
intc
cdef
int
clip
(
int
a
,
int
min_value
,
int
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
@
cython
.
boundscheck
(
False
)
@
cython
.
wraparound
(
False
)
def
compute
(
int
[:,
::
1
]
array_1
,
int
[:,
::
1
]
array_2
,
int
a
,
int
b
,
int
c
):
x_max
=
array_1
.
shape
[
0
]
y_max
=
array_1
.
shape
[
1
]
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
DTYPE
)
cdef
int
[:,
::
1
]
result_view
=
result
cdef
int
tmp
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
docs/examples/userguide/numpy_tutorial/compute_memview.pyx
View file @
b67e5567
import
numpy
as
np
DTYPE
=
np
.
intc
cdef
int
clip
(
int
a
,
int
min_value
,
int
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
def
compute
(
int
[:,
:]
array_1
,
int
[:,
:]
array_2
,
int
a
,
int
b
,
int
c
):
cdef
Py_ssize_t
x_max
=
array_1
.
shape
[
0
]
cdef
Py_ssize_t
y_max
=
array_1
.
shape
[
1
]
# array_1.shape is now a C array, no it's not possible
# to compare it simply by using == without a for-loop.
# To be able to compare it to array_2.shape easily,
# we convert them both to Python tuples.
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
DTYPE
)
cdef
int
[:,
:]
result_view
=
result
cdef
int
tmp
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
import
numpy
as
np
DTYPE
=
np
.
intc
cdef
int
clip
(
int
a
,
int
min_value
,
int
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
def
compute
(
int
[:,
:]
array_1
,
int
[:,
:]
array_2
,
int
a
,
int
b
,
int
c
):
cdef
Py_ssize_t
x_max
=
array_1
.
shape
[
0
]
cdef
Py_ssize_t
y_max
=
array_1
.
shape
[
1
]
# array_1.shape is now a C array, no it's not possible
# to compare it simply by using == without a for-loop.
# To be able to compare it to array_2.shape easily,
# we convert them both to Python tuples.
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
DTYPE
)
cdef
int
[:,
:]
result_view
=
result
cdef
int
tmp
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
docs/examples/userguide/numpy_tutorial/compute_prange.pyx
View file @
b67e5567
# tag: openmp
# You can ignore the previous line.
# It's for internal testing of the cython documentation.
# distutils: extra_compile_args=-fopenmp
# distutils: extra_link_args=-fopenmp
import
numpy
as
np
cimport
cython
from
cython.parallel
import
prange
ctypedef
fused
my_type
:
int
double
long
long
# We declare our plain c function nogil
cdef
my_type
clip
(
my_type
a
,
my_type
min_value
,
my_type
max_value
)
nogil
:
return
min
(
max
(
a
,
min_value
),
max_value
)
@
cython
.
boundscheck
(
False
)
@
cython
.
wraparound
(
False
)
def
compute
(
my_type
[:,
::
1
]
array_1
,
my_type
[:,
::
1
]
array_2
,
my_type
a
,
my_type
b
,
my_type
c
):
cdef
Py_ssize_t
x_max
=
array_1
.
shape
[
0
]
cdef
Py_ssize_t
y_max
=
array_1
.
shape
[
1
]
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
if
my_type
is
int
:
dtype
=
np
.
intc
elif
my_type
is
double
:
dtype
=
np
.
double
elif
my_type
is
cython
.
longlong
:
dtype
=
np
.
longlong
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
dtype
)
cdef
my_type
[:,
::
1
]
result_view
=
result
cdef
my_type
tmp
cdef
Py_ssize_t
x
,
y
# We use prange here.
for
x
in
prange
(
x_max
,
nogil
=
True
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
# tag: openmp
# You can ignore the previous line.
# It's for internal testing of the cython documentation.
# distutils: extra_compile_args=-fopenmp
# distutils: extra_link_args=-fopenmp
import
numpy
as
np
cimport
cython
from
cython.parallel
import
prange
ctypedef
fused
my_type
:
int
double
long
long
# We declare our plain c function nogil
cdef
my_type
clip
(
my_type
a
,
my_type
min_value
,
my_type
max_value
)
nogil
:
return
min
(
max
(
a
,
min_value
),
max_value
)
@
cython
.
boundscheck
(
False
)
@
cython
.
wraparound
(
False
)
def
compute
(
my_type
[:,
::
1
]
array_1
,
my_type
[:,
::
1
]
array_2
,
my_type
a
,
my_type
b
,
my_type
c
):
cdef
Py_ssize_t
x_max
=
array_1
.
shape
[
0
]
cdef
Py_ssize_t
y_max
=
array_1
.
shape
[
1
]
assert
tuple
(
array_1
.
shape
)
==
tuple
(
array_2
.
shape
)
if
my_type
is
int
:
dtype
=
np
.
intc
elif
my_type
is
double
:
dtype
=
np
.
double
elif
my_type
is
cython
.
longlong
:
dtype
=
np
.
longlong
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
dtype
)
cdef
my_type
[:,
::
1
]
result_view
=
result
cdef
my_type
tmp
cdef
Py_ssize_t
x
,
y
# We use prange here.
for
x
in
prange
(
x_max
,
nogil
=
True
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result_view
[
x
,
y
]
=
tmp
+
c
return
result
docs/examples/userguide/numpy_tutorial/compute_py.py
View file @
b67e5567
import
numpy
as
np
def
clip
(
a
,
min_value
,
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
def
compute
(
array_1
,
array_2
,
a
,
b
,
c
):
"""
This function must implement the formula
np.clip(array_1, 2, 10) * a + array_2 * b + c
array_1 and array_2 are 2D.
"""
x_max
=
array_1
.
shape
[
0
]
y_max
=
array_1
.
shape
[
1
]
assert
array_1
.
shape
==
array_2
.
shape
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
array_1
.
dtype
)
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result
[
x
,
y
]
=
tmp
+
c
return
result
import
numpy
as
np
def
clip
(
a
,
min_value
,
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
def
compute
(
array_1
,
array_2
,
a
,
b
,
c
):
"""
This function must implement the formula
np.clip(array_1, 2, 10) * a + array_2 * b + c
array_1 and array_2 are 2D.
"""
x_max
=
array_1
.
shape
[
0
]
y_max
=
array_1
.
shape
[
1
]
assert
array_1
.
shape
==
array_2
.
shape
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
array_1
.
dtype
)
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result
[
x
,
y
]
=
tmp
+
c
return
result
docs/examples/userguide/numpy_tutorial/compute_typed.pyx
View file @
b67e5567
import
numpy
as
np
# We now need to fix a datatype for our arrays. I've used the variable
# DTYPE for this, which is assigned to the usual NumPy runtime
# type info object.
DTYPE
=
np
.
intc
# cdef means here that this function is a plain C function (so faster).
# To get all the benefits, we type the arguments and the return value.
cdef
int
clip
(
int
a
,
int
min_value
,
int
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
def
compute
(
array_1
,
array_2
,
int
a
,
int
b
,
int
c
):
# The "cdef" keyword is also used within functions to type variables. It
# can only be used at the top indentation level (there are non-trivial
# problems with allowing them in other places, though we'd love to see
# good and thought out proposals for it).
cdef
Py_ssize_t
x_max
=
array_1
.
shape
[
0
]
cdef
Py_ssize_t
y_max
=
array_1
.
shape
[
1
]
assert
array_1
.
shape
==
array_2
.
shape
assert
array_1
.
dtype
==
DTYPE
assert
array_2
.
dtype
==
DTYPE
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
DTYPE
)
# It is very important to type ALL your variables. You do not get any
# warnings if not, only much slower code (they are implicitly typed as
# Python objects).
# For the "tmp" variable, we want to use the same data type as is
# stored in the array, so we use int because it correspond to np.intc.
# NB! An important side-effect of this is that if "tmp" overflows its
# datatype size, it will simply wrap around like in C, rather than raise
# an error like in Python.
cdef
int
tmp
# Py_ssize_t is the proper C type for Python array indices.
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result
[
x
,
y
]
=
tmp
+
c
return
result
import
numpy
as
np
# We now need to fix a datatype for our arrays. I've used the variable
# DTYPE for this, which is assigned to the usual NumPy runtime
# type info object.
DTYPE
=
np
.
intc
# cdef means here that this function is a plain C function (so faster).
# To get all the benefits, we type the arguments and the return value.
cdef
int
clip
(
int
a
,
int
min_value
,
int
max_value
):
return
min
(
max
(
a
,
min_value
),
max_value
)
def
compute
(
array_1
,
array_2
,
int
a
,
int
b
,
int
c
):
# The "cdef" keyword is also used within functions to type variables. It
# can only be used at the top indentation level (there are non-trivial
# problems with allowing them in other places, though we'd love to see
# good and thought out proposals for it).
cdef
Py_ssize_t
x_max
=
array_1
.
shape
[
0
]
cdef
Py_ssize_t
y_max
=
array_1
.
shape
[
1
]
assert
array_1
.
shape
==
array_2
.
shape
assert
array_1
.
dtype
==
DTYPE
assert
array_2
.
dtype
==
DTYPE
result
=
np
.
zeros
((
x_max
,
y_max
),
dtype
=
DTYPE
)
# It is very important to type ALL your variables. You do not get any
# warnings if not, only much slower code (they are implicitly typed as
# Python objects).
# For the "tmp" variable, we want to use the same data type as is
# stored in the array, so we use int because it correspond to np.intc.
# NB! An important side-effect of this is that if "tmp" overflows its
# datatype size, it will simply wrap around like in C, rather than raise
# an error like in Python.
cdef
int
tmp
# Py_ssize_t is the proper C type for Python array indices.
cdef
Py_ssize_t
x
,
y
for
x
in
range
(
x_max
):
for
y
in
range
(
y_max
):
tmp
=
clip
(
array_1
[
x
,
y
],
2
,
10
)
tmp
=
tmp
*
a
+
array_2
[
x
,
y
]
*
b
result
[
x
,
y
]
=
tmp
+
c
return
result
docs/examples/userguide/parallelism/breaking_loop.pyx
View file @
b67e5567
from
cython.parallel
import
prange
cdef
int
func
(
Py_ssize_t
n
):
cdef
Py_ssize_t
i
for
i
in
prange
(
n
,
nogil
=
True
):
if
i
==
8
:
with
gil
:
raise
Exception
()
elif
i
==
4
:
break
elif
i
==
2
:
return
i
from
cython.parallel
import
prange
cdef
int
func
(
Py_ssize_t
n
):
cdef
Py_ssize_t
i
for
i
in
prange
(
n
,
nogil
=
True
):
if
i
==
8
:
with
gil
:
raise
Exception
()
elif
i
==
4
:
break
elif
i
==
2
:
return
i
docs/examples/userguide/parallelism/cimport_openmp.pyx
View file @
b67e5567
# tag: openmp
# You can ignore the previous line.
# It's for internal testing of the Cython documentation.
from
cython.parallel
cimport
parallel
cimport
openmp
cdef
int
num_threads
openmp
.
omp_set_dynamic
(
1
)
with
nogil
,
parallel
():
num_threads
=
openmp
.
omp_get_num_threads
()
# ...
# tag: openmp
# You can ignore the previous line.
# It's for internal testing of the Cython documentation.
from
cython.parallel
cimport
parallel
cimport
openmp
cdef
int
num_threads
openmp
.
omp_set_dynamic
(
1
)
with
nogil
,
parallel
():
num_threads
=
openmp
.
omp_get_num_threads
()
# ...
docs/examples/userguide/parallelism/setup.py
View file @
b67e5567
from
distutils.core
import
setup
from
distutils.extension
import
Extension
from
Cython.Build
import
cythonize
ext_modules
=
[
Extension
(
"hello"
,
[
"hello.pyx"
],
extra_compile_args
=
[
'-fopenmp'
],
extra_link_args
=
[
'-fopenmp'
],
)
]
setup
(
name
=
'hello-parallel-world'
,
ext_modules
=
cythonize
(
ext_modules
),
)
from
distutils.core
import
setup
from
distutils.extension
import
Extension
from
Cython.Build
import
cythonize
ext_modules
=
[
Extension
(
"hello"
,
[
"hello.pyx"
],
extra_compile_args
=
[
'-fopenmp'
],
extra_link_args
=
[
'-fopenmp'
],
)
]
setup
(
name
=
'hello-parallel-world'
,
ext_modules
=
cythonize
(
ext_modules
),
)
docs/examples/userguide/parallelism/simple_sum.pyx
View file @
b67e5567
from
cython.parallel
import
prange
cdef
int
i
cdef
int
n
=
30
cdef
int
sum
=
0
for
i
in
prange
(
n
,
nogil
=
True
):
sum
+=
i
print
(
sum
)
from
cython.parallel
import
prange
cdef
int
i
cdef
int
n
=
30
cdef
int
sum
=
0
for
i
in
prange
(
n
,
nogil
=
True
):
sum
+=
i
print
(
sum
)
docs/examples/userguide/sharing_declarations/landscaping.pyx
View file @
b67e5567
cimport
shrubbing
import
shrubbing
def
main
():
cdef
shrubbing
.
Shrubbery
sh
sh
=
shrubbing
.
standard_shrubbery
()
print
(
"Shrubbery size is"
,
sh
.
width
,
'x'
,
sh
.
length
)
cimport
shrubbing
import
shrubbing
def
main
():
cdef
shrubbing
.
Shrubbery
sh
sh
=
shrubbing
.
standard_shrubbery
()
print
(
"Shrubbery size is"
,
sh
.
width
,
'x'
,
sh
.
length
)
docs/examples/userguide/sharing_declarations/lunch.pyx
View file @
b67e5567
cimport
c_lunch
def
eject_tomato
(
float
speed
):
c_lunch
.
eject_tomato
(
speed
)
cimport
c_lunch
def
eject_tomato
(
float
speed
):
c_lunch
.
eject_tomato
(
speed
)
docs/examples/userguide/sharing_declarations/restaurant.pyx
View file @
b67e5567
from
__future__
import
print_function
cimport
dishes
from
dishes
cimport
spamdish
cdef
void
prepare
(
spamdish
*
d
):
d
.
oz_of_spam
=
42
d
.
filler
=
dishes
.
sausage
def
serve
():
cdef
spamdish
d
prepare
(
&
d
)
print
(
f'
{
d
.
oz_of_spam
}
oz spam, filler no.
{
d
.
filler
}
'
)
from
__future__
import
print_function
cimport
dishes
from
dishes
cimport
spamdish
cdef
void
prepare
(
spamdish
*
d
):
d
.
oz_of_spam
=
42
d
.
filler
=
dishes
.
sausage
def
serve
():
cdef
spamdish
d
prepare
(
&
d
)
print
(
f'
{
d
.
oz_of_spam
}
oz spam, filler no.
{
d
.
filler
}
'
)
docs/examples/userguide/sharing_declarations/setup.py
View file @
b67e5567
from
distutils.core
import
setup
from
Cython.Build
import
cythonize
setup
(
ext_modules
=
cythonize
([
"landscaping.pyx"
,
"shrubbing.pyx"
]))
from
distutils.core
import
setup
from
Cython.Build
import
cythonize
setup
(
ext_modules
=
cythonize
([
"landscaping.pyx"
,
"shrubbing.pyx"
]))
docs/examples/userguide/sharing_declarations/shrubbing.pyx
View file @
b67e5567
cdef
class
Shrubbery
:
def
__cinit__
(
self
,
int
w
,
int
l
):
self
.
width
=
w
self
.
length
=
l
def
standard_shrubbery
():
return
Shrubbery
(
3
,
7
)
cdef
class
Shrubbery
:
def
__cinit__
(
self
,
int
w
,
int
l
):
self
.
width
=
w
self
.
length
=
l
def
standard_shrubbery
():
return
Shrubbery
(
3
,
7
)
docs/examples/userguide/sharing_declarations/spammery.pyx
View file @
b67e5567
from
__future__
import
print_function
from
volume
cimport
cube
def
menu
(
description
,
size
):
print
(
description
,
":"
,
cube
(
size
),
"cubic metres of spam"
)
menu
(
"Entree"
,
1
)
menu
(
"Main course"
,
3
)
menu
(
"Dessert"
,
2
)
from
__future__
import
print_function
from
volume
cimport
cube
def
menu
(
description
,
size
):
print
(
description
,
":"
,
cube
(
size
),
"cubic metres of spam"
)
menu
(
"Entree"
,
1
)
menu
(
"Main course"
,
3
)
menu
(
"Dessert"
,
2
)
docs/examples/userguide/sharing_declarations/volume.pyx
View file @
b67e5567
cdef
float
cube
(
float
x
):
return
x
*
x
*
x
cdef
float
cube
(
float
x
):
return
x
*
x
*
x
docs/examples/userguide/wrapping_CPlusPlus/cython_usage.pyx
View file @
b67e5567
# distutils: language = c++
from
Rectangle
cimport
Rectangle
def
main
():
rec_ptr
=
new
Rectangle
(
1
,
2
,
3
,
4
)
# Instantiate a Rectangle object on the heap
try
:
rec_area
=
rec_ptr
.
getArea
()
finally
:
del
rec_ptr
# delete heap allocated object
cdef
Rectangle
rec_stack
# Instantiate a Rectangle object on the stack
# distutils: language = c++
from
Rectangle
cimport
Rectangle
def
main
():
rec_ptr
=
new
Rectangle
(
1
,
2
,
3
,
4
)
# Instantiate a Rectangle object on the heap
try
:
rec_area
=
rec_ptr
.
getArea
()
finally
:
del
rec_ptr
# delete heap allocated object
cdef
Rectangle
rec_stack
# Instantiate a Rectangle object on the stack
docs/examples/userguide/wrapping_CPlusPlus/function_templates.pyx
View file @
b67e5567
# distutils: language = c++
cdef
extern
from
"<algorithm>"
namespace
"std"
:
T
max
[
T
](
T
a
,
T
b
)
print
(
max
[
long
](
3
,
4
))
print
(
max
(
1.5
,
2.5
))
# simple template argument deduction
# distutils: language = c++
cdef
extern
from
"<algorithm>"
namespace
"std"
:
T
max
[
T
](
T
a
,
T
b
)
print
(
max
[
long
](
3
,
4
))
print
(
max
(
1.5
,
2.5
))
# simple template argument deduction
docs/examples/userguide/wrapping_CPlusPlus/iterate.pyx
View file @
b67e5567
# distutils: language = c++
from
libcpp.vector
cimport
vector
def
main
():
cdef
vector
[
int
]
v
=
[
4
,
6
,
5
,
10
,
3
]
cdef
int
value
for
value
in
v
:
print
(
value
)
return
[
x
*
x
for
x
in
v
if
x
%
2
==
0
]
# distutils: language = c++
from
libcpp.vector
cimport
vector
def
main
():
cdef
vector
[
int
]
v
=
[
4
,
6
,
5
,
10
,
3
]
cdef
int
value
for
value
in
v
:
print
(
value
)
return
[
x
*
x
for
x
in
v
if
x
%
2
==
0
]
docs/examples/userguide/wrapping_CPlusPlus/nested_class.pyx
View file @
b67e5567
# distutils: language = c++
cdef
extern
from
"<vector>"
namespace
"std"
:
cdef
cppclass
vector
[
T
]:
cppclass
iterator
:
T
operator
*
()
iterator
operator
++
()
bint
operator
==
(
iterator
)
bint
operator
!=
(
iterator
)
vector
()
void
push_back
(
T
&
)
T
&
operator
[](
int
)
T
&
at
(
int
)
iterator
begin
()
iterator
end
()
cdef
vector
[
int
].
iterator
iter
#iter is declared as being of type vector<int>::iterator
# distutils: language = c++
cdef
extern
from
"<vector>"
namespace
"std"
:
cdef
cppclass
vector
[
T
]:
cppclass
iterator
:
T
operator
*
()
iterator
operator
++
()
bint
operator
==
(
iterator
)
bint
operator
!=
(
iterator
)
vector
()
void
push_back
(
T
&
)
T
&
operator
[](
int
)
T
&
at
(
int
)
iterator
begin
()
iterator
end
()
cdef
vector
[
int
].
iterator
iter
#iter is declared as being of type vector<int>::iterator
docs/examples/userguide/wrapping_CPlusPlus/python_to_cpp.pyx
View file @
b67e5567
# distutils: language = c++
from
libcpp.string
cimport
string
from
libcpp.vector
cimport
vector
py_bytes_object
=
b'The knights who say ni'
py_unicode_object
=
u'Those who hear them seldom live to tell the tale.'
cdef
string
s
=
py_bytes_object
print
(
s
)
# b'The knights who say ni'
cdef
string
cpp_string
=
<
string
>
py_unicode_object
.
encode
(
'utf-8'
)
print
(
cpp_string
)
# b'Those who hear them seldom live to tell the tale.'
cdef
vector
[
int
]
vect
=
range
(
1
,
10
,
2
)
print
(
vect
)
# [1, 3, 5, 7, 9]
cdef
vector
[
string
]
cpp_strings
=
b'It is a good shrubbery'
.
split
()
print
(
cpp_strings
[
1
])
# b'is'
# distutils: language = c++
from
libcpp.string
cimport
string
from
libcpp.vector
cimport
vector
py_bytes_object
=
b'The knights who say ni'
py_unicode_object
=
u'Those who hear them seldom live to tell the tale.'
cdef
string
s
=
py_bytes_object
print
(
s
)
# b'The knights who say ni'
cdef
string
cpp_string
=
<
string
>
py_unicode_object
.
encode
(
'utf-8'
)
print
(
cpp_string
)
# b'Those who hear them seldom live to tell the tale.'
cdef
vector
[
int
]
vect
=
range
(
1
,
10
,
2
)
print
(
vect
)
# [1, 3, 5, 7, 9]
cdef
vector
[
string
]
cpp_strings
=
b'It is a good shrubbery'
.
split
()
print
(
cpp_strings
[
1
])
# b'is'
docs/examples/userguide/wrapping_CPlusPlus/rect_ptr.pyx
View file @
b67e5567
# distutils: language = c++
from
Rectangle
cimport
Rectangle
cdef
class
PyRectangle
:
cdef
Rectangle
*
c_rect
# hold a pointer to the C++ instance which we're wrapping
def
__cinit__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
c_rect
=
new
Rectangle
(
x0
,
y0
,
x1
,
y1
)
def
__dealloc__
(
self
):
del
self
.
c_rect
# distutils: language = c++
from
Rectangle
cimport
Rectangle
cdef
class
PyRectangle
:
cdef
Rectangle
*
c_rect
# hold a pointer to the C++ instance which we're wrapping
def
__cinit__
(
self
,
int
x0
,
int
y0
,
int
x1
,
int
y1
):
self
.
c_rect
=
new
Rectangle
(
x0
,
y0
,
x1
,
y1
)
def
__dealloc__
(
self
):
del
self
.
c_rect
docs/examples/userguide/wrapping_CPlusPlus/templates.pyx
View file @
b67e5567
# distutils: language = c++
# import dereference and increment operators
from
cython.operator
cimport
dereference
as
deref
,
preincrement
as
inc
cdef
extern
from
"<vector>"
namespace
"std"
:
cdef
cppclass
vector
[
T
]:
cppclass
iterator
:
T
operator
*
()
iterator
operator
++
()
bint
operator
==
(
iterator
)
bint
operator
!=
(
iterator
)
vector
()
void
push_back
(
T
&
)
T
&
operator
[](
int
)
T
&
at
(
int
)
iterator
begin
()
iterator
end
()
cdef
vector
[
int
]
*
v
=
new
vector
[
int
]()
cdef
int
i
for
i
in
range
(
10
):
v
.
push_back
(
i
)
cdef
vector
[
int
].
iterator
it
=
v
.
begin
()
while
it
!=
v
.
end
():
print
(
deref
(
it
))
inc
(
it
)
del
v
# distutils: language = c++
# import dereference and increment operators
from
cython.operator
cimport
dereference
as
deref
,
preincrement
as
inc
cdef
extern
from
"<vector>"
namespace
"std"
:
cdef
cppclass
vector
[
T
]:
cppclass
iterator
:
T
operator
*
()
iterator
operator
++
()
bint
operator
==
(
iterator
)
bint
operator
!=
(
iterator
)
vector
()
void
push_back
(
T
&
)
T
&
operator
[](
int
)
T
&
at
(
int
)
iterator
begin
()
iterator
end
()
cdef
vector
[
int
]
*
v
=
new
vector
[
int
]()
cdef
int
i
for
i
in
range
(
10
):
v
.
push_back
(
i
)
cdef
vector
[
int
].
iterator
it
=
v
.
begin
()
while
it
!=
v
.
end
():
print
(
deref
(
it
))
inc
(
it
)
del
v
docs/examples/userguide/wrapping_CPlusPlus/vector_demo.pyx
View file @
b67e5567
# distutils: language = c++
from
libcpp.vector
cimport
vector
cdef
vector
[
int
]
vect
cdef
int
i
,
x
for
i
in
range
(
10
):
vect
.
push_back
(
i
)
for
i
in
range
(
10
):
print
(
vect
[
i
])
for
x
in
vect
:
print
(
x
)
# distutils: language = c++
from
libcpp.vector
cimport
vector
cdef
vector
[
int
]
vect
cdef
int
i
,
x
for
i
in
range
(
10
):
vect
.
push_back
(
i
)
for
i
in
range
(
10
):
print
(
vect
[
i
])
for
x
in
vect
:
print
(
x
)
docs/examples/userguide/wrapping_CPlusPlus/wrapper_vector.pyx
View file @
b67e5567
# distutils: language = c++
from
libcpp.vector
cimport
vector
cdef
class
VectorStack
:
cdef
vector
[
int
]
v
def
push
(
self
,
x
):
self
.
v
.
push_back
(
x
)
def
pop
(
self
):
if
self
.
v
.
empty
():
raise
IndexError
()
x
=
self
.
v
.
back
()
self
.
v
.
pop_back
()
return
x
# distutils: language = c++
from
libcpp.vector
cimport
vector
cdef
class
VectorStack
:
cdef
vector
[
int
]
v
def
push
(
self
,
x
):
self
.
v
.
push_back
(
x
)
def
pop
(
self
):
if
self
.
v
.
empty
():
raise
IndexError
()
x
=
self
.
v
.
back
()
self
.
v
.
pop_back
()
return
x
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment