Python's Walrus Operator??
HTML-код
- Опубликовано: 11 сен 2024
- ⭐ Join my Patreon: / b001io
💬 Discord: / discord
🐦 Follow me on Twitter: / b001io
🔗 More links: linktr.ee/b001io
Background Music:
Slowly by Tokyo Music Walker | / user-356546060
Music promoted by www.free-stock...
Creative Commons / Attribution 3.0 Unported License (CC BY 3.0)
creativecommon...
An obvious note is that the Walrus Operator only appeared since Python 3.8, so if you have to work on older systems, it will not be backwards compatible...
backwards compatible code is retarded. why not just code on the lowest version you want to run it on? that way if it runs on your machine, it (likely) runs on all versions above
From my experience using python software, it is the forward compatibility you should care about.
@@werakoko thats what im saying
I like using modern syntax to bully my coworkers that keep using 3.7 for whatever reason.
Why doesn't regular assignment work? Works in Ruby where everything (including assignment) is an expression; and the if statement evaluates expressions.
Another nice example from the PEP with while:
while chunk := file.read(8192):
process(chunk)
You can't rewrite that without having to change the control flow.
thank you. will def use this
Sure you can.
while True:
chunk = file.read(8192)
if not chunk:
break
process(chunk)
This construct is called a Loop-and-a-half and very helpful sometimes. Using the assignment in the condition is a very common concept in C code and more concise. But for more complex loop setups than a simple assignment you want to use the long form instead of crunching 200 characters into the condition. The control flow is the same.
@@bultvidxxxix9973 you are using an extra control flow statement
What about:
chunk = file.read (8192)
while chunk:
process (chunk)
chunk = file.read (8192)
Wouldn't that have the same control flow?
@@sierravanriel6906 yes but it's not DRY. You have to remember to update the chunk size in two places (if you want to change it), and the loop body might be long.
Something worth noting about the walrus operator, is that it always "returns" the value of the variable, unlike a regular assignment operation (eg: x = 10), this is why it works inside stuff like an if statement or inside other operations.
In python, you have assignments, and expressions, you can assign an expression to something, but you cannot perform a normal assignment inside an expression because a normal assignment doesnt return anything.
assignments don’t return anything in python?!
As a C programmer, that's really weird! In C, just: if ((n = count_odds(data)) > 1) ...
@@UnlikelyToRemember Except that because it's so easy to accidentally use '=' instead of '==', lots of bugs are introduced this way. It's so common that the de facto usage pattern has become `if (CONST == myVar)` to throw a compiler error in the case of an accidental assignment operator use. This is why so many modern languages stopped allowing it, only to realize it is sometimes very useful, so introduced a much less error-prone syntax for it.
@@bloodgain Compilers have been warning about "if (a=b) ..." for at least 2 decades now. But, some people just aren't cut out to be programmers.
@@UnlikelyToRemember So, your option is to either turn off warnings for that or ignore them? Hmm. I prefer to deal with compiler warnings. But I guess some people just aren't cut out to be _good_ programmers.
I love that you added the "obvious" method which makes for a great explanation of when to choose what, i.e. readability. Great tutoring. Thank you! :=
Dude I'm a freshman taking APSCP, our teacher is teaching VIA python. I've picked up on it fast, but a lot of advanced stuff like this is hard for me (Especially since we're working on AP task). I really appreciate the tricks and tips you provide!
isn't the ap program java only for the exam........
@@snesmocha The AP test is psuedocode, Create PT is whatever you want
@@snesmocha I think AP CS Principles is mainly in Python, and I think it covers a more 'high-level' overview that you'd see closer to IT rather than CS (though tbf neither really cover all that much soooo). It's different than the CS A class which just covers Java (ughh...)
@@snesmocha No APSCP is in any language, including block based like scratch. I think APSCA might be java only though, not sure
@@Emily-fm7pt My school's teaching JS for APCSP, and AP CS A is in Java, so I think AP CS Principles is in any language, and I bet CS A is Java-only.
It can also avoid indentation. Before:
match1 = pattern1.match(data)
if match1:
result = match1.group(1)
else:
match2 = pattern2.match(data)
if match2:
result = match2.group(2)
else:
result = None
After:
if match1 := pattern1.match(data):
result = match1.group(1)
elif match2 := pattern2.match(data):
result = match2.group(2)
else:
result = None
Example from the PEP.
why u type match1 = pattern1.match(data) outside of clause but match2 = pattern2.match(data) inside the clause in the first one?
wow, this was an easy and straight to the point explanation, thank you!
Historical note from an old-timer:
We never thought to call it "the walrus operator" but . . .
Going back DECADES the := operator was used in Algol and derived languages (like Pascal) . . . for assignment statements.
I didn't know something like this was in Python. Very interesting. This is very similar to the "=" operator in C, except that can be used for assignment anywhere in an expression, including something that looks like Python's assignment statements. The problem with that is it's quite easy to accidentally turn the equality operator "==" into the assignment operator, especially in conditions, where it will cause an assignment and make the condition succeed when it shouldn't. It's good practice to use parentheses to make deliberate embedded assignments clear, and some compilers can detect if you don't. But I like this approach, of requiring you to write a different operator if you really mean to do this.
In C++17 you can declare variables in if and while as well:
if (int n = stuff()) {
stuff_with(n);
}
Python's := has annoyingly low precedence, so you often end up with lots of parentheses anyway.
As someone who works with JavaScript far more than Python, I was just thinking, "wait, isn't that just how assignment works anyway?" 😅
In C-derived languages, at least.
For me, the odd thing was the term "walrus operator", which I had never heard before. Took a second to figure out where the name came from.
@@TrueThanny Isn't python a C-derived language?
@@sonicsplasher In no way whatsoever is Python derived from C.
Have you ever written code in either one?
Anybody else remembers this as the standard assign statement from Pascal?
This is interesting to know and I appreciate how such syntactic sugars are useful. Also, I've encountered many situations where the use of such specific or unique syntax make reading the code more effort-full, which especially in teams and with team communication can slow development. Personally, if it can be done in a way which is faster to comprehend without major impacts to other aspects of the development cycle or to product maintenance, then that way is preferable.
Also, I cannot get the similarity of a C-syntax variable assignment inside a control structure's condition evaluation out of my head.
An important note:
Always surround it with parenthesis!
"if x:=y == 0:" isn't a syntax error, but it doesn't set x to y. It sets x to "y == 0".
Also "x = y = 0" is valid python that sets x and y to 0. That makes it look like "y = 0" evaluates to 0. But it doesn't evaluate to anything. You can't use a single equals in an if statement like in C.
if "y = 0" doesn't evaluate to anything, what would the value of x be in the statement "x = y = 0"?
Normally we think of 'evaluating' as getting the return value of an expression. However, in Python, assignments do not have return values (as opposed to languages like C, where a return value might be needed to verify an assignment succeeded). The assigned value of x will be 0, but neither of the statements "x = y = 0" and "y = 0" evaluate to anything. This is what the walrus operator is meant for, by the way -- it allows you to both make the assignment and evaluate the expression (it's actual name is the 'assignment expression operator').
this is why I love python. I don't actually use it because I don't have any reason to but it seems like such a useful language. I do c# and lua btw
i find it extremely annoying and costly to deal with no typing, making it so you are expected to implement every piece of code correctly together (no warnings) or else you get runtime errors; Also doing a lot of try/catches to validate user input, i mean, they call them exceptions yet everyone expects them and put them in handles...
though i've seen a lot of smart people being very skilled at this language, i simply don't get them, from experience i've come to love Typescript as a weakly typed scripting language
Fancy operators like this usually end up not transferable to other languages, and are extremely unreadable to other programmers who aren't used to this particular language. It's not worth sacrificing readability when it's only going to save a line or two.
I made the mistake of learning all the quirky syntactic sugars in JS/TS, and only ended up confusing the heck out those working with me. I'm never going to let that happen again. If you can't be sure you everyone who works with you has the same dedication to python and niche python features, just use the standard syntax.
I mean, from what it looks like to me, the walrus operator isn't only for reducing lines of code, but also can be used for optimizing the code and reducing redundancies in calculations and such. It may make the code more difficult to read in a collaborative setting, but may still be useful for optimizing performance.
I might just be talking out of my ass though, I just started learning to code a month ago at the end of an unrelated bachelor's degree. I don't really know how things work in the real world.
@@zedeps you can still optimize while not sacrificing readability, maybe for lowering memory storage if the n:= is erased right after the comparison.
I was thinking.. You can just assign the return value to a variable first, then use it wherever necessary.
n = function(array)
if n > 1:
# process
Other than aesthetics.. does this serve any other purpose?
I really like these style of `if` predicates and did not know about this operator.
Thanks
The walrus operator is an absolute gem for one liner codes. It's been a nightmare for me to work without it because I'm forced to use Python 3.6 ;-;
I don't really need Python tutorials right now. This was recommended after I looked at C# tutorials, of which I am currently expanding my knowledge. It just interested me because I had never heard the walrus operator before.
I have to say that the clarity, conciseness, and simplicity of the explanation is exactly what I wish I could find in the videos I've been looking for, but unable to find so far, regarding C#. This is an example of what people want in these types of videos done perfectly.
Guess it makes sense to use this symbol, as := is also used in mathematics to denote assignment, e.g.:
"Let 2 := 1 + 1 denote the successor to 1.".
Assignment is already "=" as in any modern programming language.
And what you wrote there is grammatically really wonky. Usually one would write "Let 2 be 1+1". Or just "2:=1+1". Because in mathematics ":=" is not a walrus operator.
Immense disrespect to the case where you have only one odd number.
Facts
I think I'm more surprised you can make lists like that than learning about this operator
It's a pretty cool way of doing it, and It's called list comprehension in the case of lists. There's also tuple comprehension, dictionary comprehension and set comprehension.
It's a neat way to create iterables in one line instead of many.
Ya, and list comprehensions can be nested in each other:
transpose = [[row[i] for row in matrix] for i in range(len(matrix))]
So this does the same as the = in almost any other language? 😱
No, it does the same as = does in python too.
It specifically allows you to make in-line assignments in places you otherwise wouldn't.
It's nearly useless in actual code to be honest, because it's cleaner to put the equation 1 line up and simply call the variable instead of using := which in this case is python specific
@@dominat0r3600 Except that that's exactly what they're saying... "= in other languages" means that = can be used in an expression, while Python forbids this.
@@dominat0r3600 You've apparently never seen C code.
I used to do this a lot in C, but forgot that it exists in Python so thanks for reminding me.
Seeing as you had to make a video to explain what it does I would argue assigning to the variable is more easily understood. Good video.
Then the variable is in a larger scope than necessary. When refactoring and testing you might accidentally use it which can hide a bug.
@@nicktreleaven4119 make smaller functions in that case to limit the scope. Can't see myself ever using walrus operator, sry.
@@cleverclover7 it's still more bug prone in practice. Best practice is to keep variable scopes small. This helps. In more complex code it also helps to simplify nesting (see my top level reply if interested).
Thank god for making this short. Other videos are like 12 minutes to talk about one f'ing operator
The text size in the video thumbnail was nice, but in the video was so tiby I couldn't read it.
exactly what i was looking for, thanks
In languages that support expression assignment it would be much easier. Python took the shortcut and hard coded many things to be multi line, so this is the price we have to pay to write concise code.
Can you give an example of expression assignment?
@@Sarmachus
common patterns that I seen in js/typescript/c
//javascript/typescript
let result: null|Result;
if(result = someOperation()){//returns instance of Result or null, which is falseish
//do something with result, now that you know it's not null
}
//c
data_type* some_ptr;
if(some_ptr = get_obj()){//returns NULL or pointer to data_type
//do something with some_ptr, now that you know it's not NULL.
}
```
I see. Makes sense, though I don't see how it is significantly different from := in python. It's all syntax in the end.
I do like having the variable declared ahead of time though.
@@Sarmachus Yeah, it's not that of a big deal indeed since it's just a single character. But I do think that it is kind of confusing because := is used as declaration in languages like go, but not for assignment. But in python := and = do essentially the same things if my understanding is correct.
But overall I love this new feature now that I can use the same conditional assignment patterns that I see in other languages.
For while statements it can be great !
I feel like a lot of python is about writing fewer, more dense lines of code. And I honestly feel like its really bad practice in many cases. For this example, I'd assign the count to a variable, naming it in a descriptive way, and then perform the if > print block. In a few situations python has some really cool stuff that is human readable and dense, like 'o for o in data if 0%2==1', which I really like about the language, but so many of these things can be misused. At least from this example I can't see any use case for this operator outside of code golf.
Maybe it's just me, but I like to write more lines, have each line be clear in its purpose, and when things get too long I separate it into a function so that it stays a single line which now has a function name that describes the process. It's simple self-documenting code, which 'pythonic' solutions often end up being the exact opposite of.
This sort of control flow is actually much more common and considered "good practice" in other languages albeit with slightly different syntax. Rust and Swift implement this feature with the "if.. let" syntax and tends to be preferred due to the added benefit of not needing to store the state of the return value outside of conditional scope. This last point becomes more apparent when dealing with multiple return types as now instead of having multiple variables possibly clashing in the outside namespace, they are appropriately initialized within the intended scope.
In this case, I wouldn't even include the "==1" in that odd check since 1 is already truthy
You can do this in other languages (like C) too; it's *heavily* frowned upon because it violates the principle that one SLOC should do exactly one thing in order to prevent any unintended behaviors that go unnoticed by combining operations.
Interesting that Python added that. A few other languages already did things this way, like both Go and Pascal. I liked it so much that I copied that for my own language.
I like what i saw on your channel so far.
I suggest video about lambda functions. Especially in list comprehintion.
For me, at was always something strange, what i forget every time i learn it.
Actually needed this earlier today.
Maybe n:= can be use to encapsule some private calculation. I don't know.
can you do a video on decorators please? good content as always
Yes, check out the video I posted before this one!
Noooo! You need to fix that silly missing space! Aaaaaaaaaa
My god I've been missing out on this one, thank you very much
fascinating, I have wondered if something like this exists in python, since it does in e.g. Swift and theoretically Rust
I'm really going to have to look back on the discussion on this operator because I just don't see the point.
Good content, but I wish the font was larger so that I can read it from my phone screen without going full screen.
Stop watching videos on a tiny screen then complaining about the consequences of your choice.
@@TrueThanny If I see a video on RUclips that I want to watch, and I'm on mobile, I'm gonna watch it on mobile, not wait until I'm back at my desktop. Otherwise, why would I be on the RUclips app on my phone if I didn't want to watch videos?
@@ryankhart Fine, but you need to accept the limitations that result from your choice, rather than demand the video be made worse for everyone viewing it on a proper display.
@@TrueThanny Why would the video be made worse for everyone. It's harder to make the video for the person recording because they have to pay more attention to making sure the relevant text is on screen at any given time. Larger text is worse for multitasking, for sure. But in a video format, there's no need for multitasking. It's a linear format.
Plus, think of the missed opportunity not using a large font size and a competing channel comes along and has a large font size stealing viewership away from your channel.
Two weeks ago?
Didn't I watch this a year ago?
(Is this a reupload)
nice way to explain is such a easy manner
I was searching for that, thank you
You’ve gotten yourself a new sub
Welcome to another addition of "Catching up to the mess that is JavaScript" ep.4
Oh look! Python is finally catching up with C, C++, Java, etc. :-D
Like the theme, which one is it? :)
PEP20, the zen of python: "There should be one-- and preferably only one --obvious way to do it."
Yeah. What a lie.
I completely don't get why this feature is necessary. I don't think it is a good idea to keep making changes to a language without there being some significant value to it, In other words, only make the change if the value of the change exceeds the problems caused by an increasingly changing language. Furthermore, to do something link that in C (assignments within if conditions) would be considered a bad practice and source of bugs. From what I see on RUclips, Python programmers seem to love these continuous little tweaks, but I just don't see the value.
The exact opposite is true.
Lots of Python programmers hated this addition and it was probably made to appease people coming from C or other languages in which assingments return their values by default.
Walrus is similar to C's arrow notation - it allows you to write less code
Nice!
Looks at the thumbnail
"It's the define operator!"
Remembers that definitions already work by =
"Oh..."
You know, programming languages should start using := to assign new values and = to check them
Seems usefull within listcomprehensions
I can't read what you're typing, there's this humongous "includes paid promotion >" button on mobile covering your code.
Can you please share your extensions in vs code and the theme? 😊
Can you please make a tutorial on how to create an exe for the python project? I tried pyInstaller but antivirus detects my app as a trojan
idk man i'm just listening to the first second of "what is the walrus" and thinking about lennon
Omg i had no idea this existed tysm
Time isnt really a good way to measure performance as it varies by cpu and computer and interpreter
its quite useful if you want to do things in minimal lines, so like:
n=1
while True:
print(n:=n+1)
n=1
while True:
print(n+=1)
that works the same, no?
@@davidtejuosho587 no actually, that gives a syntax error, as it only results in the fact it has been stord, and not any values, for sure not n
im pretty sure that everything you called a second was a millisecond
Can someone tell me why my VS code doesn't show the result directly but show extra details of the folder and stuff before giving the output ?
So... it saves a single line.
and (seemingly) doubles performance…
oh ok now I know what im doing today
Is the variable only in scope inside the condition if this is used? If not, then it looks like just a typing saving thing, rather than anything actually useful.
what color scheme are you using for vscode
Very informative video, btw which theme is it?
Good to know - I start to type something like this in python and then realize it doesn't exist. Now it does!
Nice video what theme is that ?
Good explanation, but I see no reason to use this operator. If you ever need to use this you may as well use ternaries.
I also checked with c++ that the evaluation of an assignment expression returns the variable. This means an equals sign here would work just as well. It also returns the pointers of strings so those work too.
That's C++, this is Python. In Python, the evaluation of an assignment does not return the variable. "if (x = y) > 0:" is a syntax error, but "if (x := y) > 0:" is not
And how does a terniary operator work in its place?
You'd still have to add another line to save the result to a variable or call it twice in the terniary statement. And with an if statement, you can run as much code as you want in the body. A terniary statement just lets you run 1 expression in the if and 1 in the else sections.
@@Spencer-wc6ew I thought python was about usability, why do they not let assignments return anything?
I agree, why cant people just use normal variables and name them properly. This just makes you use a one character variable which isn't helpful, or write a long if statement which is also a bad practice. Write clean code not cool code. But its cool to know about ig. Python could just invest some more efforts in shipping useful tools and no code-shorteners (Like proper typing/linting support)
@@goosydev Well we always have rust
That's a great name for it.
As a mobile viewer, you really using fullscreen capture to show around 20% of the screen?😅 just a tip that fontsize could be greater!
Why should the presentation be marred to accommodate someone who chose to watch the video on a tiny screen?
@@TrueThanny as a frequent mobileviewer - it is just a convenience, not to critisize content itself - and still makes video more approachable when seeing clearly what is changing and when (if not excessive animations etc. Used). So its always better from viewers perspective to have clear view of the thing you are supposed to show - podcasts are different thing.
@@TrueThanny and to be clear - while intent is good, and content is flawless - execution itself can be improved.
@@Maiska123 The execution is as good as it can be. Zooming in on the text would be _worse_ execution. You aren't writing Python code on your phone. Nobody does that unless it's an emergency and they're not near a proper computer.
This video is for people writing Python code for one reason or another. It's suitable for viewing on a proper computer, not for somebody killing time by watching videos on a device that's poorly suited to that task.
Additional use but also a potential pitfall is that the statement still evaluated lazily.
E.g. if I only wanted to print the data if its length is even:
if len(data)%2==0 and (n:=count_odds(data) > 1):
print(f"{n} odds")
So in this example we could easily skip the if statement without running count_odds.
The equally fast alternative would be:
if len(data)%2==0:
n =count_odds(data):
if n > 1:
print(f"{n} odds")
So here, it does not only save a line, but even a level of nestings.
You have to be careful tho as you can not be sure that n is defined afterwards, as count_odds did not run. So this should only be used if you use the variable within the loop but not after.
wow that was amazing !
You've somehow missed all the important details, namely:
- when the operator was added
- the 'while' use case
- clearly stating its precedence
- the scope of the variable it defines
And you focused on 'how not to call a function twice', which is arguably not an issue most people would have?
It is genuinely a better use of time to read the docs than to watch this video.
Very cool, but I'd still use a variable to store the value, seems more familiar and it's pretty self explanatory
It does assign it to a variable.
@@InigoPhentoya Yes, i know, I meant explicitly assigning it to a variable like what he did at the end of the video
So it’s the like the assignment in proper languages? ;)
Do more videos for beginners
Not relevant, but why add comments for t1 (Start time) and t2 (End time) instead of just calling the variables startTime and endTime?
Thank you! (although i prefer snake case...)
Please put spaces left and right of your mathematical operators. Makes any code so much more readable
bro theme?
I now understand how it works, but I'm not convinced it's useful. Seems like it makes code harder to read
It is nice explanation
in php you can just use "=", i don't get why the extra ":"
Excellent ❤
The walrus operator honestly seems like Perl creep. And I don't mean that in a good way. It means the code gets less legible, unless you know the fnnnthy small squiggles. For that reason it's pretty obvious that declaring your variables before the computation is a good practise, especially in a language that was built to be more legible in the first place.
But why does it have to be a new operator? Other languages can just do this with the assignment operator (=)
And BASIC used = for both assignment and equality:
REM Compare X = 0 and assign result to V.
V = X = 0
And PL/I is infamous for not having reserved keywords:
IF IF = THEN THEN THEN = ELSE ELSE ELSE = IF
Why did C and so many other languages choose == for equality?
or
Why did Pascal choose := for assignment?
or
Why do programming languages reserve keywords?
The answer is simple: because that's just how they decided to do it.
Yeah and it's an endless motor of bugs.
is it just me seeing an eggplant in :=
Your video is more useful than the walrus operator!
I was searching for this
Why doesn't it just use regular =?
Python assignments do not have return values.
@@InigoPhentoya then why not make the regular python assignments return values instead of making a new assignment operator that does return a value?
@@misaalanshori It is much, much easier to add an operator that does some new thing than to change something fundamental about an existing thing, especially in the context of backwards compatibility.
@@InigoPhentoya would making the assignment operator return a value really effect backwards compatibility? I feel like since it wasn't a feature before then no one would be using it to get a value, in fact using an assignment as a value gives a syntax error, so i feel like there would be no program that uses the assignment operator in this way. So adding this feature shouldn't break existing code.
Can you share an example where making this a feature would break something? (I haven't done any research on this tbh)
@@misaalanshori
Because that would completely break earlier code.
E.g. a=b=1 asigns both a and b the value of 1 as it stands. If assignments had return values, you'd have to change other parts of the language.
what font is this?
No question asked, I can see very clearly why it's called a "walrus" operator :D
Crazy python to use ALGOL assignment operator, which you call the walrus operator, for assignment in an expression and C style for statements. I'm guessing this has to do with adding a feature to the language which doesn't affect the parser too much as I can't imagine it would break backwards compatibility to just add support for assignments in statements.
great videos
Microseconds?
Using time.time() instead of time.perf_counter() 😢
What theme is he using?
Synthwave’84
Amazing