Commit 28c23739 authored by Mark's avatar Mark

Merge pull request #94 from matthew-brett/fused-tutorial-edits

DOC - partial rewrite of fused types doc
parents 76a1f069 629a0bc9
...@@ -2,16 +2,52 @@ ...@@ -2,16 +2,52 @@
.. _fusedtypes: .. _fusedtypes:
************************** ***********************
Fused Types (Templates) Fused Types (Templates)
************************** ***********************
Fused types can be used to fuse multiple types into a single type, to allow a single Fused types allow you to have one type definition that can refer to multiple
algorithm to operate on values of multiple types. They are somewhat akin to templates types. This allows you to write a single static-typed cython algorithm that can
or generics. operate on values of multiple types. Thus fused types allow `generic
programming`_ and are akin to templates in C++ or generics in languages like
Java / C#.
.. _generic programming: http://en.wikipedia.org/wiki/Generic_programming
.. Note:: Support is experimental and new in this release, there may be bugs! .. Note:: Support is experimental and new in this release, there may be bugs!
Quickstart
==========
::
cimport cython
ctypedef fused char_or_float:
cython.char
cython.float
cpdef char_or_float plus_one(char_or_float var):
return var + 1
def show_me():
cdef:
cython.char a = 127
cython.float b = 127
print 'char', plus_one(a)
print 'float', plus_one(b)
This gives::
>>> show_me()
char -128
float 128.0
``plus_one(a)`` "specializes" the fused type ``char_or_float`` as a ``char``,
whereas ``plus_one(b)`` specializes ``char_or_float`` as a ``float``.
Declaring Fused Types Declaring Fused Types
===================== =====================
...@@ -20,39 +56,52 @@ Fused types may be declared as follows:: ...@@ -20,39 +56,52 @@ Fused types may be declared as follows::
cimport cython cimport cython
ctypedef fused my_fused_type: ctypedef fused my_fused_type:
cython.p_int cython.int
cython.p_float cython.double
This declares a new type called ``my_fused_type`` which is composed of a ``int *`` and a ``double *``. This declares a new type called ``my_fused_type`` which can be *either* an
Alternatively, the declaration may be written as:: ``int`` *or* a ``double``. Alternatively, the declaration may be written as::
my_fused_type = cython.fused_type(cython.p_int, cython.p_float) my_fused_type = cython.fused_type(cython.int, cython.float)
Only names may be used for the constituent types, but they may be any (non-fused) type, including a typedef. Only names may be used for the constituent types, but they may be any
i.e. one may write:: (non-fused) type, including a typedef. i.e. one may write::
ctypedef double *doublep ctypedef double my_double
my_fused_type = cython.fused_type(cython.p_int, doublep) my_fused_type = cython.fused_type(cython.int, my_double)
Using Fused Types Using Fused Types
================= =================
Fused types can be used to declare parameters of functions or methods:: Fused types can be used to declare parameters of functions or methods::
cdef cfunc(my_fused_type arg):
return arg + 1
If the you use the same fused type more than once in an argument list, then each
specialization of the fused type must be the same::
cdef cfunc(my_fused_type arg1, my_fused_type arg2): cdef cfunc(my_fused_type arg1, my_fused_type arg2):
return cython.typeof(arg1) == cython.typeof(arg2) return cython.typeof(arg1) == cython.typeof(arg2)
This declares a function with two parameters. The type of both parameters is either a pointer to an int, In this case, the type of both parameters is either an int, or a double
or a pointer to a float (according to the previous examples). So this function always True for every possible (according to the previous examples). However, because these arguments are the
invocation. You are allowed to mix fused types however:: same fused type of ``my_fused_type``, both ``arg1`` and ``arg2`` must be
specialized to the same type. Therefore this function returns True for every
possible valid invocation. You are allowed to mix fused types however::
def func(A x, B y): def func(A x, B y):
... ...
where ``A`` and ``B`` are different fused types. This will result in all combination of types. where ``A`` and ``B`` are different fused types. This will result in specialized
code paths for all combinations of types contained in ``A`` and ``B``.
Fused types and arrays
----------------------
Note that specializations of only numeric types may not be very useful, as one can usually rely on Note that specializations of only numeric types may not be very useful, as one
promotion of types. This is not true for arrays, pointers and typed views of memory however. can usually rely on promotion of types. This is not true for arrays, pointers
Indeed, one may write:: and typed views of memory however. Indeed, one may write::
def myfunc(A[:, :] x): def myfunc(A[:, :] x):
... ...
...@@ -62,14 +111,16 @@ Indeed, one may write:: ...@@ -62,14 +111,16 @@ Indeed, one may write::
cdef otherfunc(A *x): cdef otherfunc(A *x):
... ...
Selecting Specializations Selecting Specializations
========================= =========================
You can select a specialization (an instance of the function with specific or specialized (i.e.,
non-fused) argument types) in two ways: either by indexing or by calling. You can select a specialization (an instance of the function with specific or
specialized (i.e., non-fused) argument types) in two ways: either by indexing or
by calling.
Indexing Indexing
-------- --------
You can index functions with types to get certain specializations, i.e.:: You can index functions with types to get certain specializations, i.e.::
cfunc[cython.p_double](p1, p2) cfunc[cython.p_double](p1, p2)
...@@ -80,8 +131,8 @@ You can index functions with types to get certain specializations, i.e.:: ...@@ -80,8 +131,8 @@ You can index functions with types to get certain specializations, i.e.::
# From Python space # From Python space
func[cython.float, cython.double](myfloat, mydouble) func[cython.float, cython.double](myfloat, mydouble)
If a fused type is used as a base type, this will mean that the base type is the fused type, so the If a fused type is used as a base type, this will mean that the base type is the
base type is what needs to be specialized:: fused type, so the base type is what needs to be specialized::
cdef myfunc(A *x): cdef myfunc(A *x):
... ...
...@@ -91,24 +142,31 @@ base type is what needs to be specialized:: ...@@ -91,24 +142,31 @@ base type is what needs to be specialized::
Calling Calling
------- -------
A fused function can also be called with arguments, where the dispatch is figured out automatically::
A fused function can also be called with arguments, where the dispatch is
figured out automatically::
cfunc(p1, p2) cfunc(p1, p2)
func(myfloat, mydouble) func(myfloat, mydouble)
For a ``cdef`` or ``cpdef`` function called from Cython this means that the specialization is figured For a ``cdef`` or ``cpdef`` function called from Cython this means that the
out at compile time. For ``def`` functions the arguments are typechecked at runtime, and a best-effort specialization is figured out at compile time. For ``def`` functions the
approach is performed to figure out which specialization is needed. This means that this may result in arguments are typechecked at runtime, and a best-effort approach is performed to
a runtime ``TypeError`` if no specialization was found. A ``cpdef`` function is treated the same way as figure out which specialization is needed. This means that this may result in a
a ``def`` function if the type of the function is unknown (e.g. if it is external and there is no cimport runtime ``TypeError`` if no specialization was found. A ``cpdef`` function is
for it). treated the same way as a ``def`` function if the type of the function is
unknown (e.g. if it is external and there is no cimport for it).
The automatic dispatching rules are typically as follows, in order of
preference:
The automatic dispatching rules are typically as follows, in order of preference: * try to find an exact match
* try to find an exact match * choose the biggest corresponding numerical type (biggest float, biggest
* choose the biggest corresponding numerical type (biggest float, biggest complex, biggest int) complex, biggest int)
Built-in Fused Types Built-in Fused Types
==================== ====================
There are some built-in fused types available for convenience, these are:: There are some built-in fused types available for convenience, these are::
cython.integral # short, int, long cython.integral # short, int, long
...@@ -117,6 +175,7 @@ There are some built-in fused types available for convenience, these are:: ...@@ -117,6 +175,7 @@ There are some built-in fused types available for convenience, these are::
Casting Fused Functions Casting Fused Functions
======================= =======================
Fused ``cdef`` and ``cpdef`` functions may be cast or assigned to C function pointers as follows:: Fused ``cdef`` and ``cpdef`` functions may be cast or assigned to C function pointers as follows::
cdef myfunc(cython.floating, cython.integral): cdef myfunc(cython.floating, cython.integral):
...@@ -136,11 +195,13 @@ Fused ``cdef`` and ``cpdef`` functions may be cast or assigned to C function poi ...@@ -136,11 +195,13 @@ Fused ``cdef`` and ``cpdef`` functions may be cast or assigned to C function poi
Type Checking Specializations Type Checking Specializations
============================= =============================
Decisions can be made based on the specializations of the fused parameters. False conditions are pruned
to avoid invalid code. One may check with ``is``, ``is not`` and ``==`` and ``!=`` to see if a fused type Decisions can be made based on the specializations of the fused parameters.
is equal to a certain other non-fused type (to check the specialization), or use ``in`` and ``not in`` to False conditions are pruned to avoid invalid code. One may check with ``is``,
figure out whether a specialization is part of another set of types (specified as a fused type). In ``is not`` and ``==`` and ``!=`` to see if a fused type is equal to a certain
example:: other non-fused type (to check the specialization), or use ``in`` and ``not in``
to figure out whether a specialization is part of another set of types
(specified as a fused type). In example::
ctypedef fused bunch_of_types: ctypedef fused bunch_of_types:
... ...
...@@ -165,9 +226,11 @@ example:: ...@@ -165,9 +226,11 @@ example::
__signatures__ __signatures__
============== ==============
Finally, function objects from ``def`` or ``cpdef`` functions have an attribute __signatures__, which maps
the signature strings to the actual specialized functions. This may be useful for inspection. Finally, function objects from ``def`` or ``cpdef`` functions have an attribute
Listed signature strings may also be used as indices to the fused function:: __signatures__, which maps the signature strings to the actual specialized
functions. This may be useful for inspection. Listed signature strings may also
be used as indices to the fused function::
specialized_function = fused_function["MyExtensionClass, int, float"] specialized_function = fused_function["MyExtensionClass, int, float"]
...@@ -175,11 +238,12 @@ It would usually be preferred to index like this, however:: ...@@ -175,11 +238,12 @@ It would usually be preferred to index like this, however::
specialized_function = fused_function[MyExtensionClass, int, float] specialized_function = fused_function[MyExtensionClass, int, float]
Although the latter will select the biggest types for ``int`` and ``float`` from Python space, as they are Although the latter will select the biggest types for ``int`` and ``float`` from
not type identifiers but builtin types there. Passing ``cython.int`` and ``cython.float`` would resolve that, Python space, as they are not type identifiers but builtin types there. Passing
however. ``cython.int`` and ``cython.float`` would resolve that, however.
For memoryview indexing from python space you have to use strings instead of types:: For memoryview indexing from python space you have to use strings instead of
types::
ctypedef fused my_fused_type: ctypedef fused my_fused_type:
int[:, ::1] int[:, ::1]
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment