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?
-
5No. It's part of the python language itself. Thats how the language parses.jdi– jdi2012-08-04 18:28:48 +00:00Commented Aug 4, 2012 at 18:28
-
1@jdi That's an answer, why not make it one?kojiro– kojiro2012-08-04 18:30:57 +00:00Commented Aug 4, 2012 at 18:30
-
@kojiro: Well only because I couldn't find a link to official python docs stating that it can't be changed. I found tons of 3rd party links stating it though.jdi– jdi2012-08-04 18:33:00 +00:00Commented Aug 4, 2012 at 18:33
-
I came across the same problem while trying to increase precedence of xor operator when implementing geometric algebra. Behold, it was Professor Macdonald himself who asked this same question much earlier.syockit– syockit2023-07-23 14:20:35 +00:00Commented Jul 23, 2023 at 14:20
2 Answers
You can cheat that mechanism in this way:
- Override all operators to not do the calculations but create list of instructions wrapped in some object.
- 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.
Comments
No. It's part of the python language itself. Thats how the language parses.
Official quote: Evaluation order
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
Other quotes:
Python:Basics:Numbers and operators
When performing mathematical operations with mixed operators, it is important to note that Python determines which operations to perform first, based on a pre-determined precedence. This precedence follows a similar precedence to most programming languages.
Note that Python adheres to the PEMDAS order of operations.