4 ms·
As someone who is not very good with grammars of programming languages, what is wrong with having if a = b(): foo(a) I know it doesn't work, but wh
by wodenokoto 8y ago
As someone who is not very good with grammars of programming languages, what is wrong with having
if a = b():
foo(a)
I know it doesn't work, but why couldn't it?
- Macha 8y agoToo easy to typo when you mean if a == b(): foo(a)
- misnome 8y agoThis is addressed in the PEP: https://www.python.org/dev/peps/pep-0572/#why-not-just-turn-existing-assignment-into-an-expression https://www.python.org/dev/peps/pep-0572/#why-not-just-turn-.... Their argument seems to be that 'if a = b()' is too similar to 'if a == b():' and thus doing that would cause more mistakes, whereas at the moment (?) they are caught by the parser.
- AlexandrB 8y agoYes. This mistake is very common in C. So much so that it's considered good practice to put the constant first when doing equality comparisons: if (10 == x) This way accidentally missing a "=" triggers a compiler error instead of quietly doing the wrong thing.
- sorenjan 8y agoCalled Yoda conditions. https://en.wikipedia.org/wiki/Yoda_conditions https://en.wikipedia.org/wiki/Yoda_conditions