user-defined operators: a very modest proposal

Steve R. Hastings steveha at localhost.localdomain
Tue Nov 22 16:48:05 EST 2005


I have been studying Python recently, and I read a comment on one
web page that said something like "the people using Python for heavy math
really wish they could define their own operators".  The specific
example was to define an "outer product" operator for matrices.  (There
was even a PEP, number 211, about this.)

I gave it some thought, and Googled for previous discussions about this,
and came up with this suggestion:

User-defined operators could be defined like the following: ]+[

I'm not any kind of language design expert, but this seems to me like a
syntax that would be easy for Python to recognize.  Because the square
braces are reversed from the usual "[]" order, this should not look like
any currently-valid code.  And square braces, IMHO, do not fail the
"low-toner printout" test. (Some earlier proposals included operators like
"~+" and these were deemed too hard to read.)

For improved readability, Python could even enforce a requirement that
there should be white space on either side of a user-defined operator.
I don't really think that's necessary.

It should be possible to define operators using punctuation,
alphanumerics, or both:

]+[
]add[
]outer*[


Examples of use:

m = m0 ]*[ m1
m = m0]*[m1

m = m0 ]outer*[ m1
m = m0]outer*[m1



It looks a lot better with the white space, I think, but it's not horrible
without the white space.


Also, there should be a way to declare what kind of precedence the user-defined
operators use. Python already has lots of operators with different precedence,
and I think the best way is just to indicate which Python operator the new
operator's precedence should match:

class MyExcellentMatrix(object):
    @precedence('*')
    def __op_outer*__(self, right):
        # ...do stuff...

I think a decorator is a good way to set the precedence. 
Perhaps the default precedence should be that of '+'.

Augmented forms should be supported:

]+=[
]*=[
]outer*=[


Examples:

m ]*=[ m0
m]*=[m0

m ]outer*=[ m0
m]outer*=[


Either I actually have made a sensible suggestion, or else people will now
explain why this idea isn't good (and I'll learn something).  Either way,
I look forward to your comments.



References:

Elementwise/Objectwise Operators
http://www.python.org/peps/pep-0225.html


Adding A New Outer Product Operator
http://www.python.org/peps/pep-0211.html


-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha



More information about the Python-list mailing list