3 ms·
But it used to be that any expression on its own was a valid statement. Is that going to change? When is an expression allowed to have := in it, is (x := 1)
by Scarblac 7y ago
But it used to be that any expression on its own was a valid statement. Is that going to change?
When is an expression allowed to have := in it, is
(x := 1)
on its own allowed?
- n3k5 7y agoFor contexts where the walrus is not allowed, see [0]. You'll find that it's generally possible to circumvent the restriction by parenthesising the expression. So yes, (x := 1) is a valid (but poorly written) statement. But while there are now two ways of doing assignment, I wonder how often people will actually encounter situations where it's difficult to figure out which choice is better. [0] https://www.python.org/dev/peps/pep-0572/#exceptional-cases https://www.python.org/dev/peps/pep-0572/#exceptional-cases
- Sohcahtoa82 7y agoAllowed, yes. But the PEP that introduced walrus operators says not to do it. Every possible line of code has an alternate ugly way to write it. This isn't a valid criticism. Anyone who decides to start writing simple assignment statements like that deserves to be ridiculed for writing ugly code.
- Scarblac 7y agoOf course, and there's no reason to write such code. I just dislike that the simple syntax rule "any expression can be used as a statement" now has an exception. I haven't been able to think of scenarios where that might have consequences (code generation or refactoring tools?) but that doesn't say much as I'm not that smart. Edit: having looked at the cases that are disallowed, they remind me of generator expressions. Those are usually written with parens, that can optionally be omitted in some cases. := is the same except they can be omitted in so many cases that it's easier to list the cases where they can't. I think a generator expression used as a statement already requires the parens, even though they can be omitted e.g. as a single parameter of a function call. So that's probably ok then.