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: Ternary operator precedence relative to bitwise or
Type: behavior Stage: resolved
Components: Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: amazingmo, gvanrossum
Priority: normal Keywords:

Created on 2021-01-12 01:20 by amazingmo, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg384874 - (view) Author: Peter (amazingmo) Date: 2021-01-12 01:20
Hello,

I expect the following code to run fine, but the assertion fails. dbg1 is 1, while dbg2 is 3.  I thought they would both be 3.
Note that the only difference between the expressions for dbg1 and dbg2 are the parentheses.
Please accept my apologies if this is expected behavior, but it came as a big surprise to me.


import json
if __name__ == "__main__":
    msg = '''
        {
        "Sync Setup Flags": {
            "Setup Sync": "Enable",
            "Generate Primary Sync": "Enable",
            "Backup Primary Sync": "Disable",
            "Follow Only": "Disable",
            "Use Local Clock": "Disable",
            "Set Active": "Disable"
        }
        }
        '''
    obj = json.loads(msg)
    dbg1 = \
        1 if obj["Sync Setup Flags"]["Setup Sync"] == "Enable" else 0 | \
        2 if obj["Sync Setup Flags"]["Generate Primary Sync"] == "Enable" else 0 | \
        4 if obj["Sync Setup Flags"]["Backup Primary Sync"] == "Enable" else 0 | \
        8 if obj["Sync Setup Flags"]["Follow Only"] == "Enable" else 0 | \
        16 if obj["Sync Setup Flags"]["Use Local Clock"] == "Enable" else 0 | \
        128 if obj["Sync Setup Flags"]["Set Active"] == "Enable" else 0
    dbg2 = \
        (1 if obj["Sync Setup Flags"]["Setup Sync"] == "Enable" else 0) | \
        (2 if obj["Sync Setup Flags"]["Generate Primary Sync"] == "Enable" else 0) | \
        (4 if obj["Sync Setup Flags"]["Backup Primary Sync"] == "Enable" else 0) | \
        (8 if obj["Sync Setup Flags"]["Follow Only"] == "Enable" else 0) | \
        (16 if obj["Sync Setup Flags"]["Use Local Clock"] == "Enable" else 0) | \
        (128 if obj["Sync Setup Flags"]["Set Active"] == "Enable" else 0)

    assert(dbg1 == dbg2)
msg384878 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2021-01-12 01:33
You may be surprised, but it's not a bug -- '|' binds tighter than 'if'/'else'.

If you need more help, please contact a user forum.
History
Date User Action Args
2022-04-11 14:59:40adminsetgithub: 87066
2021-01-12 01:33:54gvanrossumsetstatus: open -> closed

nosy: + gvanrossum
messages: + msg384878

resolution: not a bug
stage: resolved
2021-01-12 01:20:28amazingmocreate