Matlab vs Python (was RE: Discussion: Introducing new operators for matrix computation)

John Lull lull at acm.org
Tue Jul 18 10:51:52 EDT 2000


At the dawn of the third millenium (by the common reckoning), Paul
Prescod <paul at prescod.net> wrote (with possible deletions):

> I don't think you need __getattr__
> 
> class Matrix:
> 	def __init__( self, ....):
> 		self.T=Transpose( self )
> 		self.H=Hermitian( self )
> 		self.I=Inverse( self )
> 		self.C=Conjugate( self )
> 		self.E=Elementwise( self )
> 		self.M=self # matrixwise is default
> 	... other matrix-like methods ...

This, I think, works for everything but .E.  You can write a method
Transpose which, for most possible classes derived from Matrix, does
the right thing by returning a derived class object with the data
transposed.  An element-wise matrix, however, would have exactly the
same data as the original matrix, it just has a lot of the *methods*
replaced.  To make this work for derived classes, you have to either
add a level of indirection to all the standard operator methods, or
prohibit overriding the standard operator methods.

How about one small change to Python, breaking no existing code, and
applicable (I'm sure) to domains far-afield from linear algebra:

Currently,
    object operator other
is really just convenient shorthand for:
    object.__operatorname__(other)
or
    other.__roperatorname__(object)
where operator is any binary arithmetic operator.

What if we simply make
    object @operator other
convenient shorthand for:
    object.__alt__operatorname__(other)
or
    other.__alt__roperatorname__(object)
for all those same operators?

This would be a syntax error when applied to anything other than an
object, and would raise an appropriate exception if neither object nor
other provided an appropriat __alt method.

This would provide a way of adding a reasonable variety of
domain-specific operators to *any* class with very little impact on
the language, zero runtime penalty, and obvious & correct behaviour
when creating derived classes.  It would not break any existing code
and should be very simple to implement.

I haven't thought through whether the same behavior should apply to
anything other than binary arithmetic operators.  Doing so would seem
very Pythonic.

Regards,
John



More information about the Python-list mailing list