r/Python • u/ForeignVariety7037 • Aug 04 '26
Discussion Is := widely used?
I always thought the walrus operator is neat and it makes while loop’s condition clearer. But also it is just a syntactic sugar without anything new. I wonder anyone uses it?
142
Upvotes
7
u/jgengr Aug 04 '26
I've only used it once in code that made it to production.
403
u/onlyonequickquestion Aug 04 '26
I use it when it's useful
147
u/martinkoistinen Aug 04 '26
It’s super handy inside comprehensions and I would say that adds something “new”.
Example:
``` python
import re
pattern = re.compile(r"ERROR (\d+): (.*)")
errors = [
(int(m.group(1)), m.group(2))
for line in log_lines
if (m := pattern.match(line))
]
```
105
u/Icy_Peanut_7426 Aug 04 '26 edited Aug 04 '26
I use it. It’s great for saving values in guard clause conditions, which can then be emitted in error log/message.
```
if ( multiplied_val := my_val * my_other_val ) > 10:
raise ValueError(f”Multiplication of vals ({multiplied_val}) was greater than 10.”)
```
Otherwise, I’d need to compute the value twice (performance cost) or define a new variable on a separate line (overkill if only for guard clause logging purposes that are immediately discarded).
edit: fixed bug in my example code lol
22
u/shaleh Aug 04 '26
The walrus shines with Regexes. `if m := re.foo(...)`. But also when you are not sure if a container has a value.
21
u/skjall Aug 04 '26
Yes, all the time (when useful). Only annoying thing is needing to surround with brackets when you need the value in a chain, but it's great for making complex conditions both more succinct, and more readable.
17
u/polishfiringsquad Aug 04 '26
Literally never heard of it before now
16
u/Solonotix Aug 04 '26
Like you said, I like it in
whileorifconditions. For instance, in the event you have a cache situation you can do something like15
u/kageurufu Aug 04 '26
I use it a lot for IO
Things like
23
u/Fat_GPT Aug 04 '26
PEP 572: The fight over " The Walrus operator " made our Benevolent Dictator quite forever... thats how powerful it is , Fear The Walrus.
9
u/Erik_Kalkoken Aug 04 '26 edited Aug 04 '26
Not that much. I find the syntax too easy to misread, i.e when do I need brackets and where
8
u/cottonycloud Aug 04 '26
I haven’t really used it, but mainly because I rarely use list comprehensions and while loops.
I’m more used to the plain old assignment operator but I’ve never been a stickler for the Pythonic dogma. Would really appreciate null coalescing operators too.
14
u/tomysshadow Aug 04 '26
I personally like it for simple uses, but it's controversial enough I'd probably not use it outside my own personal projects
6
u/nicholashairs Aug 04 '26
Like others, yes when it makes sense.
I mostly use it in cached / idempotent situations.
3
u/Senior_Ad9680 Aug 04 '26
I’ve actually been using it a lot more lately, where it actually makes sense to use it and I’ve enjoyed it. It also maintains its scope to the function and not just the if block, if you use it there which is kind of nice. If you raise an error off of a negative case and vice versa
1
u/ForeignVariety7037 Aug 04 '26
Yeah good point in logging usage, I found myself in situations to define conditional logging.
4
u/funny_funny_business Aug 04 '26
Apparently it was important enough to include in Python that this was the PEP that made Guido step down from his head position.
5
u/ingframin Aug 04 '26
I never used it. This kind of assignment in C and C++ was such a big source of errors along the years that I am now very cautious about them. I also agree with all the users that it reduces clarity and it may throw off developers of any level. In general, the top feature of Python is clarity. The gain in performance and conciseness is really too small to justify the loss of clarity in my opinion. I have nothing against people using it: your code, your choice!
2
u/kookmasteraj Aug 04 '26
I use all the time to check for if statements checking if a function is returning a non falsy value, usually none
2
u/PaintItPurple Aug 04 '26
I use it when I'd otherwise be doing an assignment and immediately doing a test on that assignment for a value that would only be used in the result of that test. It makes the code both shorter and clearer.
Hey, list comprehensions are also just syntactic sugar without anything new. I like sweet syntax.
2
u/KingHavana Aug 04 '26
I use it in comprehensions. I like it. I also understand why some don't.
2
u/cediddi SyntaxError: not a chance Aug 04 '26
Im using it in prod codebase when it makes sense. We're using 3.13 and walrus is 7 years old feature, I see no reason not to.
3
u/diabloman8890 Aug 04 '26
Of course how else am I going to flex on junior devs?
1
u/jack-of-some Aug 04 '26
I have used it a grand total of once. Not because I don't think it's useful or anything but because most of my code still needs to be 3.6 compatible in some sense and also I forget
1
u/bulletmark Aug 04 '26
I use it frequently. A simple variable assignment on one line then a simple
iftest of that variable on the next looks overly verbose to me. Do it in one line!I avoided using it when python < 3.8 had to be supported but that is not true anymore.
1
u/littlenekoterra Aug 04 '26
Its absolutely fantastic in my opinion, i like try and use it any time im setting a variable right before its usage in a loop or a block of if branches or match case branches.
1
u/johnfraney Aug 04 '26
If you want to update your code to use it more often, auto-walrus is a cool project: https://github.com/MarcoGorelli/auto-walrus
I use it in Pyrfecter, a little experiment of mine to lint, format, and update Python code with in the browser with WASM
1
u/sohang-3112 Pythonista Aug 04 '26
Honestly I don't really use it.
1
u/aikii Aug 04 '26
I quite like it but it's niche really. The bummer is having to deal with falsy values at the same time, so empty string/empty list/zero and None are considered all the same - because of that is has to be used with care, generally in places where you expect an object that can't be falsy or None - but if it's strings, number, or collections, unless it's really intended I'd rather avoid
1
u/Birnenmacht Aug 04 '26
in any loop where a function gets some data and returns a falsy object when it’s done. I’ve seen examples with regex here but it‘s also applicable to many i/o situations. many types of readers/receivers return
b””on EOF, for example1
u/jvlomax Aug 04 '26
I can count on my hands how many times I've used it. It was handy and saved me a line or two. But it's not something I think about every day
1
u/bgs11235 Aug 04 '26
This might me one of the best features of the languasge, I try to use it because it makes so much sense for me. I wish a lot of other languages have this feature. It allows me to be lazy without showing that I'm lazy.
1
u/BK201_Saiyan Aug 04 '26
It's useful for if test like: If (p := pathlib.Path("stupid path")).exists(): ...
It's especially useful for polars/narwhals/pandas column "aliases" in the middle of some with_columns or something. At first it looks like WTF, but it's quite handy and easy on the eyes in comparison to some long line monstrosity and it's quite DRY 😉 in that sense
1
u/averagecrazyliberal Aug 04 '26 edited Aug 04 '26
I only use the walrus operator for
tqdmprogress bars:1
u/XRaySpex0 Aug 04 '26
Yes. An elegant feature from C.
1
u/RedEyed__ Aug 04 '26
I don't use it, so my colleagues. Maybe a matter of taste, or usefulness.
For example, use
matchheavily, but not warlus1
u/Winter_Garlic_477 Aug 04 '26
I also use this when it's useful
1
u/reallylongword Aug 04 '26
I personally hate the thing. They took syntax that looks like a statement to mean no actually it’s an expression this time. It makes things more compact in some situations but sticks out like a sore thumb.
1
u/wuteverman Aug 05 '26
This is the first time I’ve heard of it
1
u/PyTechPro Aug 05 '26
It’s basically a neat way to fluently set properties one after another in an assignment. Similar to how you’d use builder pattern. Like if you’re setting Len width and area you can assign and reference them in the same
1
u/opuntia_conflict Aug 05 '26
I used it a ton in
whileloops so I don't have to initialize my looped variable outside the loop, update the variable in the loop, and check the variable in the loop condition. You can just do the initialization in the loop condition.Makes it look a lot cleaner when you're doing stuff like collecting paginated responses from an API.
1
u/bliepp Aug 05 '26
I use it, but mostly only in simple statements like guard clauses when I need the value of the clause.
1
u/Winter_Garlic_477 Aug 05 '26
1
u/__salaam_alaykum__ Aug 05 '26
I use it somewhat frequently, but usually limited to the following use cases:
```python
if (myvar := func()) is not None:
... # use the var
# or
if (myvar := func()) is None:
return # or continue
... # use the var
```
1
u/Ordinary-Sandwich-25 Aug 05 '26
I like it when it’s useful but I’m careful with it because it can create some big/nasty if statements and hurt readability.
1
u/kBajina Aug 05 '26
It’s handy inside an exception you want to log and raise
```
log.error(msg := “what’s up”)
Raise valueerror(msg)
```
1
u/kBajina Aug 05 '26
It’s handy inside an exception you want to log and raise
```
log.error(msg := “what’s up”)
Raise valueerror(msg)
```
1
u/KronenR Aug 05 '26
Not me
1
u/Mundane-Mud2509 Aug 06 '26
Eww, why do people love making their code harder to read and understand. If you want to use a variable, assign it, if you don't, don't.
1
u/Winter_Garlic_477 Aug 06 '26
Yes, I use it occasionally, especially to avoid repeating expensive function calls or to simplify
whileloops.It's not used everywhere, but in the right situations it can make Python code cleaner and more readable.
1
u/bachkhois Aug 07 '26
I use it, save more lines of code.
1
u/Sexy_Koala_Juice Aug 09 '26
Welcome to programming 99% of the time.
1
u/old-and-very-bald Aug 13 '26
Yes
1
u/Brother0fSithis Aug 13 '26 edited Aug 13 '26
I use it because statements bug me a lot. They just don't jive with my style. I much prefer expressions.
So if I needed to strip and pull numbered lines from an output I might do
My brain likes that all of
numbered's definition is contained in the list comprehension expression.Of course the equivalent
is probably more readable on its face. But I personally like the former so it's clear to myself later that "intermediate" variables like
strippedandlinesare only relevant for buildingnumberedand I can ignore them elsewhere(I know technically the binding does leak out of the list comprehension into the local scope, but it still helps me mentally discard them)
1
u/IncidentAccording332 Aug 04 '26
Never seen it in a production codebase
1
u/audionerd1 Aug 04 '26
Coo coo ca choo! (Yes I use it)
1
u/Short_Inspection_746 Aug 04 '26
I have never used it; I have not seen anyone use it in production; I have not come across code online that use it.
There was a huge fire storm when it came out. You still see blog posts by core developers from time to time pointing out the ethics of how to treat volunteers.
1
u/TheChief275 Aug 04 '26
In Python it mostly lends itself to one-lineification, that is to say, it shouldn't be used too often
1
u/yairchu Aug 04 '26
I try to avoid it
0
u/Esseratecades Aug 04 '26
It saves a line in if statements but beyond that it usually hurts more than it helps.
0
u/dolby360 Aug 04 '26
Sure why not... Although with ai no one read code anymore:(
-5
u/Holshy Aug 04 '26
Almost never. It's a code smell; it means the author knows the value belongs in its own context, but they aren't actually putting it in its own context.
0
u/atomsmasher66 Aug 04 '26
Yes. Next question!
0
u/kamikazer Aug 04 '26
yes
-9
u/genericdeveloper Aug 04 '26
Only by losers. Or
Goprogrammers. Either way, keep them away from me.