A bit weird dictionary behavior

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Sep 22 07:32:14 EDT 2008


Pekka Laukkanen:
> but it still doesn't feel exactly right. Would it be worth submitting a bug?

It feels wrong because it is. In a tidier language (Pascal, Java, etc)
a boolean and an integer must be different types. Keeping booleans and
integers separated may avoid some bugs too (I don't know how many/
often).
But the Python language copies many things from C, where most things
are chosen for practical purposes and maximum efficiency (and from
much simpler Python implementations, where there was no boolean type,
so bools are grafted in), so it's not a bug, and I think it will not
be fixed soon (Python 3 was probably the last chance to change it, for
several years to come).
So you probably have to live with this illogical behavior.

On the other hand it has some little practical advantages, you can do:
sum(x == y for x in iterable)

That also equals to a more tidy:
sum(1 for x in iterable if x == y)

Regarding the dict, they are dynamically typed, but good programming
practice (that comes from experience of bugs that have bitten you)
tells you that generally it's better to be careful with the inserting
different types into a dict; often it's better to avoid doing it.

Bye,
bearophile



More information about the Python-list mailing list