Duck Typing and **kwds

Kay Schluehr kay.schluehr at gmx.net
Thu Oct 11 08:11:08 CEST 2007


On 11 Okt., 06:05, Luis Zarrabeitia <ky... at uh.cu> wrote:

> Is that behavior expected? Is there any reason (performance, perhaps?) to break
> duck-typing in this situation?

I guess it wasn't considered to be relevant writing a coercion
function since there aren't too many dict like types that are not
dicts. You can examine what happens in the relevant code fragment in
ceval.c

    if (flags & CALL_FLAG_KW) {
        kwdict = EXT_POP(*pp_stack);
        if (!(kwdict && PyDict_Check(kwdict))) {
            PyErr_Format(PyExc_TypeError,
                     "%s%s argument after ** "
                     "must be a dictionary",
                     PyEval_GetFuncName(func),
                     PyEval_GetFuncDesc(func));
            goto ext_call_fail;
        }
    }
    if (flags & CALL_FLAG_VAR) {
        stararg = EXT_POP(*pp_stack);
        if (!PyTuple_Check(stararg)) {
            PyObject *t = NULL;
            t = PySequence_Tuple(stararg);
            if (t == NULL) {
                if (PyErr_ExceptionMatches(PyExc_TypeError)) {
                    PyErr_Format(PyExc_TypeError,
                             "%s%s argument after * "
                             "must be a sequence",
                             PyEval_GetFuncName(func),
                             PyEval_GetFuncDesc(func));
                }
                goto ext_call_fail;


I paralleled this with the subsequent clause for tuples where some
coercion function is applied ( PySequence_Tuple ).

It would be cleaner to implement a simple conversion function
PyDictlike_Dict

which seeks for a __dictionary__ method providing the following
interface

__dictionary__(self) -> dict

and is called when being available. Maybe you can suggest this at
python-dev? It might not require a PEP.




More information about the Python-list mailing list