Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change operator precedence in Python

I have overloaded some Python operators, arithmetic and boolean. The Python precedence rules remain in effect, which is unnatural for the overloaded operators, leading to lots of parentheses in expressions. Is there a way to "overload" Python's precedences?

like image 880
Alan Macdonald Avatar asked Aug 04 '12 18:08

Alan Macdonald


1 Answers

You can cheat that mechanism in this way:

  1. Override all operators to not do the calculations but create list of instructions wrapped in some object.
  2. Add your own bracket operator (ie. as a _ function).

Example:

>>> a = MyNumber(5); b = MyNumber(2); c = MyNumber(3)
>>> a + b * c
MyExpression([MyNumber(5), '+', MyNumber(2), '*', MyNumber(3)])

Brackets:

>>> a + _(b * c)

Note that _ is a function that evaluates expression (in order you enforce in it)

So if you reverse priorites you will get:

>>> _(a + b * c)
MyNumber(21)

PS. Django does similar trick with Q and F operators.

like image 152
Tomasz Wysocki Avatar answered Oct 29 '22 16:10

Tomasz Wysocki