Built-in functions and keyword arguments

Armando Serrano Lombillo arserlom at gmail.com
Mon Oct 29 11:46:41 EDT 2007


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) (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 (the object=[1,2] won't shadow the built-in object outside
of the function).




More information about the Python-list mailing list