Bryan Olson wrote: > D'Arcy J.M. Cain wrote: >> John Nagle wrote: >>> What's the cheapest way to test for an empty dictionary in Python? > >> Try this: >> >> if dict: > > D'Arcy is right; that's the way to go. I'll add that 'dict' is the name > of the built-in class, so an instance is usually best named something else.
Is this a documented language feature? The only references to this in the spec are vague. In "3.4.5 Emulating container types" there's "Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context." That's as close as the reference manual seems to come. There are mentions that in Python 3K, __nonzero__ should be replaced by __bool__. But I'm not finding anything in the spec that actually says that sequences, used in a Boolean context, are False if empty and True if nonempty. In fact, "5.8 Comparing Sequences and Other Types" in the Tutorial ("Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name.Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc.") might lead one to think that this wasn't the case. John Nagle -- http://mail.python.org/mailman/listinfo/python-list