[Python-bugs-list] <dict>.has_key() allows more than one argument (PR#210)

guido@python.org guido@python.org
Thu, 24 Feb 2000 07:27:56 -0500 (EST)


> [Andreas Jung]
> > According to the documentation the dictionary method has_key() allows
> > only one argument. However the current implementation allows more than
> > one argument. That makes no sense.
> >
> > >>> d={1:2}
> > >>> d.has_key(1)
> > 1
> > >>> d.has_key(1,2)
> > 0
> >
> > Maybe Python regards 1,2 as a tuple !?
> 
> This may well be a bug in the docs:  the ability to say
> 
>     d = {}
>     d[1, 2] = 5
> 
> was a late addition to Python (it implicitly converts "1, 2" to a tuple),
> and if you can use
> 
>     1, 2
> 
> as a dict key it certainly makes sense that you be able to say
> 
>     dict.has_key(1, 2)
> 
> too.  My guess is that this was added to dict.has_key at the same time it
> was added to dict.__getitem__ etc, but simply didn't get documented in the
> former.

I don't think so (clever excuse though).

To test for a tuple with has_key, you should use dict.has_key((1, 2)).

The form without the extra parentheses passes two arguments to the
has_key() method.  I'd like to exclude this syntax -- just like
list.append(1, 2), which also currently means list.append((1, 2)), but
which should really be disallowed because the user could easily have
intended list.extend([1, 2]).  (Excluding the latter is not so easy
because it would break existing sloppy code; for Python 1.6 I think we
can afford such breakage.)

The real excuse is that in Python 0.9.x, there was no difference
between f(1, 2) and f((1, 2)) -- it was all the same to the
interpreter.  While that was sometimes handy (no need for 'apply') it
didn't mix well with default arguments, when those were added, so it
was changed, but not all built-ins were fixed.

Note that dict[1, 2] means exactly the same thing as dict[(1, 2)] --
as in an assignment context, you get the tuple "for free" without the
parentheses.  This doesn't work in an argument list, as explained
above.

(I had to write this because Fred already fixed the code. :-( )

--Guido van Rossum (home page: http://www.python.org/~guido/)