[Tutor] evaluating AND

Rikard Bosnjakovic rikard.bosnjakovic at gmail.com
Fri Sep 14 06:34:45 CEST 2007

On 14/09/2007, Terry Carroll <carroll at tjc.com> wrote:

> The second one, which just checks "if x" and is satisfied with any false
> value, including an empty tuple, does not raise the error condition, even
> though the data is bad.  This is a bad thing.

For me, "if x" would be enough. If you think it's a bad thing when x
is of the wrong data, then you really should check that it contains
*correct* data as well.

Using the the two function of yours, setting x to an integer:

>>> x = 2
>>> print test01(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/tmp/python-3716vZq", line 3, in test01
TypeError: unsubscriptable object
>>> print test02(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/tmp/python-3716vZq", line 8, in test02
TypeError: unsubscriptable object

Rewriting your test01-function into this:

def test01(x):
 if (type(x) == type((0,)) and
     (x is not None) and
     (length(x) == 2)):
  if x[0]>0:
   return x[1]/x[0]

and testing again:

>>> x = 2
>>> print test01(x)

My point is that if you think it's bad for a function to receive
incorrect data you should do exhaustive checks for the input to make
sure it is of correct type, size and whatever the requirements might
be, not just check if it's a tuple or not.

- Rikard - http://bos.hack.org/cv/

More information about the Tutor mailing list