Well, I finally ran into a Python Unicode problem, sort of

Steven D'Aprano steve at pearwood.info
Sun Jul 3 22:30:42 EDT 2016


On Mon, 4 Jul 2016 10:17 am, BartC wrote:

> On 04/07/2016 01:00, Lawrence D’Oliveiro wrote:
>> On Monday, July 4, 2016 at 11:47:26 AM UTC+12, eryk sun wrote:
>>> Python lacks a mechanism to add user-defined operators. (R has this
>>> capability.) Maybe this feature could be added.
>>
>> That would be neat. But remember, you would have to define the operator
>> precedence as well. So you could no longer use a recursive-descent
>> parser.
> 
> That wouldn't be a problem provided the new operator symbol and its
> precedence is known at a compile time, and defined before use.

You're still having problems with the whole Python-as-a-dynamic-language
thing, aren't you? :-)

In full generality, you would want to be able to define unary prefix, unary
suffix and binary infix operators, and set their precedence and whether
they associate to the left or the right. That's probably a bit much to
expect.

But if we limit ourselves to the boring case of binary infix operators of a
single precedence and associtivity, there's a simple approach: the parser
can allow any unicode code point of category "Sm" as a legal operator, e.g.
x ∇ y. Pre-defined operators like + - * etc continue to call the same
dunder methods they already do, but anything else tries calling:

x.__oper__('∇', y)
y.__roper__('∇', x)

and if neither of those exist and return a result other than NotImplemented,
then finally raise a runtime TypeError('undefined operator ∇').

But I don't think this will ever be part of Python.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list