4 ms·
Ate there any good reasons to assign things in an if statement?
by WillPostForFood 7y ago
Ate there any good reasons to assign things in an if statement?
- Sean1708 7y agoI have to work with stacks a lot and doing while (item := stack.pop()) is not None: # ... is a lot harder to get wrong than item = stack.pop() while item is not None: # ... item = stack.pop() Really wish it was scoped though... Edit: Just realised you were asking for an if-statement... but I think this is still a valid point.
- wffurr 7y agoScope the assigned variable to the if statement.
- mc3 7y agoIf so, it might be a code smell to consider defining a separate function.
- rs23296008n1 7y agoSo far, all the suggested usages of := have a code smell about them.
- archgoon 7y agothat's not how the walrus operator works though. if x := 3: print("x is now: ", x) print("x isn't scoped to the if:",x)
- Thorrez 7y agoThe post's example with reductor seems like a good reason to me.
- thaumasiotes 7y agoDon't think of the walrus as being an assignment. You can conceptualize it that way, but you shouldn't; that thought will be unhelpful in producing and reading code. Assignment is still the normal =, with a variable on the left and the value you want to put in it on the right. The walrus is for giving names to values you were computing anyway. Instead of a storage bin and the value you want to store there, the walrus involves a value and the name you want to refer to it by. Conceptually, the value is where you begin.
- willtim 7y agoThat is really really confusing given that there is lots of prior art for = meaning variable binding and := assignment (Algol, Pascal etc). Using = for assignment was a bad decision and it's coming back to bite. EDIT: Based the examples given, the Python := operator doesn't appear to behave as a let binding. The scoping suggests it is another form of assignment.
- thaumasiotes 7y agoIt is another form of assignment if you're implementing a Python compiler. The intended use is as a tool for naming values.
- deleted 7y ago[deleted]
- willtim 7y agoI'm trying to understand the semantics not the implementation. The semantics are clearly not "let x = .. in .." as anyone familiar with expression let-bound variables would expect. I wish I could avoid Python but sadly it is taking over the world. It's even taught at schools now and my kids will be learning it as their first programming language.