New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
False positive using operator 'AND' while checking keys on dict() #83330
Comments
using Python 3.7.6 (default, Dec 27 2019, 09:51:07) @ macOs dict = { 'a': 1, 'b': 2, 'c': 3 }
if you `if 'a' and 'b' and 'c' in dict: print('ok')` you will get a True, since everything is true.
if you `if 'a' and 'g' and 'c' in dict: print('ok')` you also get a True because the last statement is True but the mid statement is false. To avoid this false positive, you need to be explicit: |
It's intended as non-empty strings evaluate to True so you with >>> all(char in dict for char in ['a', 'b', 'c'])
True
>>> all(char in dict for char in ['a', 'b', 'g'])
False |
P.S. You should also read the "Operator precedence" section for expressions in the Python Language Reference manual which explains that comparison operators bind tighter than Boolean AND operators: https://docs.python.org/3/reference/expressions.html#operator-precedence |
I would totally agree if it wasn't for this: >>> 'a' and 'b' and 'g' in dict
False The last evaluation is False, making the whole statement False. but thanks for the documentation link and stackoverflow suggestion. Happy new year! |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: