Built-in functions and keyword arguments

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Oct 29 18:30:28 CET 2007


Armando Serrano Lombillo a écrit :
> On Oct 29, 3:20 pm, Bruno Desthuilliers <bruno.
> 42.desthuilli... at wtf.websiteburo.oops.com> wrote:
>> Armando Serrano Lombillo a écrit :
>>
>>> 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
>> In the second case, the name of the argument *is* 'object'. Which is not
>> the case for the builtin len (which, fwiw, has type
>> 'builtin_function_or_method', not 'function', so inspect.getargspec
>> couldn't tell me more).
> 
> so that's the point, built-in functions don't behave as normal
> functions.

>> <ot>
>> While we're at it, you should avoid using builtin's names for
>> identifiers - here, using 'object' as the arg name shadows the builtin
>> 'object' class).
>> </ot>
> 
> As Duncan points out, I was using the name object because it's what
> you get when you type help(len) 

That what I thought. But anyway, you're not the only person reading this 
newsgroup, and there are a couple gotchas that are worth pointing out 
for those who don't know yet.

>(or in the calltips, or in). Anyway, I
> don't think there's any harm in overriding a builtin name in such a
> small scope 

In this specific case, possibly - because there are few chances you need 
to get at the builtin object type here. Still, it's better to avoid 
shadowing builtin names IMHO - if only for readability.



More information about the Python-list mailing list