Earlier quoted context omitted.
> The "walrus operator" will occasionally be useful, but I doubt I will find many effective uses for it. The primary one I want is if m := re.match(...): print(m.group(1)) and while s := network_service.read(): process(s) both of which are both clearer and less error-prone than their non-walrus variants. The other one that I would have found useful an hour ago is in interactive exploration with comprehensions. I freq…
Coming from Perl, I used to want this badly, but then I thought that there's absolutely nothing wrong with m = re.match(...) if m is not None: pass Now, I wonder what you meant saying that single-line version is less error-prone, because I don't think so. I believe they're exactly the same in this regard, except for a bizarre case when someone would bastardize the code by putting some irrelevant lines between the ass…
for line in f:
if (m:= pat1.search(line)) is not None:
... do stuff ..
elif (m:= pat2.search(line)) is not None:
... do other stuff ..
elif (m:= pat3.search(line)) is not None:
... do something else ..
In older Python that's: for line in f:
m = pat1.search(line)
if m is not None:
... do stuff ..
else:
m = pat2.search(line)
if m is not None:
... do other stuff ..
else:
m = pat3.search(line)
if m is not None:
... do something else ..
I think the newer makes it clear that it's supposed to be a simple elif chain, where all branches following the same structure.There are other ways to structure it, but the alternatives I can think of also have their own cumbersome complexities.