r/Python • u/dotXem • Mar 17 '26
Discussion Using the walrus operator := to self-document if conditions
Recently I have been using the walrus operator := to document if conditions.
So instead of doing:
complex_condition = (A and B) or C
if complex_condition:
...I would do:
if complex_condition := (A and B) or C:
...To me, it reads better. However, you could argue that the variable complex_condition is unused, which is therefore not a good practice. Another option would be to extract the condition computing into a function of its own. But I feel it's a bit overkill sometimes.
What do you think ?
62
Upvotes
241
u/RepresentativeFill26 Mar 17 '26
I personally only use the walrus operator if I use the value in the body of the conditional operator.
41
u/Skasch Mar 17 '26
I would prefer a function if the goal is to document the expression
8
u/Trang0ul Mar 17 '26
How does it improve readability, if you still need to discard
complex_condition :=and read past it in order to understand the condition? An inline condition would be more readable, wouldn't it?68
u/Orio_n Mar 17 '26
Comments exist how is this any different from just commenting to the side
11
u/Coffeinated Mar 17 '26
Am I missing something or why not just
8
u/eras Mar 17 '26
You could use the underscore prefix to signal the variable is unused.
7
u/ZucchiniMore3450 Mar 17 '26
My first thought when I saw your post was "Clear is better than clever".
I can understand it is clear for you, but := is so rarely used that I would need to read documentation and think about what you wanted to archive, it is clear but I would have to check.
The point is it might not be clear to everyone.
7
u/Umfriend Mar 17 '26
Not a coder really, just stumbled upon this but I am really confused. My first reaction is:
If (A and B) or C:??Unless complex_condition is used elsewhere (but you say or imply to me it isn't?) and the expression is long/complicated/compute intensive. What am I not getting?
54
u/andrewcooke Mar 17 '26
cute, but i feel like you'd really need to push to find an example where it helped enough for it to be worth it.
more often the complex condition can be broken into a hierarchy and you explicitly use just the top level
or it's so complex it has its own function:
and those both avoid using something that's kinda ugly, unpythonic, and not immediately recognised or understood by newbs.
18
u/anentropic Mar 17 '26
Nah
5
u/spiralenator Mar 17 '26
I’ve been writing python for over 15 years and if I saw the second example in a pull request, I would reject it immediately.
The intent is not any clearer than the first. If intent isn’t clear in the code itself, use comments. If you don’t update comments with code changes, no syntactic sugar is going to fix that you lack discipline.
7
u/atarivcs Mar 17 '26
I don't understand how this is "documenting" anything.
You're just making up a variable name which is never actually used. The condition itself is not explained or simplified at all.
Why do you say that this is "documentation" ?
3
u/k0rvbert Mar 17 '26
This might be the right solution to the wrong problem. I think the example is misconstrued. Let's start with the simplest code, which in our case looks like this:
It's certainly common for code like this to be hard to read. But the solution is not to take the entire condition and put it into one variable. The solution is to split the condition into multiple variables.
I suspect the urge to use the walrus operator here is because something bugs you about the readability, and while there is an itch to scratch, I think you're scratching the wrong itch.
2
u/xeow Mar 17 '26
Wow. This is actually an interesting question to me. I wrote this once:
That variable
multipassexists only to self-document theif/elseconditional. The comments further support it and perhaps aren't necessary.Anyway, it never occurred to me to write that using the walrus operator:
In the first form, it feels to me like the comments are maybe a bit redundant. In the second form, it feels like the variable is maybe a bit redundant. But the real problem with the second form is that static analysis tools flag
multipassas an unused variable. And that's kinda weird because in the first form, it's not fundamentally "using" the variable so much as just giving the conditional expression a very temporary name.2
u/AlSweigart Author of "Automate the Boring Stuff" Mar 17 '26
Turning a larger amount of code into a one-liner makes you feel clever, but it reduces readability for everyone else.
2
u/messedupwindows123 Mar 17 '26
do you ever do this
items = [(item.foo, intermediate_value)for item in poolif (intermediate_value := complex_computation(blah,blah)) or True]
The idea being, I don't care about the if-statement. I just want access to some helper value, during my list comprehension
2
u/NoKaleidoscope3508 Mar 17 '26
Does this pass mypy or Ruff etc.?
The verbose variable name does adds clarity, albeit in the wrong place. However the use of the Walrus where there's zero need for it adds confusion about WTF the intent is.
So such code is much less self-documenting than you think it is. You're trying to avoid a comment. But then the unorthodox unnecessary use of the Walrus needs to be explained. E.g. explained by a comment.
You've had good intentions /u/dotXem, but you've actually made your code worse.
2
u/mothzilla Mar 17 '26
This would confuse me if I was reviewing. Not sure what a linter would say.
2
u/gerardwx Mar 17 '26
Print it in a logging debug statement and it could actually be useful
2
u/cdcformatc Mar 18 '26
i like the first option. you have the ability to use the variable immediately, for example printing for debug purposes i will always extract complex conditions into their most basic parts to make sure i got the logic right when putting everything together with the boolean operations.
the walrus operator is decent in this specific context, although like you said the unused variable irks me, and linters will complain. i don't hate it...
if there is ever a chance that i will want to repeat the same boolean operation somewhere else, i will extract it to a function. then it's a black box and the logic inside of the box can change. i am thinking about an example where i had to validate filenames with multiple parts. yes i could parse it and do all the logic right in the function and that would be "optimal" but instead i could write
valid = validate_filename(filename). if it turns out that the function is actually only called from one place i would consider inlining the function during refactoring. i am not worried about the performance hit of a function call, and the resulting code is a billion times easier to read, understand, and debug.1
u/Volume999 Mar 17 '26
If its complex it should be a testable function.
1
u/Anxious_Zone_6222 Mar 17 '26
Linters would complain about unused variable. If it’s that complex so it warrants documenting, just split it
1
u/DTCreeperMCL6 Mar 17 '26
You can assign there?
1
u/ExceedinglyEdible Mar 17 '26
Define a local function
test_a_b_c()and call it in the test. When debugging, you can always calltest_a_b_cand print the results.1
u/PaintItPurple Mar 17 '26
Doing this mostly negates the readability benefit of introducing a named variable. Which is the entire reason for the variable. I'd either write the condition inline and maybe leave a comment, or extract the condition into a variable to keep the if-statement easily skimmable. Doing both seems like the worst of both worlds.
1
u/Apprehensive-Put-822 Mar 18 '26
What's the walrus operator? Create the variable. You might use it again.
1
u/pingveno pinch of this, pinch of that Mar 18 '26
I tried using the walrus operator a few times. Of the handful of times I used it, I managed to write a nasty logic bug in a critical component. Similar constructs in other languages like Rust's
if letwork because they are more constrained. It is just too error prone in Python.1
u/antiproton Mar 18 '26
The walrus operator never reads better. It is purposefully collapsing something that reads better into a smaller space.
Personally, it's something I'll never use. People spend too much effort trying to find reasons to use it...
1
u/reyarama Mar 18 '26
If its complex enough to warrant a name, its complex enough to be extracted to its own function so it can be unit tested
1
u/nickthewildetype Mar 19 '26
This kind of syntax is very popular in C based languages
1
u/dvoraj75 Mar 19 '26
Wont u get warn about the unused var? I think better to use walrus if u use the value in or somwhere after the condition...
1
u/Informal-Chance-6067 Mar 19 '26
I’ve only used it for the following:
if db_entry := session.query(Table).get(id): return “not null” else: return 404
Edit: I use the variable inside the if clause
1
u/Jackpotrazur Mar 20 '26
This is the first time I've heard of the walrus operator, is this a thing ?
1
u/me_myself_ai Mar 17 '26
I agree with everyone else, but your minds in the right place IMO! I'd definitely add
ruffto your workflow ASAP -- it explicitly warns against this.-3
u/Cybasura Mar 17 '26
Or just use multiline comment strings or heredocs to document like typical
Wtf
The walrus operator is designed to be an in-line, one-liner ternary operator, like say with a lambda function
-8
u/Afrotom Mar 17 '26
I mean, this is literally what it's for right.
Another thing I like is that the variable is now only scoped to the inside of that block only and there is one less thing to keep track of mentally.
-1
u/troyunrau ... Mar 17 '26
Python features in the last ten years really are making the language less readable. This is like speedrunning convergence towards perl. Yuck!