News for hackers. Stuff that matters.
Re:Python best practices by yogipatel on Wednesday July 09, 2008 @12:03AM (#240762)
> 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)?
Re:Python best practices by sah on Wednesday July 09, 2008 @12:07AM (#240768)
There'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
Re:Python best practices by yogipatel on Wednesday July 09, 2008 @03:56AM (#240901)
Good 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...
Re:Python best practices by etal on Wednesday July 09, 2008 @02:35PM (#241489)
Most 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).
Re:Python best practices by Erwin on Wednesday July 09, 2008 @04:58AM (#240936)
bool(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