On Dec 3, 2009, at 12:56 AM, Stefan Behnel wrote:
> Hi,
>
> I mentioned this idea before, but I think it's worth it's own thread.
>
> The main problem with the current type inference mechanism for
> existing
> code is that the semantics of assignments to untyped names change,
> i.e.
>
> cdef int i = 5
> x = i
>
> will type 'x' as C int with type interence enabled. This will break
> existing code, as I expect most Pyrex/Cython code to depend on the
> above
> idiom for creating a Python object from a C type.
>
> Robert, please correct me, but IIUC, the above problem was the main
> reason
> not to enable type inference by default (except for some remaining
> bugs,
> but those will go away over time).
Yep.
> However, type inference has many other virtues, e.g. for code like
> this:
>
> l = []
> for x in range(100):
> item = do_some_complex_calculation(x)
> l.append(item)
>
> If the type of 'l' was inferred to be a list in this code,
> "l.append" would
> get optimised into the obvious C-API call (potentially even without
> a None
> check), instead of generating additional fallback code for cases
> where l is
> not a list. The same applies to the various other optimisations for
> builtin
> types.
>
> Another use case is for extension types. Currently, when
> instantiating an
> extension type, the result variable needs to be typed if you want to
> access
> its C methods and fields later on. With type inference enabled, the
> following would work without additional typing:
>
> cdef class MyExt:
> cdef int i
>
> x = MyExt()
> print x.i
>
> And, for the case that 'i' was actually declared 'public' or
> 'readonly',
> the access would go though the C field instead of the Python
> descriptor.
>
> So my proposal is to enable type inference by default (after fixing
> the
> remaining bugs), but only for Python types (including extension
> types).
> That should break *very* little code, but would give a major
> improvement in
> terms of both usability and performance.
>
> The existing directive would then only switch between full inference
> when
> enabled (including C types) and no type inference at all (when
> disabled
> explicitly).
>
> Comments?
Sounds like it would be safe (and very useful) to me. The only thing
that can happen on assignment between object types is a type check,
and the type inference engine infers based on the set of assignments,
so I don't see how it could go wrong. (There are corner cases where
the behavior would change, but hopefully people aren't *counting* on
cdef class MyExt:
cdef int i
x = MyExt()
print x.i
raising an AttributeError...)
>
- Robert
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev