4 ms·
I'm all in favor of the walrus operator for the for loop, but the first example given to justify it is code I'd never write. The first if does a return, so the
by tasty_freeze 7y ago
I'm all in favor of the walrus operator for the for loop, but the first example given to justify it is code I'd never write. The first if does a return, so there is no need for the else: and indentation. I'm sure there are other code examples that would justify it, but this one is unconvincing.
- duckerude 7y agoThe return statements make it a poor example. There's an example from the standard library in the PEP that has a similar shape: reductor = dispatch_table.get(cls) if reductor: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor: rv = reductor(4) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: raise Error( "un(deep)copyable object of type %s" % cls) Becomes: if reductor := dispatch_table.get(cls): rv = reductor(x) elif reductor := getattr(x, "__reduce_ex__", None): rv = reductor(4) elif reductor := getattr(x, "__reduce__", None): rv = reductor() else: raise Error("un(deep)copyable object of type %s" % cls)
- wodenokoto 7y agoNice way in without walrus m = re.match(p1, line) if m: return m.group(1) m = re.match(p2, line) if m: return m.group(2) m = re.match(p3, line) ... With walrus: if m := re.match(p1, line): return m.group(1) elif m := re.match(p2, line): return m.group(2) elif m := re.match(p3, line): The example would have been better if it didn't have the return, but just a value assign or a function call.