On 2008-08-01, Terry Reedy <[EMAIL PROTECTED]> wrote: >> Nevertheless, I think this is probably the best example of the >> enhanced polymorphism of "if x" yet. I'm kind of surprised no one >> came up with it.) > > I think of Python code as 'generic' rather than 'polymorphic'. I am not > sure if that is a real difference or not, since I am a bit fuzzy on the > meaning of 'polymorphic' in this context. > > The generality of 'if x:' depends on the context. If x is defined as a > number by doc or previous code (or possibly even by subsequent code), > then 'if x:' is equivalent to 'if x != 0:'. At this point, it is a > stylistic argument which to use. > > But here is an example where 'if x:' is more generic. > > def solve(a,b): > 'a and b such that b/a exists' > if a: > return a/b > else: > raise ValueError('a not invertible, cannot solve' > > Now suppose we have a matrix class (2x2 for simplicity and realism). > Its __bool__ (3.0) method implements 'is non-singular'. As written > above, solve(mat,vec) works (with compatible mat and vec sizes), but it > would not with 'if a != 0:'. > > Of course, the issue goes away by not looking before the leap: > > def solve(a,b): > return a/b > # let callers deal with exceptions > or > try: > return a/b > except... > # raise customized error
Maybe I'm going to be pedantic here, but I fear that your code won't work with matrices. The problem is that multiplication is not commutative with matrices. This means that matrices have two divisions a right and a left division. A far as I know the "/" operator usaly implements the left division while solving is done by using a right division. So your code will probably fail when applied to matrices. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list