Built-in functions and keyword arguments

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Oct 29 10:24:27 EDT 2007


On Mon, 29 Oct 2007 13:52:04 +0000, Armando Serrano Lombillo 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

Because len() takes no keyword arguments, just like it says, but my_len() 
is written so it DOES take a keyword argument.

When you call a function foo(object=[1,2]) you are instructing Python to 
bind the value [1,2] to the keyword argument "object". But if the 
function doesn't have a keyword argument named "object" then it will fail 
immediately. Since len() doesn't have ANY keyword arguments, naturally it 
doesn't have one called "object".

You can see the same effect here:

>>> def my_len2(*args):
...     return len(arg[0])
...
>>> my_len2(object=[1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_len2() got an unexpected keyword argument 'object'


Apart from the error message being slightly different, many (most? all?) 
of the built in functions are like my_len2().

You may be thinking that keyword arguments are the equivalent of this:

object=[1,2]
len(object)

That is not the case. They are not at all equivalent.



-- 
Steven.



More information about the Python-list mailing list