Implicit conversion to boolean in if and while statements

Ian Kelly ian.g.kelly at gmail.com
Fri Feb 8 20:06:34 EST 2013


On Fri, Feb 8, 2013 at 12:58 PM, Rick Johnson
<rantingrickjohnson at gmail.com> wrote:
> I'm a bit unnerved by the sum function. Summing a sequence only makes sense if the sequence in question contains /only/ numeric types. For that reason i decided to create a special type for holding Numerics. This will probably result in many complaints from lazy people who want to use only one Sequence type, which holds mixed types, THEN jamb nothing but numeric types into it, THEN have a sum method that throws errors when it encounters a non-numeric type!!! I say, too bad for you.
>
> Stop obfuscating your code! Of course someone could probably find a legitimate reason to apply a sum method to non-numeric values; if so, then inherit from NumericSequence and create your custom type!

Are you aware that the approach you're advocating here is bad OOP
design?  If you declare a class NumericSequence with the property that
it contains only numeric types, and then you declare a subclass
NonnumericSequence that does not share that property, then guess what?
 You've just violated the Liskov Substitution Principle.

The goal you're trying to achieve here is nonsensical anyway.  Ask
yourself what the semantic meaning of the sum() function is, what
purpose it is meant to serve.  My answer: it is the reduction of the
addition operator.  The implication of this is that the input type of
the sum() function is not "numbers", but rather "things that can be
added".  That includes numbers, but since I see from your proposed
class hierarchy that you are retaining the __add__ method on
sequences, it also includes sequences.  Are you really going to tell
the user that (1, 2, 3) + (4, 5, 6) is perfectly fine, but that the
semantic equivalent sum([(1, 2, 3), (4, 5, 6)]) is nonsense?



More information about the Python-list mailing list