Built-in functions and keyword arguments

Duncan Booth duncan.booth at invalid.invalid
Mon Oct 29 10:10:32 EDT 2007


Armando Serrano Lombillo <arserlom 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.



More information about the Python-list mailing list