[Python-Dev] dict containment annoyance
Scott Dial
scott+python-dev at scottdial.com
Mon Aug 14 00:46:27 CEST 2006
Jean-Paul Calderone wrote:
> def blacklisted(o):
> try:
> # Is the object contained in the blacklist set?
> return o in _blacklistset
> except TypeError:
> # If it *cannot* be contained in the blacklist set,
> # then it probably isn't.
> return False
I feel confident that the parent could've wrote this snippet himself.
His point was to discuss the semantic logic of "x in y" throwing and
exception when x can't be in y (because of the TypeError you are
catching in your snippet).
FWIW, I think the logic of swallowing the TypeError is completely
reasonable. It is surprising in a way that you are presented with an
exception. However, I can't say I have ever ran into this.
For my money, it would make the most sense to have your own blacklistset
type.
class BlacklistSet(dict):
def __contains__(self, x):
try:
hash(x)
except TypeError:
return False
return super(BlacklistSet, self).__contains__(x)
It's however unfortunate that you cannot use the handy curly-braces anymore.
--
Scott Dial
scott at scottdial.com
scodial at indiana.edu
More information about the Python-Dev
mailing list