3 ms·
> if x is None: ... > if items is None: ... None's truth value is false, so the above are equivalent to: if x: ... if items: ... Empty sequences and mapp
by yogipatel 18y ago
> if x is None: ...
> if items is None: ...
None's truth value is false, so the above are equivalent to:
if x: ...
if items: ...
Empty sequences and mappings are also considered false, so you don't need to
if len(items): ...
Instead, you should
if items: ...
On a side note, does it annoy the hell out of anyone else that a sequence's length is len(foo) instead of foo.length() (or size, count, etc)?
- sah 18y agoThere's a reason why "if x is None" is idiomatic when "if not x" is shorter: >>> x = '' >>> if x is None: ... print 'x is None' ... >>> if not x: ... print 'x is empty' ... x is empty
- yogipatel 18y agoGood point. I was only thinking of sequence types, and failed to see that it would break with strings. I also somehow forgot to include "not" in the if statements! Pretty sad for a first post...
- deleted 18y ago[deleted]
- Erwin 18y agobool(x) may sometimes do more than x is None. If x is not None, then truth value is determined by calling __nonzero__ or __len__. For an ordinary sequence type that's fine, but some years ago I had code like this: if not self.db: self.db = bsddb.hashopen(...). I just couldn't find out why my process spent valuable seconds apparently reading in the entire bsddb database into memory at random times -- but that's because bool(self.db) above turned into len(self.db.keys()) != 0
- etal 18y agoMost of the builtins have a corresponding __magic_attribute__ for objects that support it: bool -> foo.__bool__, len -> foo.__len__, iter -> foo.__iter__. This is usually because some syntactic sugar or other built-in function/method relies on it being there. Example: "for x in foo" relies on foo having __iter__ (or an equivalent, maybe).