[Python-Dev] dict contains raises TypeError on unhashable input (original) (raw)

Ben Hoyt benhoyt at gmail.com
Sat Jul 20 05:11:44 CEST 2013


"unhashable key" doesn't make sense to me. If it's a "key", it has to be hashable, and I'd think it'd often be a sign of a bug if you were trying to do "unhashable_value in mapping", so to me it seems good that it raises a TypeError. It totally depends on what's on the RHS of the in -- for instance, you get a TypeError if you do:

42 in 'xyz'

Whereas by your reasoning, it should return False, because the integer 42 can never be "in" that string. But really you want the TypeError, because that's a bug waiting to happen.

This is something of an aside, but I like the fact that Python is (relatively) strongly typed, and I think this is an example of that. Just the other day I was surprised to learn that in both Java and C# you can do:

"foo" + 3 + 4

And get "foo34" without any compile-time or run-time error (in a statically typed language like Java or C# I would have expected a compile-time error). A friend had written code equivalent to that, except with the 3 and 4 being integer variables. He was expecting to see "foo7" because that was his intent, but then realized what was going on -- numbers are automatically converted to strings in this context, and the + operators are applied left-to-right.

Whereas if you try that in Python, bomp -- TypeError: cannot concatenate 'str' and 'int' objects!

-Ben

On Sat, Jul 20, 2013 at 1:30 PM, Ethan Furman <ethan at stoneleaf.us> wrote:

http://bugs.python.org/**issue18510 <http://bugs.python.org/issue18510>

Commenting further: somekey in dict is conceptually the same as somekey in dict.keys() which /would/ return False for an unhashable key -- at least it did in 2.x; for 3.x you have to say somekey in list(dict.keys()) which seems like a step backwards. Is it worth changing contains and keys() to be in line with equality?

-- Ethan _______** Python-Dev mailing list Python-Dev at python.org http://mail.python.org/**mailman/listinfo/python-dev<http://mail.python.org/mailman/listinfo/python-dev> Unsubscribe: http://mail.python.org/mailman/options/python-dev/ benhoyt%40gmail.com<http://mail.python.org/mailman/options/python-dev/benhoyt%40gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20130720/cb889898/attachment-0001.html>



More information about the Python-Dev mailing list