Custom operator

Terry Reedy tjreedy at
Fri Feb 6 19:42:50 CET 2004

<mathias.foehr at> wrote in message
news: at
>I want to define new operators because mathematicians use special
> (eg circle plus (+), circle times (*), arrows ->) since centuries.
> It increases readability in this area and people have got used to it.

I am sympathetic to the desire and for the same reason, but there are
practical problems with operator extensibility, which is why most computer
languages lack it.

Your choices:

* Reuse existing operators (which Python does allow).

* Use overt functions and function calls.  Operators are covert functions
with an alternate and somewhat ambiguous syntax for function calls, which
is why associativity and precedence rules are needed to disambiguate.
Short names are not all that bad, and meaningful short name also have
readability benefits.

* Write custom additions to some version of the interpreter.

* Write a preprocessor that does a partial parse to identify custom
operators and the blocks governed by each and then use rules to rewrite
code with overt function calls.  If the preprocessor is an external
program, it can be written in any language.  One can preprocess 'in line',
by quoting the code, manipulating it, and then compile or execute.  This
works best when the custom manipulation is pretty localized.

* Use another language

> By the way, are there hooks in python to preprocess a statement before
> python compiler takes care of it?

No, there is no built-in macro facility.  The best you can do is to quote
code to protect it from the initial compiler pass so you can manipulate it
as a runtime string before really compiling it.

Terry J. Reedy

More information about the Python-list mailing list