I absolutely dislike the first use-case shown, because it "hides" the assignments within other pieces of code. IMHO it makes the code less readable - especially without an IDE these assignments are sometimes hard to spot. In contrast I like the use of the walrus operator within the if-statement. Here is a clear connection where the variable is assigned becaue it is ususally only used in the branches of the if-statement.
@Indently
Жыл бұрын
I enjoy using it for short lines of code in dictionaries. I mean if you convolute it, of course it might become less readable. But the same thing goes for list comprehensions in the end. For now I suffered no readability problems with the first approach, but I will have to update you in 6 months when I look back at it. If I can read it without any comments, I'll know for sure 😅
@Indently
Жыл бұрын
The thing is: it's sugar syntax.
@DrDeuteron
Жыл бұрын
I agree. I remember reading there is no n++ operator b/c Guido never mixes expressions and assignments, but I guess that is passé. Moreover, which order is the dict construction evaluated? I guess left to right, but that is non-pythonic code imho. Also: what if you assign to word more than once in the dict constructor? Sounds buggy af.
@davea136
2 ай бұрын
People used to look at my Perl code and instantly say, "You're a C programmer, aren't you?" YES! Because I like very easy to read code. I like declaring everything clearly. I like for each statement to clearly ahve a purpose. I prefer to not obfuscate the code with incidental assignments or side-effects or "cool tricks" of any kind. Sure, I use extra lines. Here's a secret: The compiler does not care. Here's another reason to not use the walrus operator - if you are that 1 in 1000 python eveloper that actually uses the debugger *gasp* instead of prints everywhere it makes things harder to debug.
@Kommentierer
Жыл бұрын
I want to use the walrus now.
@vikingthedude
Жыл бұрын
I am the walrus
@philkeier2652
10 ай бұрын
Now your Codes looks like scrambled JavaScript.
@theViceth
11 ай бұрын
My personal favourite is the while loop. While it still isn't a proper do-while, i can at least replace the standard true check and discard the unnecessary if breaks.
@SalihArdaMermer
Жыл бұрын
I enjoy utilizing this functionality within if statements when working with complex JSON data. It is particularly useful when I want to modify the value associated with a specific key, but I'm uncertain if the key exists in every record. Here's an example: if value := my_dict.get("key"): # Perform certain operations using the value my_dict["key"] = new_value
@SagangaKapaya
26 күн бұрын
I am learning python/programing, but alyways missed this, but my mind told me this possibility needs to be there. Great. Thanks, as always great teaching.🎉
@pallenda
Жыл бұрын
Cool video! For some reason it confused me a bit with 'words' and words := Took me a bit to understand that the words variable and 'words' wasn't referring to the same thing. details: dict = {'all_the_words' : (words := text.split())}, That version might have made it easier for me. 😅
@xanderlewis
9 ай бұрын
'Walrus Operator' is going to be my new band name.
@fromgermany271
Жыл бұрын
So what‘s complained about in C(++) for decades is now honored for keystroke saving in other languages as well 😂
@datboi_gee
6 ай бұрын
been using walrus operator left and right ever since it was added, really such a beautiful tool to condense code while making things even more self-documented. I wonder if it's possible, however, to add your own custom operators into python. Like a +> for the equivalent of a self-inclusive max() function. max_sum +> sum(vals) vs max_sum = max(max_sum, sum(vals) where the evaluation is baked into the operator, and the value for use in the comparison is implied much like a += operator.
@il_dimas7337
Жыл бұрын
Found out about warlus oprator in one of the leetcode solutions. Glad to see info about it in KZitem video
@epicanthus
Жыл бұрын
I wouldn’t use the walrus operator in a dictionary. However, I think the most useful usecase of the walrus operator is not mentioned in the video. I usually use it to assign a value to a variable and do something if its new value differs from its previous. I use this approach when I want to update a tkinter widget only and only if its parameters have changed. if x != (x := func()): # order matters! do_things() Without the walrus operator I would have to use a temporary variable, like: previous_value = x x = func() if previous_value != x: do_things()
@LiamInviteMelonTeee
Жыл бұрын
Oh damn that's a cool one
@DrDeuteron
Жыл бұрын
you should pass x to do_things()....just to show that you actually need it.
@epicanthus
Жыл бұрын
Not necessarily. You may use x only next time your program reaches this snippet to check whether x has been changed since last call.
@DrDeuteron
Жыл бұрын
@@epicanthus idk. I make all function pure, so this use case I would avoid. Maybe in a method.
@junioralves9526
Жыл бұрын
I wish i already have knew about that operator when i made python algorithms avaliations on paper. It will certainly save me when i forgot to declare variables on the first lines😂😂
@rasmuskaj
11 ай бұрын
The use in the if statement is great, but my favorite is the use in elif, where it saves not only a line of code or two, but actually an indention level!
@kareltavernier6642
4 ай бұрын
This is a really good point.
@bassycounter
Жыл бұрын
I’m slightly confused but I’m determined to understand it cause it does seem really handy for cleaning up code
@Talent_Unlimited
Жыл бұрын
That's so helpful! Thank you!
@maxca
Жыл бұрын
Woow ive heard about walrus operator before but never knew how to use it. Thanks!
@starmscloud
Жыл бұрын
Excellent.. learned something new today !.. Thank You !
@xzex2609
Жыл бұрын
one of the best use case of walrus operator is to reduce the load of a function call , consider if you have such condition if ((f(x) > m > 2*f(x)) or (c >= f(x)) and (f(x)
@Bl0xxy
4 ай бұрын
except i'd recommend not naming it f since your function is already named f :D
@houstonbova3136
Жыл бұрын
Literally use it all the time. Super useful for conditional filtering. Here’s a sample where I assign the data from a mutex and then assign it again to the filtered subset to prevent an empty data frame from being returned if you accidentally configured out all of your data. def filter_data(selected_rows): if len(dff := (df := get_data()).iloc[selected_rows]) == 0: return df return dff
@Bl0xxy
4 ай бұрын
I use the walrus all the time with input() uses in if statements
@minati7485
24 күн бұрын
BTW, I like :=(Walrus Operator) & I will use it
@gksculpture
5 ай бұрын
Love this 👍🏾
@ChrisHalden007
6 ай бұрын
Great video. Thanks
@Pawlo370
2 ай бұрын
okay now i'm understand
@jamesmiller5984
Жыл бұрын
I learned about the walrus two days ago it definitely an interesting one.
@josgibbons6777
Жыл бұрын
I can't believe you didn't mention while loops.
@MarcoAntoniotti
8 ай бұрын
Ok. It took about 30 years to get this in Python.
@valorien1
6 ай бұрын
You completely "skipped" over what the operator does and what it actually means and just jumped straight over to an example. Seems like you missed the entire point of the video you yourself created. What a shame, and a waste of time.
@Indently
6 ай бұрын
Hey there! If you consider the video a waste of time, imagine how others will see your comment. I'm sorry you saw it as a waste of time, maybe you'd like to share a better example so more people can learn from your comment? I mean, the real shame is not being constructive in the comments section to help people :)
@DavidLouisson
6 ай бұрын
@@Indently I've always felt that the best way to explain 'abstract' concepts like the walrus was through the use of examples.
@eugenew2
Жыл бұрын
I thought I was the walrus, but maybe I'm the egg man.
@nbme5804
Жыл бұрын
Koo Koo kachoo!
@leightaylor8069
Жыл бұрын
Good video. The feature of Python I see underused a lot is the "dict.setdefault" method.
@Indently
Жыл бұрын
That's actually my next video coincidentally
@DrDeuteron
Жыл бұрын
I prefer collections.defaultdict, which is different...but usually more appropriate. just won't throw a KeyError.
@gardnmi
Жыл бұрын
The operator that made Guido quit python.
@DrDeuteron
Жыл бұрын
well that explains it.
@julienblanchon6082
Жыл бұрын
Very usefull to iterate a tqdm iterator and still have access to the pbar object: for x in (pbar := tqdm(it)): ... pbar.set_postfix(...)
@minati7485
24 күн бұрын
Dude, How do you type thumb up emoji in laptop
@brijeshvarsani9972
Жыл бұрын
How to change the appearance of the arrow used for function annotations from "->" to a unicode arrow symbol?
@Indently
Жыл бұрын
You need to search for something called "Ligatures"
@hiredfiredtired
Жыл бұрын
@@Indently Isn't that the thing you put on instruments to keep the reed on?
@DavidLouisson
6 ай бұрын
@@hiredfiredtired Not in the crime documentaries that I've watched LOL
@jackytaly
Жыл бұрын
I think it’s an overused operator, as in it should almost never be used. The only thing it does it make code less readable. Edit: To clarify, don’t use the operator unless you have a specific reason. If you use it just to save a line, it will likely cause headaches in debugging. especially in larger projects.
@Indently
Жыл бұрын
Out of curiousity, where do you see it overused? In 2 years I've seen it (only barely) a couple of times being used.
@jackytaly
Жыл бұрын
@@Indently I was being a little hyperbolic. By overused, I mean using it even once is too much. I just personally don’t like it because in every use case I can think of it reduces readability for the sake of saving one additional line. Edit: Fyi it wasn’t meant to be a dig, I do enjoy your channel. Just wanted to share my opinion, as at the time I saw many comments from beginners that wanted to try using this operator.
@DrDeuteron
Жыл бұрын
I agree. I use it in if statements where I need the value on some branches but not all..esp if I only need it to throw errors with messages. I mean if I need the value for clean execution, I'm happy to devote a line of code.
@tihon4979
6 ай бұрын
PEP 20: Explicit is better than implicit....
@Sailesh_Bhoite
6 ай бұрын
Nice tricks!
@namvu607
Жыл бұрын
New and come in handy 🤩
@jello195
11 ай бұрын
why do yo declare variable as variable_name : type = x instead of variable_name = x ?
@ItzPouriya
Жыл бұрын
So good explains! how do u use emojis in ur strings??
@EW-mb1ih
2 ай бұрын
Does this operator give any gain in speed performance ?
@ShubhamChavan
Жыл бұрын
I've been learning Python for a couple months now and this is the first time i Saw an arrow. damn this really discourages me and makes me feel dumb. But on the positive side there's so much more to learn and make my code more efficient. :D
@DrDeuteron
Жыл бұрын
and I have been doing py since 2002, and the arrow is new to me. As far as Im concerned it's for babies addicted to their IDEs to tell them how to write code. I mean I usually go with new python stuff, but this seems down right unpythonic. Java dev hand holding.
@IManu96I
Жыл бұрын
@@DrDeuteronare you talking about the "->" in the function signature?
@DrDeuteron
Жыл бұрын
@@IManu96I the whole package. I mean when I see: name: str = "Monty" that is not pythonic at all.
@IManu96I
Жыл бұрын
@@DrDeuteron There is not any package imported in the line you wrote. Do you mean the use of "typing" package and type hints? What you wrote is redundant, the "str" has no effect there in that specific case. It is assumed that this is a str. And what do you mean with "no pythonic"? Its zen says "better explicit than implicit". Technically adding str is more explicit. In addition, the typing provides 1) extra IDE autocompletion (as the IDE knows the type of the variable), 2) new way of documenting code and 3) tools that can scan your code to verify that there is not anything breaking through static type checking, which is a way of static testing. When developing code for companies, it is a must. Many of them enforce it. It gives you confidence that your code will not break when running it or after a big refactor
@cgyh68748
Жыл бұрын
How have I never seen this in a coding video before?
@istvandarvas3372
Жыл бұрын
saving one line of code means you are going to degarade the code readability --- so it is interesting, but I think it should nit be used a alot or abused i would say
@athulkrishnadiyil1735
11 ай бұрын
i got an instant rejection in an interview for not having good knowledge about this so called Walrus operator.
@gustavomaia2252
Жыл бұрын
How did he put a thumbs up in a string? 😂😂
@viktoreidrien7110
Жыл бұрын
nice !!
@Rainmakeroffire
Жыл бұрын
4:15 - can't get this one. What prevents you from putting it as simple as that: user_input = 'Hello world' if len(user_input) > 5: print(user_input, '👍') else: print(user_input, '👎') Why would you even need the 'text' variable?
@gregoriopescucci4997
Жыл бұрын
Because in the example text is the length of the string, not the string itself (that's user_input), so in the output you would need to rewrite print(len(user_input), "emoji"). Just a poorly named variable, should've been called something like "string_length".
@Rainmakeroffire
Жыл бұрын
@@gregoriopescucci4997 oh yeah, I've just realized it was the string length. Still I don't think it's worth the trouble to create a separate variable, just to avoid mentioning len() twice.
@DrDeuteron
Жыл бұрын
I reject 2 function calls, and would do: print(user_input, 'up' if Len(user_input) > 5 else 'down') no, I would have:\ RESPONSE = {True: 'up', False: 'down'} defined in the appropriate namespace and have 1 execution line: print(ui, RESPONSE[len(ui) > 5]) because I prefer static complexity over dynamic complexity...within reason.
@naturfagstoff
Жыл бұрын
Powerful operator, but I feel a bit discouraged by the complexity in the operation still. Seems to me it will take some time getting used to.
@michaelemulu
Жыл бұрын
you have to adopt changes Else: you'll be left behind
@joseoncrack
11 ай бұрын
Just think of all the new operators you'll have in Python 10.0!
@KeithKazamaFlick
10 ай бұрын
@@joseoncrack if im still alive yeh lol
@joseoncrack
10 ай бұрын
@@KeithKazamaFlick Get ready for the double-Walrus operator: =:= (no it won't be a cat smiley, but an operator). This one will allow bidirectional assignment. Yes, this is groundbreaking. Don't thank me.
@RobertLugg
10 ай бұрын
Python was originally written to not not have all these handy but complex feature like previous languages. After 30 years people realize the value of those "old" constructs and are adding them back.
@michaelemulu
Жыл бұрын
I learned sth. Thank you
@berni_schmorg
Жыл бұрын
Hey! I just tried using the operator in print(f'{absolute := abs(a - b)}') but that doesn't seem to work... is that not a use case for the walrus operator?
@berni_schmorg
Жыл бұрын
OHH wait it does work! It needs extra parentheses for some reason: print(f'{(absolute := abs(a - b))}')
@elmussom5433
Жыл бұрын
Im suprised nobody invented this earlier. I needed this operator for many years
@michaelraasch5496
Жыл бұрын
Doing everything in one line is meant for PERL :-)
@Lucs-ku5cb
Жыл бұрын
Or Haskell
@AlexCernat
Жыл бұрын
welcome python to 21st century 😀 nothing new that man can do in c, perl, php etc. since eons ago!
@HoSza1
Жыл бұрын
Instead of the following value = produce() while value is not None: consume(value) value = produce() You can write this: while (value := produce()) is not None: consume(value)
@DrDeuteron
Жыл бұрын
that is nice
@RoboArc
Жыл бұрын
It's still 2 lines. Not any faster doing this btw. Makes your library less new user freindly too. Since not everyone uses them regularly. Almost no reason for all this The if statement is useful though. Didn't like the first example much.
@吳政霖-b9t
Жыл бұрын
As far as I personally use it, the whole purpose of Walrus Operator is actually to reduce some annoying template typing. For example, when you use coroutines (implemented by generators), you always have to type over and over again like x=getCoro(); next(x); y=getCoro(); next(y) Or when performing regular matching, m=re.match(...); if m is not None: return ...; m=re.match(...); if m is not None: return . ..; these templates are really intrusive and interfere with readability. The Walrus Operator helps with readability as long as you maintain consistency throughout your source code.
@TSPxEclipse
2 ай бұрын
Ok, I'm sorry but I burst into laughter seeing you copy-paste in the thumbs-up and thumbs-down emojis. Emojis in code are so cursed.
@mikesmith6838
7 ай бұрын
Oh great, another operation, like list comprehension, that will allows programmers to write even more unreadable code. Well done, Python.
@Indently
7 ай бұрын
You’re every marketing teams worst nightmare for a business 🤣
@Yupppi
9 ай бұрын
print( ( 👎, 👍) [len(user_input) > 5] ) I never get to use ternary operator in programs I write.
@Indently
9 ай бұрын
But the ternary operator isn’t the walrus operator, unless you’re just talking about the ternary operator with no correlation to the video.
@davea136
2 ай бұрын
OMG! Use a WHOLE OTHER LINE?!?! Seriously, people. If screen space is the issue let's just go back to Perl so we can mystify people with one-liners in the O.G. way. Your eyes travel to the left to see declarations of vars. Embedding it in the center of a line disrupts that. Boo!
@rishiraj2548
Жыл бұрын
🙏👍
@NathanChambers
Жыл бұрын
It really is useless for most cases, since most python projects are small. If all python projects were huge, than yes this would be underrated. But as it stands, it's OVERrated in "every day" small python scripts.
@KeithKazamaFlick
10 ай бұрын
:=
@DrDeuteron
Жыл бұрын
I don't think I like type hints.
@aliasgar.burhani1099
Жыл бұрын
I thought Go was the one to introduce walrus operator ... but python did it before
@quillaja
4 ай бұрын
:= was used for assignment in Pascal. Maybe others.
@sh1maru
Жыл бұрын
This operator literally killed python
@Indently
Жыл бұрын
Yeah, Python was never used again by anyone after this sugar syntax
Пікірлер: 110