Hi!

The topic of this post/request: Please share your knowledge about how
to keep code duplication as small as possible when writing Cython code
relying on several underlying implementations! 

In the Sage library, I have sometimes seen the following technique to
imitated templating with Cython:
1. Write a Cython file bla_template.pxi, which defines stuff using a
   placeholder (say, object_type).
2. For each value of object_type (say, int, str,...) write a Cython file
   bla_int.pyx, bla_str.pyx,... starting with "object_type=int" resp.
   "object_type=str", and then including bla_template.pxi
Hence, for the generic code in bla_template.pxi, several specialisations
will be created, and a class Foo in the template results in
sage....bla_int.Foo, sage....bla_str.Foo etc.

Recently, I have learnt another technique, namely Cython's "fused
types". This would work as follows:

ctypedef fused object_type:
    str
    int

cpdef object_type foo(object_type x, object_type y):
    if object_type is int:
        <do something special for int>
    else:
        <do something special for str>

cpdef object_type bar(object_type x):
    <have some generic code using the function foo>


Cython would create versions of foo and bar for each value of object_type,
explicitly accessible by foo[int] or bar[str], but is clever enough to
automatically choose the right implementation if the type of the
arguments is known, and also the "if object_type is int" statement in
foo will be resolved at compile time.

Problem: Cython does not allow to derive a cdef class from a fused type,
nor does it allow methods or attributes involving fused types. On the
ticket, I have given some proof-of-concept at #15820 on how to trick a
little bit to imitate "fused methods" with relatively little effort, but
this has some shortcomings, and perhaps you know better techniques ---
I'd be pleased to learn them!

Best regards,
Simon


-- 
You received this message because you are subscribed to the Google Groups 
"sage-devel" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-devel+unsubscr...@googlegroups.com.
To post to this group, send email to sage-devel@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-devel.
For more options, visit https://groups.google.com/d/optout.

Reply via email to