Built-in functions and keyword arguments

Armando Serrano Lombillo arserlom at gmail.com
Mon Oct 29 11:34:58 EDT 2007


On Oct 29, 3:10 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Armando Serrano Lombillo <arser... at gmail.com> wrote:
>
>
>
> > Why does Python give an error when I try to do this:
>
> >>>> len(object=[1,2])
> > Traceback (most recent call last):
> >   File "<pyshell#40>", line 1, in <module>
> >     len(object=[1,2])
> > TypeError: len() takes no keyword arguments
>
> > but not when I use a "normal" function:
>
> >>>> def my_len(object):
> >      return len(object)
>
> >>>> my_len(object=[1,2])
> > 2
>
> At the C level there are several options for how you define a function
> callable from Python. The most general form is
> METH_VARARGS|METH_KEYWORDS which accepts both a tuple of arguments and a
> dictionary of keyword arguments. These then have to be parsed to find
> the actual arguments.
>
> Many of the builtin functions use only METH_VARARGS which means they
> don't support keyword arguments. "len" is even simpler and uses an
> option METH_O which means it gets a single object as an argument. This
> keeps the code very simple and may also make a slight difference to
> performance.
>
> I don't know if the reason that most builtin functions don't accept
> keywords is just historical (someone would have to go through a lot of
> code and add keyword argument names) or if there really is any
> measurable performance difference to not using the METH_KEYWORDS option.
> Being able to write less C code may be the main factor.

Ok. I was suspecting something like this. Performance issues aside, I
think it would be a good idea if built-in functions behaved exactly
the same as normal functions.

BTW, I came into this problem when trying to use functools.partial:

import functools
getattrF = functools.partial(getattr, default=False)

which I think should have worked if getattr behaved as normal
functions do.

In the end I did:

def getattrF(object, name):
    return getattr(object, name, False)

Any better idea?




More information about the Python-list mailing list