On 09/07/10 12:52, Phlip wrote:
try:
     return Model.objects.get(pk=42)
except Model.DoesNotExist:
     return sentinel

The flow of control is much clearer this way.

It reminds me of Visual Basic.

And no it's not "much clearer". Exceptions are for catastrophic errors
that the caller should care not to handle. A "record not found" is not
a catastrophe.

Exceptions are not limited to catastrophic errors, simply exceptional (not the common) cases. E.g. iterators raising StopException when exhausted.

>>> i = iter(range(2))
>>> i.next()
0
>>> i.next()
1
>>> i.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> i = iter(range(2))
>>> for v in i:
...     print v
...
0
1

Running out of things to iterate over is pretty non-catastrophic in my book. :)

Using exceptions as in the grandparent's post seem perfectly fine to me. The other option would be to LBYL:

  items = list(MyModel.objects.filter(...))
  if len(items) == 1:
    do_something(items[0])
  else:
    what_the(...)

-tkc




--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to