[Python-ideas] If branch merging

Andrew Barnert abarnert at yahoo.com
Sun Jun 7 14:18:04 CEST 2015

On Jun 7, 2015, at 03:20, s.krah <stefan at bytereef.org> wrote:
> Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Jun 06, 2015 at 11:40:55PM -0400, random832 at fastmail.us wrote: 
> >> Well you could always go with if aisb = a == b. 
> > No, that is a terrible design and a source of many bugs in languages 
> > that allow it. 
> > if a = expr: ... 
> > Oops, I meant to compare a == expr, instead I assigned the result of the 
> > expression to a. 
In C I've mistyped this perhaps twice

Then you must be an amazing programmer. Or maybe you don't code in C very much. Look through the commit history of any major early C project and you'll find plenty of these errors. Dennis Ritchie made this mistake more than two times just in the Unix source.

Why do you think compilers added the warning? If this really were a non-issue that nobody ever faces in real life, no compiler vendor would have bothered to write a warning that will annoy people far more often than it helps. Or, if someone did just to satisfy some rare clumsy user, nobody else would have copied it.

in which case you get a compiler

Of course you also get the compiler warning when you use this feature _intentionally_, which means it's actually not usable syntax (unless you like to ignore warnings from the compiler, or pepper your code with pragmas). 

Most compilers let you use some variant on the syntax, typically throwing meaningless extra parentheses around the assignment, to make the warning go away. But this implies that C chose the wrong syntax in the first place.

If I were designing a new C-like language, I'd allow declarations, but not assignments, in the if condition (with the variable only live inside the if statement's scope). That would handle what you want 90% of the time, and usually better than the current rule, and would have no chance of confusing an assignment with a comparison, so the compiler warning would go away.

But of course this is irrelevant to Python, which doesn't have variable declarations (or sub-function scopes). In Python, I think not allowing assignment in an if condition was the right choice.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150607/f673dff3/attachment.html>

More information about the Python-ideas mailing list