> Pyrex will do this if you declare the object as being of
> type 'dict' (and it will check the type on the boundary
> between Python and extension code, so it's still type-safe).
> Similarly for 'list' and a few other built-in types that
> have dedicated C APIs.
>

Sure, Cython will also (usually) do this if you *explicitly declare*
the type -- any places where it doesn't qualify as TODOs in my head,
anyway. In fact, now that we have some type inferencing going on,
Cython will even do this in some cases where you don't declare the
type, but we can deduce it.

In the example above, though, notice I said "a function that takes an
arbitrary Python object" -- I'm talking about the case where there
*is* no explicit type information, but you still want to avoid
typechecks and dispatching into generic code. I'm talking about a
snippet like this:

cdef void foo(object x):
    if isinstance(x, dict):
        x['spam'] = 5

Is Pyrex smart enough to infer that x is in fact a dict, and emit a
call to PyDict_GetItemString or the like? I don't think Cython is
right now, but I sure would like to make it smart enough to handle
that case. Similarly, if someone made a call to a library function
that always returned a dict, it'd be nice to tag the resulting object
as a dict for the same kind of things. I think there are at least
three key ingredients to handle things like the above: (1) type
inference, (2) control-flow analysis, and (3) potentially shadowing
variables (if x is used for several different Python types in a
block). These are all in the vein of "we don't do them yet, but we
want to."

That said, the real "black magic" I was referring to is beyond that
example: I'm talking about code that *doesn't* have explicit type
declarations, and *doesn't* do any type testing -- just blindly takes
an arbitrary PyObject * and calls off to a PyDict_* method, or
manually reaches into the underlying PyDictObject struct and does
something crazy. Of course, this isn't something you can do from
Python -- but it *is* something you could do from C. These are
generally horribly unsafe things to do, which is what I was saying
about segfaults above -- however, there are times that speed is more
important than any sort of safety, and that's a barrier you can't
cross in Pyrex/Cython without directly using the Python/C API
yourself, I think.

-cc
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to