Boolean tests [was Re: Attack a sacred Python Cow]

Maric Michaud maric at aristote.info
Wed Jul 30 16:50:00 CEST 2008


Le Wednesday 30 July 2008 15:31:28 giltay at gmail.com, vous avez écrit :
> > > class Signal:
> > >     [...]
> > >     def dc_offset(self, amount):
> > >         if amount == 0:
> > >             return
> > >         self.samples = [sample + amount for sample in self.samples]
> >
> > This function is also wrong assuming that because amount compare to zero,
> > it can be added to sample.
>
> Not quite.  I'm assuming that if amount equals 0, then amount is some
> scalar.  In fact, only if that comparison fails will I get my
> exception: since [] != 0, it will then try to add sample + [], which
> will raise TypeError.
>
> > If you want to make type checking just check the type or convert your
> > parameter to an int, but the test "== 0" is of no help here.
>
> I'm not going for type checking here because I want Signal to support
> int and float samples (and numpy.int16, &c.).

Ok, but the fact that amount == 0 passes, doesn't ensure you didn't a 
programming error, this add just some relative robustness (protect you from 
passing an empty list). And a reader would probably not see your intention 
here (he already expect a scalar due to the name of the variable).

This is exactly the problem ABC is intended to solve.

Without ABC, to explicitly ensure amount is a scalar, just doing a int(amount) 
or int(abs(amount)) if you want to deal with complex numbers too, at the 
begining of the function is a common idiom.

-- 
_____________

Maric Michaud



More information about the Python-list mailing list