[Python-Dev] Special-casing "O"

Tim Peters tim.one@home.com
Sun, 27 May 2001 19:17:27 -0400


[Thomas Wouters]
> And don't forget the method-specific errormessage by passing ':len' in
> the format string. Of course, this can easily be (and probably should)
> done by passing another argument to whatever parses arguments in
> METH_O, rather than invoking string parsing magic every call.

Martin's patch automatically inserts the name of the function in the
TypeError it raises when a METH_O call doesn't get exactly one argument, or
gets a (one or more) keyword argument.

Stick to METH_O and it's a clear win, even in this respect:  there's no info
in an explicit ":len" he's not already deducing, and almost all instances of
"O:name" formats today are exactly the same this way:

if (!PyArg_ParseTuple(args, "O:abs", &v))
if (!PyArg_ParseTuple(args, "O:callable", &v))
if (!PyArg_ParseTuple(args, "O:id", &v))
if (!PyArg_ParseTuple(args, "O:hash", &v))
if (!PyArg_ParseTuple(args, "O:hex", &v))
if (!PyArg_ParseTuple(args, "O:float", &v))
if (!PyArg_ParseTuple(args, "O:len", &v))
if (!PyArg_ParseTuple(args, "O:list", &v))
else if (!PyArg_ParseTuple(args, "O:min/max", &v))
if (!PyArg_ParseTuple(args, "O:oct", &v))
if (!PyArg_ParseTuple(args, "O:ord", &obj))
if (!PyArg_ParseTuple(args, "O:reload", &v))
if (!PyArg_ParseTuple(args, "O:repr", &v))
if (!PyArg_ParseTuple(args, "O:str", &v))
if (!PyArg_ParseTuple(args, "O:tuple", &v))
if (!PyArg_ParseTuple(args, "O:type", &v))

Those are all the ones in bltinmodule.c, and nearly all of them are called
extremely frequently in *some* programs.  The only oddball is min/max, but
then it supports more than one call-list format and so isn't a METH_O
candidate anyway.  Indeed, Martin's patch gives a *better* message than we
get for some mistakes today:

>>> len(val=2)
Yraceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: len() takes exactly 1 argument (0 given)
>>>

Martin's would say

    TypeError: len takes no keyword arguments

in this case.  He should add "()" after the function name.  He should also
throw away the half of the patch complicating and slowing METH_O to get some
theoretical speedup in other cases:  make the one-arg builtins fly just as
fast as humanly possible.