[New-bugs-announce] [issue42900] Ternary operator precedence relative to bitwise or

Peter report at bugs.python.org
Mon Jan 11 20:20:28 EST 2021


New submission from Peter <peter_dulimov at hotmail.com>:

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)

----------
messages: 384874
nosy: amazingmo
priority: normal
severity: normal
status: open
title: Ternary operator precedence relative to bitwise or
type: behavior
versions: Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42900>
_______________________________________


More information about the New-bugs-announce mailing list