This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Const folding in parser with negative numbers doesn't match float/int behaviour
Type: behavior Stage: resolved
Components: Parser Versions: Python 3.10, Python 3.9, Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: anthonypjshaw, lys.nikolaou, pablogsal, steven.daprano, tim.peters
Priority: normal Keywords:

Created on 2021-07-21 05:18 by anthonypjshaw, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg397922 - (view) Author: anthony shaw (anthonypjshaw) * (Python triager) Date: 2021-07-21 05:18
Powers with negative bases do not observe the same rules that float_pow/long_pow do when it comes to returning negative results/

Example:

> -2 ** 2
-4

>>> x = -2
>>> y = 2
>>> x ** y
4

>>> -2. ** 2.
-4.0
>>> x = -2.
>>> y = 2.
>>> x ** y
4.0

Tested on 3.8, 3.9 and 3.10, they all have the same bug.
msg397923 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2021-07-21 05:25
The binary power operator (`**`) has higher precedence than the unary negation operator (`-`).

That is, -x**y groups as -(x**y).

Not a bug - that's how it was designed and how it's documented.

Note that this isn't novel, either. For example, to give just one example of many, that's how Maxima does it too:

(%i1) -2**3;
(%o1) -8
msg397924 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-07-21 05:26
Not a bug, this is due to operator precedence.

It is documented under the power operator:

https://docs.python.org/3/reference/expressions.html#the-power-operator

and in the operator precedence table:

https://docs.python.org/3/reference/expressions.html#operator-precedence

If you want to raise a negative literal to a power, you need parentheses:

    (-2)**2
msg397925 - (view) Author: anthony shaw (anthonypjshaw) * (Python triager) Date: 2021-07-21 05:31
Thanks! I didn't realise it applied the negative operator instead of loading the constant value.
History
Date User Action Args
2022-04-11 14:59:47adminsetgithub: 88858
2021-07-21 05:31:43anthonypjshawsetmessages: + msg397925
2021-07-21 05:26:37steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg397924

resolution: not a bug
stage: resolved
2021-07-21 05:25:37tim.peterssetnosy: + tim.peters
messages: + msg397923
2021-07-21 05:24:49anthonypjshawsettitle: Const unfolding in parser with negative numbers doesn't match float/int behaviour -> Const folding in parser with negative numbers doesn't match float/int behaviour
2021-07-21 05:18:16anthonypjshawcreate