[Cython] Prototype for parametrized types
Robert Bradshaw
robertwb at math.washington.edu
Mon Mar 10 23:52:35 CET 2008
On Mar 10, 2008, at 3:03 PM, Dag Sverre Seljebotn wrote:
> (I take the liberty to top-post when I'm on cellular...)
>
> I like Robert's proposal, but with a twist: It is NOT a
> declaration, but an automatically inferred variable and a cast.
Handling explicit casts is easy, and I like the syntax below, but I
am trying to come up with a way to do an actual type declaration
(which may or may not be part of an assignment). For example, think
of code that uses temporary mpz_t values (if you're not familiar with
gmp, see http://trac.sagemath.org/sage_trac/attachment/ticket/2155/
trac-2155.patch for a concrete example). Also, one of the things that
makes Cython so great is that it handles type conversions
automatically--having to do so manually every time would be a big
step back.
Ideally, I'd like some syntax that could be run as valid Python (no
syntax or name errors) but declare a specific variable to be a type,
which is more powerful than using assignment + type inference (for
example, one could add several python ints to a and it would do the
right thing).
> So if foo() returns a Python int (object), then you can not write
>
> a = cython.types.int
> a = foo()
>
> but have to write
>
> a = cython.types.int(foo())
>
> The former example is very confusing to Pythoners, while the second
> is very consistent: Some *classes*/types have compile-time
> optimizations when they are operated on (whether numpy.ndarray or
> cython.types.int), but variable semantic actually follow Python's.
> We compile actions on *types* to C, not actions on variables.
Yes. But to discover types, a variable <-> type mapping is used. (In
the distant future different variables could even be typed
differently in different parts of a function, but that would be more
complicated to write and more difficult to understand as a user).
> Declaring types on arguments are then simply a short-hand for
> "always run argument through the given factory/type constructor",
> and can be implemented for Python types as well, so
>
> def foo(a : unicode):
>
> would make sure int and str params are converted to unicode.
Yes.
> I believe this to be very in the spirit of rest of Python, and that
> it wouldn't be that much more verbose. The cost is lack of compiler
> warnings - but one share that with the rest of Python, and I
> believe we type for speed, not design?
Compiler warnings are very, very nice (and more valuable in Cython as
the edit-compile-run cycle takes much longer.
> Perhaps easy type asserts can then be used in addition if one wants
> to check that the code is compiled efficiently...
This is a good idea.
- Robert
More information about the Cython-dev
mailing list