The walrus operator := and assignment expressions, PEP 572, was opposed by majority of Python core developers, and led Guido van Rossum to step down from BDFL role. Here's the outline for the video: 0:00 - Walrus operator 1:26 - Use cases 3:33 - Criticisms 5:59 - Guido van Rossum
Why doesn't Python do as other languages do... assignment also return the assigned value, so no : would be required. As in C: if (a = b) // true as long as b is different from false/null This is quite a stupidity from Python devs, like the indentation to determine blocks of code, which gets annihilated by different IDEs in different OSes working with source control, and is therefore difficult to use in corporate environment.
@@marsovac The canonical reason is that returning the assigned value is prone to one specific kind of error, when you say this: if a = b: ... but you meant to say this: if a == b: ... In the first version, a will always equal b because it is assigned the value in b, and if b is not False, the contents of the if statement will always run. This was a really common error in C, and Python made the = operator non-valued to specifically fix it. FWIW, I like the semantics of := and look forward to using it. Some other languages added new constructs (e.g. if-let in Clojure) to specifically enable cases similar to this.
@@asyntactic you have a warning for that in at least some C compilers. Here is what you get with clang: "using the result of an assignment as a condition without parentheses [-Wparentheses]" While in other languages like C# that is not a valid if statement at all since it does not return boolean, compilers are intelligent nowadays. I don't remember if I had an error caused by that in the last 10 years of coding. If Python happens to have such issues then there are more fundamental problems in the language itself. Like for example "do not treat anything/everything as boolean" would have solved this specific problem. If you want to be explicit about the syntax there is nothing better than "null != (a=b)" but to introduce more interpunction around assignment operators is clear as fuck, especially when it does something else than what other languages use it for.. Don't get me wrong. I'm not trying to piss on python, I would in fact like to use it, there are nice features for working with data and data sets, but sure there are some weird decisions taken that solve nothing and introduce new problems, which make it not good enough for sharing code across teams with different environments on the same code repository. The one time we tried some guy destroyed code files by using nano indentation not matching what others used in VSCode. That problem was created by what? Trying to remove braces from code? And the choice to not use returning the assigned value solves what? A compiler lack of common sense?
@@marsovac Yes, modern compilers do that. I've actually been bitten by this problem in C, but that was more than 15 years ago. The "assignment isn't an expression" convention in Python also originated over 20 years ago, back when this was maybe a more common problem. I don't see it as fundamental language issue - many languages have their own quirky definitions of truthiness. Instead, it's a culture issue. The = vs. == distinction is one of the first things introduced in the tutorial when new users first start with Python, so it's become deeply imbedded in the culture of the Python community. I suspect the anger that Guido provoked was more ideological in nature than technical. The original language designer thought he could change his mind - joke's on him! The fact is this isn't a matter of right or wrong. Programming languages have their own idioms, and you get used to their particular way of doing things. Python isn't my favorite language, but I've used it for years, and it's turned out to be very valuable.
I highly doubt this is the reason why he stepped down. I can only imagine the levels of forum drama and hate that this "issue" arouse... And probably *that* is more related to him leaving.
@@cuentadeyoutube5903 He actually stepped down so that Python could cleanly transition to a model where it didn't require him as a BDFL in order to operate. It was planned for a while. He found capable successors and helped reshape the governance structure before stepping down. It just so happens there was some controversy around a language feature around the same time, but there was lots of controversy with prior PEPS, as is the nature of all open-source language development.
Python has been a solid programming language for decades. You can pretty much stop developing it now. And just focus on the issues arise from new OSes. The core python is super solid. And Pypi packages are solid too. A language like this can guide itself on its own.
@@NoName-to5xl Only when necessary. I have been writing python for almost 3 years and never used it. It is useful for things like numpy where addition on objects is very common.
The := operator should not be criticized for its similarity to the = operator in C. In C, the = operator is error prone because occasionally the == operator is mistyped as =. If the left side is assignable, it compiles--as it is valid syntax--hiding the error until run-time. When used properly, it still provides the same elegance you mention. The := operator would not have this issue, since the == operator should not be mistyped as :=.
People use the variable on the right hand side and Constant on the left side like (0 == *p) to avoid this issue and compiler would promptly throw an error if one of the = sign is missed. But if both sides are variables, the compiler will not be able to detect it.
Error prone? That is if you are compiling with what? A Pocket calculator gcc from 1990? Clang gives: Warning "using the result of an assignment as a condition without parentheses [-Wparentheses]". I'm sure a modern gcc has a similar warning for the assignment in the if without proper syntax. I prefer code that is simple and the compiler that aids me in not making mistakes. The approach of Python is "you are a dumbfuck, let us decide how you write, so we don't need to write a helpful compiler".
You can easily find a C style guide that recommends using yoda conditions to prevent errors as such. I find yoda conditions pretty neat and your code is not error prone at the same time.
Every time I hear about Python drama, I am reminded that I am too freakin' old for this crap. Have I been bitten by the = vs == typo, sure, all the time. Do I think it's worth implementing "walrus" syntax to avoid that error ? Sure, go right ahead and make my life easier. This doesn't even break legacy code, so it's a freebie in my book. But do I think it should have been such a huge source of drama ? Hell no. If people are butthurt because this breaks away from C conventions, to those people I say "go use C then". A skilled programmer should use the best tools available to them, not lament the fact that a screwdriver is not a drill press. Python is supposed to be an easy and versatile scripting language, and this kind of syntactic sugar is one of the many ways in which it fulfills that mandate.
the walrus is not really supposed to avoid misusing = or ==, though it's a shorthand for reusing the assigned value in some other expression (that is not also an assignment, you could always reuse assigned values to assign more variables e.g. `a = b = c = 10`)
even though walrus operator break anything, it means one more weird syntax to learn. you can do what walrus operator does without looking scary to newcomers there is a simpler-looking and easier to understand way of doing what walrus operator does, which is why people objected to it, considering how python makes sure people cant abuse operators to obfuscate code. everything must stay in its simplest form, yet walrus operator is a redundant feature. it provides same as an existing method, and that requires people to learn more.
Whoa, I never considered that. I think it's still more convenient to just write the variable again in the last line, because then it's easier to enable/disable it (without having to remove the parentheses). And easier to move the code around, when you are exploring commands to later package into a function pipeline. Maybe if someone wrote a plugin for vs code/jupyterlab to switch between = and (:=) with one shortcut.
I think it's still important to point out that after Guido stepped down as BDFL the core developers voted to create an elected steering council of I think 5 people to together take up his role in the future and Guido was voted as one of the members. The quote at the end makes it sound like he abandoned the core devs and left them in chaos ^^ I'm not up to date on the current situation but I believe the members are voted in for a fixed period of time or something and Guido said he won't be a member the next time (or he might already not be anymore) but it has been a while so I might be misremembering or this might be out of date info.
They're two opposing programming language philosophies that are applied to many many languages (think C++ vs. Java). And I think the Python's phrasing of the principle was actually a reference to the Pearl's one.
@@leogama3422 I think for most things, the philosophy is either: A. Hack it yourself, (C, PERL) B. We have a comprehensive standard library, but you can still Hack it yourself(C++) and C. Use this one specific paradigm and everything is already done for you in a way that you have little control over (Java, python, etc) The latter can be useful in a lot of cases, and I'm not saying that's necessarily bad to use
The actual Perl community expression is "There Is More Than One Way To Do It", which has the acronym TIMTOWTDI, pronounced (and sometimes personified) as "Tim Toady".
To answer a polite question and avoid triggering the easily distracted further, I will clarify c# has a similar operator i use, and I thought recalled Java having something like that when I was studying it. I could easily be mistaken. Thanks to those of you who realized the point was to comment the operater seemed useful.
I think we will have to see how it ends up used in practice. My main concern is how it might impact readability. It's not something that should be sacrificed for brevity of the code.
@crazywayne yeah, I agree with the concern about feature creep, but I think this one is worth it. We add a bit of complexity of course, but I feel like the complexity we lose by not having extra control structures/multiple comprehensions is well worth it. In these cases I've always felt something I rarely feel when programming in Python, and that was that I was having to work around limitations of the language. There may now be two obvious ways to do some things, but there was never an obvious way to do this, at least if you've been spoiled by Python sufficiently to expect better.
@@thomaskolar90 It saves you some lines which is totally useless. The main problem with compact code is that you need more brain power to read it. When you have 3 lines of code where every line do one thing you can read it easily, when you encounter a line with the walrus operator you have to evaluate that line in your head. It is a calculation, an assignment, and a condition check in one.
The Walrus operator is mostly common in languages like Go Lang to initiate a variable, and then if you want to change the value of the variable later you use the equal sign
That's like the opposite of intuitive. I remember go had something like it, and for a second thought go was amazing. It's actually OCaml that does it right.
Personally, I'm not sure how I feel about this. I may not code in Python, but I think lambda expressions in java would be somewhat comparable to this. Not in functionality, but in similarity to the effect on code. Whenever I find code written by a previous team on my project, they abused the shit out of lambda expressions, just to "reduce lines" of code. They had multiple nesting lambdas together. Sure it made it 'smaller', but it also made the code absolutely hell to read. A for loop would have been bigger, but has greater readability potential. But the main issue is that they didn't use lambdas very well. They didn't use the right tool for the job, and used it just for the sake of doing it. So the walrus operator reminds me of this. I probably wouldn't use it, but I don't think it should be a problem that it exists in the code. Many who opposed it probably won't use it. Those who are knowledgeable will probably use it right. And those who don't use it right will pay the price.... hopefully. I guess that's where some of the concern lies. When other devs have to clean up someone else's mess. Side note: thanks Lex for showing this. I had seen/used this operator when making AutoHotKey scripts, but didn't know what it was called lol.
Or you could just learn to become familiar with the lambda syntax and embrace the concision rather than replacing it with more verbose things that you pesonally have more experience with and are more familiar with.
@@jeremykothe2847 I know how to read the lambda syntax. I'm totally fine with simple uses of it. But my point is that it a tool shouldn't be used incorrectly, and the code shouldn't become any less readable. I can't totally explain it without showing you the code, but the way they used it was like a "bandaid patch" to a flaw in the overall code design.
I agree, but this is the case for so many things in programming. A lot op people use OOP just for the sake of using OOP, even if it makes the code much more complicated than it should be. A programming language and all the functionalities it offers are just a tool to get a job done, and just like in real life, you need to select the right tool for a job. Just because people might use a hammer to put a screw into something doesn't mean there shouldn't be a hammer
I wish Guido was more like Torvalds and had just humiliated all the assholes who complained about the := operator and had remained in charge. But I guess this is not for everyone. I would've probably done just like Guido, but I wish I was able to be like Torvalds.
@@johannakunze3300 was just about to say this. the biggest thing i learned from peterson was the patterns, like chaos and order, that you can find repeated everywhere you look
I personally like the walrus operator, and don't really buy the criticisms. "Can be used just for assignment (=), so confusing to beginners" "There should be only one obvious way to do it" Not an issue since it was accepted that := can't appear on a line by itself without (); the obvious way to do assignment is with = "This is how the = operator worked in C and it was error-prone" This was only error-prone in C because it was easy to mistype == as = (a common mistake for beginners to programming, since they expect = to have the same meaning as in mathematics), so that you would end up assigning in an if-check `if (x = 42)` instead of testing for equality; I don't think it's as easy to confuse := for = (you're not using := unless you know what it does). "Simple is better than complex; Adds complexity in the name of reducing whitespace" This vague objection can be said of basically any new language feature/abstraction; list comprehension, for loops, even functions; they all add complexity in the name of reducing whitespace. Doesn't mean they're not worth it. Be more specific about why the added complexity of the walrus operator (which is little IMO; it took
@William Baric "The idea that an assignment returns a value is not intuitive. Beginners will have a hard time grasping the concept." True, but Python isn't just a toy language for noobs; one of the great things about Python is that it's simple enough for beginners to learn it easily, but has more advanced features for more experienced developers (e.g. list comprehension). Beginners can stick to easy things they know, and when/if they're ready they can check out more niche features like the walrus operator. "More importantly, packing instructions always make the code less readable" Debatable; sometimes it does, sometimes it doesn't. For example, here's some code from one of my uni assignments, where we had to read from a database with sqlite3. The starter code looked something like this: ``` cur.execute('SELECT title, year FROM movies') while True: t = cur.fetchone() if t == None: break title, year = t print(f'{title} was made in {year}') ``` I rewrote the code with the walrus operator like so: ``` cur.execute('SELECT title, year FROM movies') while t := cur.fetchone(): title, year = t print(f'{title} was made in {year}') ``` Which version is more readable, first or second? I'll admit readability is subjective, I won't criticize anyone who answers "first", but to me the second version is more readable. Not only is it shorter, but it better conveys the intent of how long we're looping for (better than while-True-break kludge).
@William Baric Oh I agree. while-True-break is an ugly technique and you should normally use better variable names. The point I was just trying to demonstrate with this small (but real) example is a good use case for the walrus operator; without the walrus operator, Python programmers would have no other choice but to use the while-True-break technique. Actually, I suppose another way to write the code would be to repeat the looping condition before the loop, something like this: ``` cur.execute('SELECT title, year FROM movies') t = cur.fetchone() while t != None: title, year = t print(f'{title} was made in {year}') t = cur.fetchone() ``` But I dislike this approach because `t = cur.fetchone()` is repeated twice, and the scope of `t` is now bigger than it needs to be, reducing clarity to me (is `t` only supposed to be used inside the while loop, or did the programmer intend to use it afterwards as well? With the walrus-operator-approach, the answer is obviously "only inside the while loop", but in this approach it's less clear). The point I'm trying to make is that this is a case where the walrus-operator-approach is more readable than any other approach (assuming they're all using the same variable names ofc).
@@saeedbaig4249 I'm totally with you on these examples. I've run into this exact situation countless times, and sometimes I've used the while True/break approach and sometimes I've used the duplicate assignment line. I've always lamented that I can't just do what the walrus operator allows. So to me, it just provides a simple solution for these awkward situations, and does so in an unobtrusive way.
In the eternal words of Terry A. Davis on a new construct he invented in HolyC (a derivative form of C): "This is voodoo. But the question is, is this too much voodoo? Is this enough for HolyC to last another 100 years? ... This right here, is the hardest question in programming."
Ah yes, that was with a very cool feature for the language. Something to do with switch statements I believe? But, yeah, I think the Walrus operator is indeed *too much* voodoo. Cool feature, but ultimately needless and more trouble than it is worth
I have never used this but, with my little programming experience I have: I think it looks kinda neat however I feel like the code was more complex using it. If you just do the examples the "old" way it is pretty clear what is happening. However if you use this operator I feel like the code is way more confusing to read and just to understand what exactly is happening
I feel like this too. I think it's because I'm not technically able to understand this type of advanced code yet. But, wherever I see code I don't understand is a opportunity to look into it and that's a great chance to learn why things are the way they are in a certain context.
Exactly. Yes, with walrus op you can write more condensed code. But, it would also become less readable, by the simple fact that you stick more operations in one line of code. I thought since the times of C, which allowed many neat tricks to write "elegant" condensed code most by today have realized that easy human readability must come first. But not for previous "head of Python" apparently.
Right? I mean, unless you don't have a fucking job so you can shittalk on democracy with faulty comparisons from the programming world, often you will have to show your code to someone, and making it readable is very important then. And from what I understand your code will not even be faster.
I've used the return of = in c++ a lot and always thought it was a great feature and how = should always be. The ++ and -- operators also return their result in place and so do +, -, /, *, and % at least in c++. I don't know why people got so worked up over it still, I feel that many languages have sort of weird choices and that you just memorize them and move on to use them in the future. Also, I'm glad you mentioned the multiple initialization feature because the returning of the value by = is what normally makes that possible in other languages while python implemented it for only that specific case which people were happy with.
A project like this which doesn't need to be represented by a democracy, because it is not meant to represent everybody. In these kinds of projects, it's often beneficial to have someone break through stalemates and say "this is what needs to be done". Unfortunately in the real world, we do need democracies to represent everybody for governance. Otherwise we end up with situations where leaders inherit powers long past their ability to lead. Plus morally you want a form of government that is accountable to everybody
I think it is even in this project important and good that people called him out on his bullshit. Instead of focusing on maybe making Python easier accessible or faster than it already is, he wastes his time on a notation that doesn't change anything on speed, only makes your code two lines shorter at a time, and makes Python less accessible - if someone uses the walrus operator and decides to share his code online, beginners will be blown away by the large amount of stuff they don't understand; without such "synonyms" in language, it will become understandable for everyone. It is just the equivalent of using fancy words when there are much simpler alternatives; it confuses beginners and scares them off unnecessarily.
FYI, R actually allows the use of = as the assignment operation. In fact within mutate in tidyverse world, you use it extensively to create columns in matrix like objects called data frames. We tend towards the usage of the arrow -> in many cases now. But there is no where in the language where you can't entirely replace an arrow with an equals sign. Also like most languages we always use double equals, == as a check for equivalence
And the data.table package uses the (defined in the language/parser but unused?) walrus operator for "column assignments" in its expressions! (edit: just sow your second comment...)
@@leogama3422 great minds :) AFAIK it's actually defined internal to data table as Matt Dowles 'invention'. A little like the pipe %>% is in magrittr, though in that case most of tidyverse imports it from there, so it can feel like it's part of the parser as well :)
I heard of the drama regarding this, but I haven't actually using this feature at all, despite having already used Python for many years. The code snippet provided as an example in this video seems confusing and uncomfortable to me, I would much prefer the one without it. However, at the same time, I am aware of my bias for the tendency of staying in comfort zone. I still remembered when I was first learning C, how confusing the expression "for (int i = 0; i < n; i++) {...}" was, which is equivalent to "int i; i = 0; while (i < n) {...i++;seamlesslysyntacticalespecially when there are more than one thing happened in a single expression. For this reason, I can relate to Guido for his decision. Programming language is a tool, and it should be designed in a way to let user focus on the problem to solve, rather than language feature itself. The good thing is that you always have the option to choose whether or not to use that feature, and write the code in the way that is most comfortable with.
they should've done something similar to Go's approach. where you could write `if x := 10; x != 10 { // do something }` where the first is an assignment statement and the second is a comparison expression. in python it would look something like this `if x = 10; x != 10: #...`
Thanks Lex for this video, which is a nice side car tangent to the topic that you brought up toward the end of #6. Seems the elements of the Zen covered to some degree Guido's resistance to the operator, along with your Criticisms slide, which I'm assuming also matched Guido's thoughts on the matter. I'm not sure though if I understood from the video, the other side, meaning why those fighting for PEP 572 dug their heels in on it. Why they thought that Python was worse or hobbled without it. And why they felt Guido was wrong. Also, while I'm relatively new to Python, I noticed when you "import this" to access the Zen statements, the "one and only one" sentence has been changed to these two: "There should be one-- and preferably only one --obvious way to do it." and "Although that way may not be obvious at first unless you're Dutch." Even if that was done in jest, it's disappointing the lack of professional courtesy in its tone.
If you have chained assignments then I don't understand why you'd even need a separate operator. It wasn't that bad in C and it's far from python's biggest problem tbh. 😅
I would have thought the problem in C was that something like "if (x = 5)" which should have been "if (x == 5)", but the walrus wouldn't have that issue because := != ==. Ironically c++17 actually made declarations in the if statement easier so now you can do "if (int x = myFunc(); x > 5)".
@@sciencecompliance235 imho production code should be dumb clean. if few months down the line you need to re-read your (or someone's) code and you (someone) needs to apply extra efforts (parse though syntax sugar) to understand what's going then such shenangigans have negative added value. // hello uncle bob; > How do you feel about list comprehensions? What about decorators? it depends how complicated /these things are ... on walrus - just the fact that you can assign value to a variable while evaluating expression in if / else is creepy.. recipe for disastrous bugs. there is a good metric on the quality of the code - "number of wtf per minute", so imho walrus will be a top contributor ^^ all this above is just my personal opinion formed from experience. i might be wrong.
@@nsd1169 Yes! Your first paragraph - Yes! Your first sentence, which is worth repeating: "imho production code should be dumb clean." - Yes!! People who pay for code will rue the introduction of the walrus operator. If they're sensible, production coders will eschew it, and if the walrus operator is used widely and almost certainly mysteriously, Python's utility and consequent use in production will be diminished.
Just a little note about mathematics and the "=" and ":=" signs: Mathematically, when you write "c=42" and "f(x)=42", the statement is actually an evaluation of a logical statement with a binary operator "=", and two constants in the first case, and a function with a vairable in the second case. It is customary to assume that the expression "c=42" means that this evaluation is *true* so that the two constant values are interchangable. It is not an assignment procedure. On the other hand, although the ":=" isn't singularly defined, I have seen it used in mathematical logic as a way to define a value as, in such a way that the statment "c:=42" will guarantee that the evaluation of "c=42" will be *true* . This resembles the usage in programming a lot more closely in my opinion.
That is not accurate. Mathematically, the comment above is accurate when describing "="; however, it incorrectly defines ":=". "=", as in "c=42", is a second order relation, which means it takes in two terms and outputs true or false; whereas, ":=", read as "is defined as", functions similarly to macros in C, where for the rest of the document, replacement is used. If the statement "c:=42" is stated, then in any future statement, whenever "c" is used, it actually means just a simple replacement with "42." For example, if "c:=42" is stated, then the formula "c=10" would be replaced by "42=10". The only reason for the use of ":=" is for convenience of writing, so that a really long formula or term can be replaced with a simpler one. Just like with C macros, one can also use ":=" with arguments, if "f(x):=x+1" is used, it also would replace "f(c)" with "c+1" or "f(20x+4)" with "20x+4+1".
"leaders have to make decisions. we need leaders" You frame a gray issue binary. We need competent leaders + we need competent citizens + we need to be lucky to face issues with clear resolution. #dunbarnumber
True that, and in government democracy has proven the only way to keep a fresh set of leaders coming in who have a chance at proving their competencies. Sometimes we got unlucky, and maybe right now we need to rejuvenate what democracy means as things become stale, but overall we need democracies in government to force out those who will rest on their laurels (or worse, their parents parents parents laurels)
@@MsJeffreyF Democracy is doing worse and worse today. Parties give citizens money for free just to be reelected which is bad for the economy. Other countries manipulate citizens during elections to make the person who will be the most convenient for them win. Democracy was working for a while but now it's not :/
@@Laszer271 I agree democracy is doing poorly in a lot of the world today, although for different reasons. Parties giving mega donors more money, contracts, etc I do agree is bad. I think the problem is that money influences the democracy too much. For it to work better, each person should have a single vote regardless of wealth. Which would mean no more lobbying in America I think there's other neat things we could try with democracy too, like instead of everyone being elected, have like 10% of the representatives be chosen randomly from the population (like jury duty). That'd help a bit with the whole political dynasty issues with the lack of term limits
@@davidwuhrer6704 It's not just bad, it's the worst. Most people just want the government to hand them money "cause they deserve it". So the government just selects the group easiest for manipulation and hand them money in the disguise of "raising social". You know, there was a revolution in France long ago because the nobles were stupid and had too much money on them. People killed the nobles and robbed their properties, then they were starving in Paris because dead nobles surprisingly didn't care about crops and couldn't sell food in the city. That's how wise is the general population. If you want the world to burn and people to starve just let the majority decide everything.
For me the walrus operator makes perfect sense: the equal sign (=) to assign and the colon (:) to return, like the "lambda" function that uses both the equal sign and the colon sign to assign and return (eg. "square = lambda x: x ** 2")
I understand the motivation behind the feature, but imo it makes the syntax too dense and requires too much mental strain to remember what it's doing in certain lines. I will not be using this feature
@@-bamks Actually it cannot save your time and only be to increase the complexity. Consider: `result=re.match(x,y) if result:...` and `if (result:=re.match(x,y)):...` The latter one requires you to press Shift to type the (, ) and : , which is annoying. I would rather type more English letters than those punctuations.
Most other popular languages have this feature, for me it is more of a strain to remember: 'when in python, don't use assignment like that'. For me it would be better if they even didn't use another operator for it, but is probably needed for backwards compatibility.
There's lots of fun errors you can cause with it that weren't really possible before. For example, you can assign a variable to have the same name as the function being called, which could potentially be problematic. Example: funcname(funcname := some value). I was also experimenting with function attributes, and if you do the same thing as the example above that has the same attribute names things can get funky. class TestClass: def __init__(self, x): self.x = x def __repr__(self): return f"TestClass({self.x})" Then defining a function with a function attribute of the same name def test(value): test.x = value Then, instantiate a TestClass object to a variable name 'test' while also passing it to the test function with a walrus operator. test(test := TestClass(5)) This causes a fun circular recursion error whenever the __repr__ method gets called or whenever self.x is directly accessed. Of course you'd have to be pretty silly to do this, and I have no idea why someone would be abusing function attributes this way, but I can see how this could introduce errors that are not as easily handled yet, and someone being dumb could cause some serious problems if they aren't paying attention. Of course 9 months later I'm not sure if it's caught on enough to even cause any problems at this point, but I think it's existence still merits discussion.
This trend of trying to force the diverse and thriving species of computer languages to follow in every detail the invented language of mathematicians in syntax and semantics comes off as authoritarian. It is a mistake and one that will be seen as such in time. Perhaps the reason computer language are so diverse boils down to different language designers thinking about logic in different ways. Mathematics too reduces down to logic, why do we not force, cajole or otherwise emotionally coerce mathematicians to write all their thoughts out not as the higher level mathematical symbols they have grown to love, but rather using the underlying language of logical symbols and the cognitive processes they represent which actually hold mathematics up like pillars from a foundation. Who is a mathematician to desire autonomy from the language of logicians? We can play this game for years. It is an unproductive one. If someone or a community of someones enjoy language X and are productively creating things in language X then it is wrongheaded to go chastising them for ‘incorrect-think’. God forbid people use == for equality and = for assignment, if one only ever sees mathematical assignment := in graduate school then think about how much ivory tower or faded bargain basement cinderblock tower stairs must be climbed before one is exposed to the mathematical assignment operator. Do people begin learning the language of reasoning at 22? Or do they begin a decade or more earlier? It utterly wrong to keep aspects of a language inaccessible (k-12 I’m looking at you) to people for a decade and then tell computer programmers “oh hey, yeah we actually have an assignment operator, you have to listen to us now”. Sorry, No! If you want your symbol to be used, you have to follow the same rules as any other meme, get it into the vernacular and common usage and get it used by many many people. I suspect this operator was not taught in K-13 because mathematicians don’t want people assigning values to things. That’s for them you see, not you. Nothing new under the sun.
In all my years working with computers, Python was the only language that actually got me excited about programming. I've just learned about the Walrus operator and damn, that's awesome! I can't wait to update my code to make use of it. :D
Awesome video! Just a suggestion: In the end, when you finished quoting Guido and started giving your thoughts on subject, you could've removed the quote/image from the screen and showed your webcam while saying the final thoughts =]
Also, if you make it change and the default is now =, it breaks older code. And I think it is a good way to update the language without major destruction like it was when the transition to python 3 happened
In borland(turbo pascal/delphi) Equal sign = was used as a logical operator(== in python) And walrus := was used as "be equal to" (= in python) It was logical, it was awsome and readable....honest I can wrap my head around what it does in python
@Vendicar Kahn _> When a single operation performs two functions, then one of those functions is a hidden side effect._ Not necessarily. Take function composition for example. When applied to pure functions, there is no side effect whatsoever. _> In this instance it is the return of the r-value that is hidden_ It explicitly returns a value. That's what functions do. _> no apparent function is being called_ There is no apparent operator that takes a parameter and returns a value? _> There is also ambiguity since c = op=(a,b) has no clear return value._ _> In this case you have a combined test and assignment._ Where?
I can remember my pascal instructor at UMASS Boston in 1975 (?) introducing us to the ':=' operator. He said that when we read it or use it to say 'gets the value'. So x:=5 reads x gets the value of 5. It was clear that way. Easy to understand. I saw it again in lotus notes formula language, then again in Java, and other languages also. Once understood, any symbol could possibly represent the action of assigning a value. In 20 years of programming in Verizon, I can't remember any bugs resulting from ':='
I'm learning python atm alongside buildig a small program (i do have programming experience though), and just yesterday I bumped into a situation where I could've used the walrus operator perfectly! I don't think I've seen anything like it before. Interestingly, even searching for a "pythonic" way of handling my problem, it wasn't mentioned anywhere ... where i was looking at least. No clue whats going on with the drama behind it, but I'm so glad i was recommended this video!
Kind of a noob here: PHP uses this by default right, just so I understand? For example, you could do the code below to dump all rows in a MySQL response: if ($row = $response->fetch_row) { var_dump($row); }
Yes it does. It’s a great feature that makes code much easier to read and imo that’s what python is all about, so I do not understand why people are complaining...
Imo i think people just crying because they don't like to change things they're used to. I'm used to walrus since pascal time in russian schools an it's very clear, intuitive and explicit concept. When you're assigning values, you're not equating them, you're "pooling" value from right to left, so i understand why it would need a different operator to mark that distinction
I've programmed for long enough, in enough languages, that I've stopped caring. I predict that we'll have editors that will re-write our code on the fly into whatever style (and perhaps language) we choose, similar to syntax highlighting styles. Languages that handle safety and currency elegantly will win out.
Heard about you on JRE, listened to random videos of yours here and there; never knew until today you had videos on Python. Very cool, much appreciated.
I'm not sure if I agree with the notion that just because you can write confusing code with an operator, the operator itself is confusing or bad. The programmer has to take a bit of responsibility to make sure they can understand their own code once they come back to it by either containing the urge to be clever, writing good comments, or both.
Exactly. I always found it natural for assignment to return a value and was kinda puzzled why this feature is not present in python-like languages. Sure, you can (ab)use this operator to write a juggling clown car circus of assignments if you really want to (aka. if you're a pretentious slow-off). But that rarely happens in practice.
A C++ dev friend of mine loves the fact that = returns a value, and uses that fact often. Since I'm not too used to it, I always doubletake when I see it, but sounds like a convenience thing. Like how in js' DOM you can chain together functions because of the method signature
LESS CODE IS NOT ALWAYS BETTER It has to be easy to learn to, especially for new user. Its one thing for experienced programmers to learn just one more thing, but for people at the bottom, it may just add to the growing list of what they have to learn Ease of use AND learning both have to be factors considered when deciding on new features and design paradigms
Well in matthematics assigment is ":=" and equality is "=" instead of "=" and '==" which are commonly used in CS. I think using ":=" is better from a mathematician point of view and I also think is better of greater levels of abstraction but I can see how people will get confused and write bad code this way.
The fact that it's a different operator from regular assignment to make it explicitly clear that you're going to immediately use the assigned value makes me like this more than the assignment operator in java and C. Half the devs I know don't even know that assignment returns a value in Java.
That is true I will get used to it and forget that it was a inconvenience in the first place. I'm just worried that I'll have to start learning more JS, because Python will become too complicated for beginners.
I'm an old developer. I've done a lot of C and assembly in my younger days. For many reasons, I like Python better than all the other languages I've touched, BECAUSE IT SIMPLIFIES THE THINGS I WANT TO DO, and is the most easy to understand (go back and read your code a year later). There are a few very useful functions that I missed with Python: Pointers, switches, and this. (I find I get by just fine in Python without pointers, because it's like everything is a pointer!) So when Python adds match/case and walrus, I will gladly use them! It's a great language that just gets better. = means one thing. == means another thing. := means another thing.
I remember the := leaving a bad taste in my mouth when I first heard about it (mostly for the reason you mentioned involving the added complexity in the name of brevity) but I had no idea about all the controversy. Shame all the crap that Guido was put through on account of a feature that we could simply choose not to utilize if we weren't fans.
Mathematician here to clear something up: x = 42 is a statement that you can logically imply that x is equal to 42 (via axiom). x := 42 is the (probably more accurate as a programmer) statement that x is defined to be equal to 42 (via definition)
You can argue that if something logically follows then it is by definition; this, however, is more commonly differentiated by using a triple line equals (congruent to) ≡
Using “=” for assignment was a mistake. It was a mistake in Fortran, it was a mistake in C, it’s a mistake in all those languages that have copied C (including Python). Consider also the inconsistency: if “==” is the equality comparison, and negated versions of operators are just supposed to have “!” in front, then why isn’t the inequality comparison “!==”? The Algol language family (including Pascal and its offshoot Ada) invented “:=” for the assignment operator, reserving “=” for equality comparison. This I think makes much more sense. Perhaps walrus in Python was a backdoor way of introducing this usage, at least in part?
@@benjaminbrady2385 pretty sure congruent is logically equivalent. (As in the truth values are equal under all interpretation). If something logically follows it'd be just an implication.
@@kami_fps it is, for the most part; the "truth values" aren't the same for "all interpretations" rather for the interpretations that we care about given the context. The real term is isomorphic (congruence is a type of isomorphism) denoted ≅. This describes when things are, via implication, identical given any properties which we care about (using this implies that they're not truly identical, usually because they aren't literally the exact same expression; they could be the same though)
So with the limited qwerty what symbol is better to represent assignment in languages that insist on symbols? There's no explicit assignment notation in math to have parity with compsci. On general keyboards there is complete lack of math symbolism; no congruent|triple-bar(≡), no therefore(∴), or turnstiles(⊨),etc. Even then those example symbols are a stretch to mean assignment. There's cringey combo symbols for assignment that just increases complexity more than necessary they need to be(-> , => ,
Thank you for teaching me something new! Walrus is great and you fixed a bad assignment trick I was using. Edit: this will only work for objects that are not modified in place [A, B, C = integer for i in range(3)] is now: A = B = C = integer Thank you!
Walrus operator is a very useful thing. Imagine you've been thinking of moving to another language, but you were hesitating. In this case it can help you to accelerate the decision making process.
I really don't think this is a problem or something worth spending a second discussion on, if you don't like it just don't use it and if you like use it. Of course python is not perfect, there is no language ("perfect") any language can have a ("but") but that does not mean it is a bad language, we must not forget that languages are tools, you cannot Saying that a screwdriver is bad because you can't use as a hammer. I personally believe that 99% of the criticism of languages in these types of forums are pure nonsense.
There is no language perpect. But perfect is what python aim to Clear and clean code, easily readable. And i believe this is why people love python, and why this little thing become controversial What i think is, python is just not about the functionality, but more like the language, philosophy and the art in it If you just use python as a tool, this won't really matter for you. But as a language, little thing can became critical to you
Sadly, "if you don't like it just don't use it and if you like use it" argument breaks when you have to deal with the code written by someone who likes to use things you don't like.
Гарсиан Кузнецов Well, in my programming experience I could say that all languages have syntax that could be a bit confusing or unreadable, however that has never been a real problem, from my perspective once you get familiar with a syntax it is no longer confusing, the real problems in the code at least from my point of view are always the same regardless of the language, infinite classes, little decoupled code, little descriptive names, absence of documentation, absence of any type of tests, poor organization at work, .. .. etc. Actually, when working, it is these last problems that really affect the team's performance, since from my point of view a syntax will be a problem the time it takes for the team to become familiar with it.
I love it how he called it a ‘Permanent Vacation’ because technically; he’ll still be BDFL while on Vacation... and he can decide to end the Vacation at any time... Technicalities, I love them.
Speaking of influential language designers - have you interviewed Anders Hejlsberg, yet? Amazing guy. I've met him person (NAME DROP!). Worked in the same building, too. Didn't "know" him, really, but we did chat a couple of times. This discussion of the walrus operator made me think of him because of his involvement with Delphi (aka Object Pascal). Personally, I think his design of C# is brilliant.
In the last few months, I've become a big fan of the := way of variable assignment, simply because "=" makes more sense to make "is this equal?" as opposed to an assignment
I believe the assign and return from the walrus might be similar to a one line arrow function in js. It's super nice to have those shorter ways to write returns
Using the equals sign for assignment makes sense if you don't think of variables as buckets to put values in, like so many misguided novices do. You declare the identifier and the value as equal. The problem begins when you start re-using the identifier for other purposes. Don't do that! Let the compiler figure out how best to make use of the available registers. That's what it's there for. Admittedly, with a low-level language like Python or Fortran, there is no compiler to do that for you. (I know that Python has a JIT compiler, but it's still a scripting language.) So on an old PDP-1, programmers had to compromise to fit their programs in core memory and still get performance. Python programmers have no such excuse. Frankly, there is no reason for re-assigning an identifier. For-loops can be replaced with list comprehensions, which are not only more terse (and yet still readable), but also isolate side effects. While loops could be replaced with tail recursion, if Guido van Rossum weren't so strictly opposed to the idea. (That is an obstacle that will soon have been overcome.) And thus, any identifier has one, and only one, purpose, and hopefully an expressive name for it. (Which would make the JIT compiler quite a bit simpler, too.) As for confusing the assignment operator for the equality operator: They could be the same operator with no ambiguity, but that would make chain assignments impossible. But if you never re-assign identifier values, when would you need chain assignments? For Python3 that is not an option of course, because it would break existing code. But only RedHat is still hanging on to Python2. The rest of the world has long since moved on from this unsupported relic. A new version of Python might even get proper versioning support.
return {kw: _kw_indexes for kw in keywords if (_kw_indexes := find_occurrences(document, kw))} This was a part of a function which takes a list of keywords and returns a dictionary containing the keywords and index occurrences. The function doesn’t add a key if there are no occurrences. Without the walrus operator you would have to repeat the search (which is expensive) or you would have to use a for loop instead of a generator. In this case the most natural solution is to use the walrus operator.
As a non programmer who subbed primarily because of astrophysics podcasts, I feel like I'll be taking Guido's side on this. It's pretty clear to me that PLIP PLOP 1337 operator assignment x + y + z + syntax BBC ABC ᕙ༼ຈل͜ຈ༽ᕗ == (51) pythons was a terrible idea and we need more hello worlds.
Good addition. This is how lisp forms works by default, and it's a useful feature. The := syntax itself may be kind of ugly but something is necessary in a language like Python.
It's not "antithetical", it's just not necessarily always the case. More often than not shortness and elegance coincide. I wonder if torturing oneself to write bloatcode is a Python dev thing.
세종대왕 not more often. Clever code means code that maybe you understand, but doesn’t mean that other people will. Clever code is not teamwork code, it’s single work code.
this solves a problem I've hit dozens of times, where I want to store data but also immediately use it in a conditional. I'm not sure why people would throw a shit storm about it
Although python is a great programming language, the more I learn about python, the more happy I am to continue to write my code in ruby. It's simply much more compatible with how I think and how my brain works.
It's not surprising that the walrus operator encountered stiff resistance among Pythonistas. It goes against the grain of the language. Pythonistas want their code to be as clear as possible, not as concise, as efficient or as pretty as possible. Any statement or operator that does more than one thing is automatically suspect. Furthermore, as stated in the video, there was already a perfectly good assignment operator and Pythonistas don't appreciate language redundancy, they want there to be only one way to do things. Guido should have decided against the walrus operator, no matter how many other languages have something similar. That's just the way Python should be. I would judge its addition to the language as a leadership failure.
"This rule is included to simplify the choice for the user between an assignment statement and an assignment expression -- there is no syntactic position where both are valid. [...] Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions. Conversely, assignment expressions don't support the advanced features found in assignment statements..." --PEP 572
Isn't this just how the regular assignment operator functions in practically every other language? Even Java, which is notorious for excluding tons of common features that "lead to bad code", has an assignment operator that functions this way. I seriously don't understand why this is so controversial.
Probably I’m the only one who rly loves it mainly because it allows me to do and if and asignation in the same line . Maybe it isn’t pythomatic etc etc but I quite enjoy it .
Personally when I was trying to learn javascript by my own when I first started I couldn't these kind of instructions "x = x+1" because for me it was mathematically invalid. Then in high school we learned Pascal (for some reason we still teach Pascal here). I finally managed to understand that instruction but I don't know if it's because I had a teacher to help (a bad one though) or because Pascal used the := operator making it clear that it's actually assignment and not equality. As for the operator itself, I'm not sure now. From a side I think that making this mathematically invalid notation is confusing but from another side I think that assignment is probably the I operation we do the most in programming so why make the operator longer ? In the case of Python, I say why not have them both ? I mean C++ is full of features that few people use but those people love them and it's probably one of the things that make C++ great, the freedom of style.
The walrus operator := and assignment expressions, PEP 572, was opposed by majority of Python core developers, and led Guido van Rossum to step down from BDFL role. Here's the outline for the video:
0:00 - Walrus operator
1:26 - Use cases
3:33 - Criticisms
5:59 - Guido van Rossum
Why doesn't Python do as other languages do... assignment also return the assigned value, so no : would be required. As in C:
if (a = b) // true as long as b is different from false/null
This is quite a stupidity from Python devs, like the indentation to determine blocks of code, which gets annihilated by different IDEs in different OSes working with source control, and is therefore difficult to use in corporate environment.
@@marsovac The canonical reason is that returning the assigned value is prone to one specific kind of error, when you say this:
if a = b: ...
but you meant to say this:
if a == b: ...
In the first version, a will always equal b because it is assigned the value in b, and if b is not False, the contents of the if statement will always run. This was a really common error in C, and Python made the = operator non-valued to specifically fix it.
FWIW, I like the semantics of := and look forward to using it. Some other languages added new constructs (e.g. if-let in Clojure) to specifically enable cases similar to this.
This is definitely not worth it. I understand it reduces the code length. It is against the principle of occam's razor
@@asyntactic you have a warning for that in at least some C compilers. Here is what you get with clang: "using the result of an assignment as a condition without parentheses [-Wparentheses]"
While in other languages like C# that is not a valid if statement at all since it does not return boolean, compilers are intelligent nowadays. I don't remember if I had an error caused by that in the last 10 years of coding. If Python happens to have such issues then there are more fundamental problems in the language itself. Like for example "do not treat anything/everything as boolean" would have solved this specific problem. If you want to be explicit about the syntax there is nothing better than "null != (a=b)" but to introduce more interpunction around assignment operators is clear as fuck, especially when it does something else than what other languages use it for..
Don't get me wrong. I'm not trying to piss on python, I would in fact like to use it, there are nice features for working with data and data sets, but sure there are some weird decisions taken that solve nothing and introduce new problems, which make it not good enough for sharing code across teams with different environments on the same code repository. The one time we tried some guy destroyed code files by using nano indentation not matching what others used in VSCode. That problem was created by what? Trying to remove braces from code? And the choice to not use returning the assigned value solves what? A compiler lack of common sense?
@@marsovac Yes, modern compilers do that. I've actually been bitten by this problem in C, but that was more than 15 years ago. The "assignment isn't an expression" convention in Python also originated over 20 years ago, back when this was maybe a more common problem. I don't see it as fundamental language issue - many languages have their own quirky definitions of truthiness. Instead, it's a culture issue. The = vs. == distinction is one of the first things introduced in the tutorial when new users first start with Python, so it's become deeply imbedded in the culture of the Python community. I suspect the anger that Guido provoked was more ideological in nature than technical. The original language designer thought he could change his mind - joke's on him!
The fact is this isn't a matter of right or wrong. Programming languages have their own idioms, and you get used to their particular way of doing things. Python isn't my favorite language, but I've used it for years, and it's turned out to be very valuable.
I don't think for a second this was worth losing Guido for, projects like this are super hard to guide and this guy did it for decades.
I highly doubt this is the reason why he stepped down. I can only imagine the levels of forum drama and hate that this "issue" arouse... And probably *that* is more related to him leaving.
@@cuentadeyoutube5903 He actually stepped down so that Python could cleanly transition to a model where it didn't require him as a BDFL in order to operate. It was planned for a while. He found capable successors and helped reshape the governance structure before stepping down. It just so happens there was some controversy around a language feature around the same time, but there was lots of controversy with prior PEPS, as is the nature of all open-source language development.
Python has been a solid programming language for decades. You can pretty much stop developing it now. And just focus on the issues arise from new OSes. The core python is super solid. And Pypi packages are solid too. A language like this can guide itself on its own.
@@DavidFlanagan_Mechatronics I agree
Python deserves to be its own eosio chain and I will pay all python programmers on github with tipit.io
I guess people had to find something to fight about in a language that has no braces and standardized indentation...
Cheap shots. Accurate, well played cheap shots.
@@codyneubeck6557 sand people
This
We have braces. Just really rare
@@Trackrace29582 I used them today! They're called dictionaries. They're pretty useful.
Me as a C++ Dev: *overloads operator= to do whatever I feel like making it do*
Python Devs: *unintelligible, angry swearing*
@@NoName-to5xl Not the assignment operator that I'm aware of... unless I'm missing something. I dabble in Python, but I'm no expert.
@@NoName-to5xl Only when necessary. I have been writing python for almost 3 years and never used it. It is useful for things like numpy where addition on objects is very common.
Python Neeeeerds. C++ is so much better.
@@NoxmilesDe excuse me but its actually nerrrrrrrrrdz
Light-hearted joke, guys. Python is a great language too. For instance, it's useful for C++ build scripts.
Who would win:
Decades long leader of one of the worlds most broadly utilized programming projects
One tusky boi :=
oh, so that's why it's called a walrus...
Haha now I can't unsee it!
HOLY SHIT THATS WHY ITS CALLED WALRUS
@@user6122 Hour did you make it past the thumbnail?
@@Rose_Harmonic you are overshooting my intelligence, FAR too much
He sounds like he's 50% high and 50% given up on life.
lmao
So like every programmer ever (the percentages might vary)
I feel stupider
@@francescoorsenigo4720 lmao
Well, he’s Russian.
Someone needs to make a "This := kills benevolent dictators." sticker.
This := gives permanent vacation for benevolent dictators lol
Don't you need parens?
/runs
@@lohphat Always. --LISP
> print(this := "PEP572")
> "Removes dictatorship"
self := kills benevolent dictators.
The := operator should not be criticized for its similarity to the = operator in C.
In C, the = operator is error prone because occasionally the == operator is mistyped as =. If the left side is assignable, it compiles--as it is valid syntax--hiding the error until run-time. When used properly, it still provides the same elegance you mention.
The := operator would not have this issue, since the == operator should not be mistyped as :=.
People use the variable on the right hand side and Constant on the left side like (0 == *p) to avoid this issue and compiler would promptly throw an error if one of the = sign is missed. But if both sides are variables, the compiler will not be able to detect it.
Agreed
Error prone? That is if you are compiling with what? A Pocket calculator gcc from 1990? Clang gives: Warning "using the result of an assignment as a condition without parentheses [-Wparentheses]". I'm sure a modern gcc has a similar warning for the assignment in the if without proper syntax.
I prefer code that is simple and the compiler that aids me in not making mistakes. The approach of Python is "you are a dumbfuck, let us decide how you write, so we don't need to write a helpful compiler".
You can easily find a C style guide that recommends using yoda conditions to prevent errors as such. I find yoda conditions pretty neat and your code is not error prone at the same time.
@@Ricardo-C I occasionally like Yoda because it can improve readability in value = function(...) conditionals where the function call is obvious.
Every time I hear about Python drama, I am reminded that I am too freakin' old for this crap. Have I been bitten by the = vs == typo, sure, all the time. Do I think it's worth implementing "walrus" syntax to avoid that error ? Sure, go right ahead and make my life easier. This doesn't even break legacy code, so it's a freebie in my book.
But do I think it should have been such a huge source of drama ? Hell no. If people are butthurt because this breaks away from C conventions, to those people I say "go use C then". A skilled programmer should use the best tools available to them, not lament the fact that a screwdriver is not a drill press. Python is supposed to be an easy and versatile scripting language, and this kind of syntactic sugar is one of the many ways in which it fulfills that mandate.
the walrus is not really supposed to avoid misusing = or ==, though
it's a shorthand for reusing the assigned value in some other expression (that is not also an assignment, you could always reuse assigned values to assign more variables e.g. `a = b = c = 10`)
even though walrus operator break anything, it means one more weird syntax to learn.
you can do what walrus operator does without looking scary to newcomers
there is a simpler-looking and easier to understand way of doing what walrus operator does, which is why people objected to it, considering how python makes sure people cant abuse operators to obfuscate code. everything must stay in its simplest form, yet walrus operator is a redundant feature. it provides same as an existing method, and that requires people to learn more.
It can be useful for jupyter too where usually the last thing you want to do in a cell is both to assign a variable and show its value.
But this is not C++ where you add every feature that can be useful.
agree, the simplest example is we don't need to print pandas df after reading it in the first block of code :p
Whoa, I never considered that. I think it's still more convenient to just write the variable again in the last line, because then it's easier to enable/disable it (without having to remove the parentheses). And easier to move the code around, when you are exploring commands to later package into a function pipeline. Maybe if someone wrote a plugin for vs code/jupyterlab to switch between = and (:=) with one shortcut.
I think it's still important to point out that after Guido stepped down as BDFL the core developers voted to create an elected steering council of I think 5 people to together take up his role in the future and Guido was voted as one of the members. The quote at the end makes it sound like he abandoned the core devs and left them in chaos ^^
I'm not up to date on the current situation but I believe the members are voted in for a fixed period of time or something and Guido said he won't be a member the next time (or he might already not be anymore) but it has been a while so I might be misremembering or this might be out of date info.
No it doesn't sound like that
Funny how python has “There should only be one obvious way to do it” and Perl was “There is always more than one way to do it”
*there is always another way to do it
They're two opposing programming language philosophies that are applied to many many languages (think C++ vs. Java). And I think the Python's phrasing of the principle was actually a reference to the Pearl's one.
@@leogama3422 I think for most things, the philosophy is either: A. Hack it yourself, (C, PERL) B. We have a comprehensive standard library, but you can still Hack it yourself(C++) and C. Use this one specific paradigm and everything is already done for you in a way that you have little control over (Java, python, etc)
The latter can be useful in a lot of cases, and I'm not saying that's necessarily bad to use
The actual Perl community expression is "There Is More Than One Way To Do It", which has the acronym TIMTOWTDI, pronounced (and sometimes personified) as "Tim Toady".
Forrest Cahoon thanks, I knew it was something like that, and Tim Toady sounded familiar
Having no Python experience, this seems like a very useful operator. Java and C# have something similar that i abuse constantly.
What does Java have that's similar?
To answer a polite question and avoid triggering the easily distracted further, I will clarify c# has a similar operator i use, and I thought recalled Java having something like that when I was studying it. I could easily be mistaken.
Thanks to those of you who realized the point was to comment the operater seemed useful.
JavaScript as well, but it's just the = sign. Why can't python make `x = 42` an expression as well?
Wilco Verhoef Because then ```if (x == 42)``` can quickly become ```if (x = 42)``` by accident.
@@Mr_Yeah admittedly this happens occasionally any all languages that use == already.
I had never heard of that operator being called a "walrus operator" before. Hilarious!
It's almost as funny as the Elvis operator.
With appropriate fonts it could be called “the pp operator.”
Wait until you learn what the name of `::` is!
python in 2021: introduce °w° operator
@@JivanPal what's the name of :: ? I've always used in C++
I think we will have to see how it ends up used in practice. My main concern is how it might impact readability. It's not something that should be sacrificed for brevity of the code.
Totally agree. 1. It works 2. it's readable/maintainable by another dev 3. anything else
I think it's more readable tho tbh. Less visual noise is great.
@@thomaskolar90 you should love coding in obfuscated c, very short, and stylish
completely unreadable though
@crazywayne yeah, I agree with the concern about feature creep, but I think this one is worth it. We add a bit of complexity of course, but I feel like the complexity we lose by not having extra control structures/multiple comprehensions is well worth it. In these cases I've always felt something I rarely feel when programming in Python, and that was that I was having to work around limitations of the language. There may now be two obvious ways to do some things, but there was never an obvious way to do this, at least if you've been spoiled by Python sufficiently to expect better.
@@thomaskolar90 It saves you some lines which is totally useless. The main problem with compact code is that you need more brain power to read it. When you have 3 lines of code where every line do one thing you can read it easily, when you encounter a line with the walrus operator you have to evaluate that line in your head. It is a calculation, an assignment, and a condition check in one.
The Walrus operator is mostly common in languages like Go Lang to initiate a variable, and then if you want to change the value of the variable later you use the equal sign
That's like the opposite of intuitive. I remember go had something like it, and for a second thought go was amazing.
It's actually OCaml that does it right.
Isn't the expression different because in python you need to use (a := b ).
Or can you do f((a := b)) in Go?
@@catcatcatcatcatcatcatcatcatca What Go and Python do with walrus operator is completely different and only relevant in the respective language
Eww Go
Mike White Don’t knock it’s til you try it. Plus it could be worse. My minor in college made me take a course on VB.net. 🤮
Personally, I'm not sure how I feel about this. I may not code in Python, but I think lambda expressions in java would be somewhat comparable to this. Not in functionality, but in similarity to the effect on code. Whenever I find code written by a previous team on my project, they abused the shit out of lambda expressions, just to "reduce lines" of code. They had multiple nesting lambdas together. Sure it made it 'smaller', but it also made the code absolutely hell to read. A for loop would have been bigger, but has greater readability potential. But the main issue is that they didn't use lambdas very well. They didn't use the right tool for the job, and used it just for the sake of doing it.
So the walrus operator reminds me of this. I probably wouldn't use it, but I don't think it should be a problem that it exists in the code. Many who opposed it probably won't use it. Those who are knowledgeable will probably use it right. And those who don't use it right will pay the price.... hopefully.
I guess that's where some of the concern lies. When other devs have to clean up someone else's mess.
Side note: thanks Lex for showing this. I had seen/used this operator when making AutoHotKey scripts, but didn't know what it was called lol.
Or you could just learn to become familiar with the lambda syntax and embrace the concision rather than replacing it with more verbose things that you pesonally have more experience with and are more familiar with.
@@jeremykothe2847 I know how to read the lambda syntax. I'm totally fine with simple uses of it. But my point is that it a tool shouldn't be used incorrectly, and the code shouldn't become any less readable. I can't totally explain it without showing you the code, but the way they used it was like a "bandaid patch" to a flaw in the overall code design.
I agree, but this is the case for so many things in programming. A lot op people use OOP just for the sake of using OOP, even if it makes the code much more complicated than it should be. A programming language and all the functionalities it offers are just a tool to get a job done, and just like in real life, you need to select the right tool for a job. Just because people might use a hammer to put a screw into something doesn't mean there shouldn't be a hammer
you won't be using it, but you'll be paying the price for those half-hearted "beautiful people" spitting code you'll be forced to use
@@fabianevans1806 Ah, that's quite interesting. I wonder how much of a performance savings it is during creation then.
I wish Guido was more like Torvalds and had just humiliated all the assholes who complained about the := operator and had remained in charge. But I guess this is not for everyone. I would've probably done just like Guido, but I wish I was able to be like Torvalds.
don't glorify linus on what he does wrong. the guy has plenty of rights to sustain constant complement
@@miguelbatista9493 "wrong" is a very strange way to spell BASED
@@miguelbatista9493 okay soyboy
Duck Meat imagine unironically saying soy boy
@@ckkitty Imagine unironically acting like one
The Universe can be described as a never-ending struggle between habit and novelty.
Or order and chaos, if you will
Brilliant, I had to share this line with my friends
If want to understand the concept more deeply, I highly recommend JBP's old Harvard lecture
@@johannakunze3300 was just about to say this. the biggest thing i learned from peterson was the patterns, like chaos and order, that you can find repeated everywhere you look
yin and yang if you will
I personally like the walrus operator, and don't really buy the criticisms.
"Can be used just for assignment (=), so confusing to beginners"
"There should be only one obvious way to do it"
Not an issue since it was accepted that := can't appear on a line by itself without (); the obvious way to do assignment is with =
"This is how the = operator worked in C and it was error-prone"
This was only error-prone in C because it was easy to mistype == as = (a common mistake for beginners to programming, since they expect = to have the same meaning as in mathematics), so that you would end up assigning in an if-check `if (x = 42)` instead of testing for equality; I don't think it's as easy to confuse := for = (you're not using := unless you know what it does).
"Simple is better than complex; Adds complexity in the name of reducing whitespace"
This vague objection can be said of basically any new language feature/abstraction; list comprehension, for loops, even functions; they all add complexity in the name of reducing whitespace. Doesn't mean they're not worth it. Be more specific about why the added complexity of the walrus operator (which is little IMO; it took
@William Baric "The idea that an assignment returns a value is not intuitive. Beginners will have a hard time grasping the concept."
True, but Python isn't just a toy language for noobs; one of the great things about Python is that it's simple enough for beginners to learn it easily, but has more advanced features for more experienced developers (e.g. list comprehension). Beginners can stick to easy things they know, and when/if they're ready they can check out more niche features like the walrus operator.
"More importantly, packing instructions always make the code less readable"
Debatable; sometimes it does, sometimes it doesn't. For example, here's some code from one of my uni assignments, where we had to read from a database with sqlite3. The starter code looked something like this:
```
cur.execute('SELECT title, year FROM movies')
while True:
t = cur.fetchone()
if t == None:
break
title, year = t
print(f'{title} was made in {year}')
```
I rewrote the code with the walrus operator like so:
```
cur.execute('SELECT title, year FROM movies')
while t := cur.fetchone():
title, year = t
print(f'{title} was made in {year}')
```
Which version is more readable, first or second? I'll admit readability is subjective, I won't criticize anyone who answers "first", but to me the second version is more readable. Not only is it shorter, but it better conveys the intent of how long we're looping for (better than while-True-break kludge).
@William Baric Oh I agree. while-True-break is an ugly technique and you should normally use better variable names. The point I was just trying to demonstrate with this small (but real) example is a good use case for the walrus operator; without the walrus operator, Python programmers would have no other choice but to use the while-True-break technique.
Actually, I suppose another way to write the code would be to repeat the looping condition before the loop, something like this:
```
cur.execute('SELECT title, year FROM movies')
t = cur.fetchone()
while t != None:
title, year = t
print(f'{title} was made in {year}')
t = cur.fetchone()
```
But I dislike this approach because `t = cur.fetchone()` is repeated twice, and the scope of `t` is now bigger than it needs to be, reducing clarity to me (is `t` only supposed to be used inside the while loop, or did the programmer intend to use it afterwards as well? With the walrus-operator-approach, the answer is obviously "only inside the while loop", but in this approach it's less clear).
The point I'm trying to make is that this is a case where the walrus-operator-approach is more readable than any other approach (assuming they're all using the same variable names ofc).
@@saeedbaig4249 I'm totally with you on these examples. I've run into this exact situation countless times, and sometimes I've used the while True/break approach and sometimes I've used the duplicate assignment line. I've always lamented that I can't just do what the walrus operator allows. So to me, it just provides a simple solution for these awkward situations, and does so in an unobtrusive way.
In the eternal words of Terry A. Davis on a new construct he invented in HolyC (a derivative form of C):
"This is voodoo. But the question is, is this too much voodoo? Is this enough for HolyC to last another 100 years? ... This right here, is the hardest question in programming."
He truly was the smartest programmer to ever live
Ah yes, that was with a very cool feature for the language. Something to do with switch statements I believe?
But, yeah, I think the Walrus operator is indeed *too much* voodoo. Cool feature, but ultimately needless and more trouble than it is worth
I have never used this but, with my little programming experience I have:
I think it looks kinda neat however I feel like the code was more complex using it. If you just do the examples the "old" way it is pretty clear what is happening. However if you use this operator I feel like the code is way more confusing to read and just to understand what exactly is happening
I feel like this too. I think it's because I'm not technically able to understand this type of advanced code yet. But, wherever I see code I don't understand is a opportunity to look into it and that's a great chance to learn why things are the way they are in a certain context.
Caio Matheus True. I bet it is just a case of actually using it just like with any bit of new code or method you learn
Exactly. Yes, with walrus op you can write more condensed code. But, it would also become less readable, by the simple fact that you stick more operations in one line of code.
I thought since the times of C, which allowed many neat tricks to write "elegant" condensed code most by today have realized that easy human readability must come first. But not for previous "head of Python" apparently.
Right? I mean, unless you don't have a fucking job so you can shittalk on democracy with faulty comparisons from the programming world, often you will have to show your code to someone, and making it readable is very important then. And from what I understand your code will not even be faster.
I've used the return of = in c++ a lot and always thought it was a great feature and how = should always be. The ++ and -- operators also return their result in place and so do +, -, /, *, and % at least in c++. I don't know why people got so worked up over it still, I feel that many languages have sort of weird choices and that you just memorize them and move on to use them in the future. Also, I'm glad you mentioned the multiple initialization feature because the returning of the value by = is what normally makes that possible in other languages while python implemented it for only that specific case which people were happy with.
He sounds so sad in this video. Like almost crying
Wouldn't you realizing Guido stepped down?
No he doesn't
So this isn’t about The Life of Brian?
No, it's about John Lennon. Imagine that.
A Duck!
@@pfzht So did JPF.
I bet the owiginal pewson who pwoposed the Walwus Opewatow was named Naughtius Maximus
clever
I'm surprised Python's = did not have this already, like C++ does...
They should have added that functionality to the = operator, instead of adding a new one
@@Anlerolo there is a == vs = mistake that's easy to make if = behaves like :=
@@Anlerolo wtf why would = returns the value again?
@@ekrem_dincel why not?
x = 1
y = 2
if x = y:
print("what?")
I came here to learn about the walrus operator, I came out as a pro dictatorship full blown fascist right winger.
Mood
Lol! Excellent comment!
Tfw the skip ad button turned into the walrus operator.
I'm already spooked.
A project like this which doesn't need to be represented by a democracy, because it is not meant to represent everybody. In these kinds of projects, it's often beneficial to have someone break through stalemates and say "this is what needs to be done".
Unfortunately in the real world, we do need democracies to represent everybody for governance. Otherwise we end up with situations where leaders inherit powers long past their ability to lead. Plus morally you want a form of government that is accountable to everybody
I think it is even in this project important and good that people called him out on his bullshit. Instead of focusing on maybe making Python easier accessible or faster than it already is, he wastes his time on a notation that doesn't change anything on speed, only makes your code two lines shorter at a time, and makes Python less accessible - if someone uses the walrus operator and decides to share his code online, beginners will be blown away by the large amount of stuff they don't understand; without such "synonyms" in language, it will become understandable for everyone. It is just the equivalent of using fancy words when there are much simpler alternatives; it confuses beginners and scares them off unnecessarily.
FYI, R actually allows the use of = as the assignment operation. In fact within mutate in tidyverse world, you use it extensively to create columns in matrix like objects called data frames. We tend towards the usage of the arrow -> in many cases now. But there is no where in the language where you can't entirely replace an arrow with an equals sign. Also like most languages we always use double equals, == as a check for equivalence
Also in R, we've actually had the walrus operator in data.table for almost a decade.
And the data.table package uses the (defined in the language/parser but unused?) walrus operator for "column assignments" in its expressions!
(edit: just sow your second comment...)
@@leogama3422 great minds :) AFAIK it's actually defined internal to data table as Matt Dowles 'invention'. A little like the pipe %>% is in magrittr, though in that case most of tidyverse imports it from there, so it can feel like it's part of the parser as well :)
I’ve always liked the look of R’s “
Arrow is nice. I started learning Pascal so I'm a little fond of the :=
I heard of the drama regarding this, but I haven't actually using this feature at all, despite having already used Python for many years. The code snippet provided as an example in this video seems confusing and uncomfortable to me, I would much prefer the one without it. However, at the same time, I am aware of my bias for the tendency of staying in comfort zone. I still remembered when I was first learning C, how confusing the expression "for (int i = 0; i < n; i++) {...}" was, which is equivalent to "int i; i = 0; while (i < n) {...i++;seamlesslysyntacticalespecially when there are more than one thing happened in a single expression. For this reason, I can relate to Guido for his decision. Programming language is a tool, and it should be designed in a way to let user focus on the problem to solve, rather than language feature itself. The good thing is that you always have the option to choose whether or not to use that feature, and write the code in the way that is most comfortable with.
they should've done something similar to Go's approach. where you could write `if x := 10; x != 10 { // do something }` where the first is an assignment statement and the second is a comparison expression. in python it would look something like this `if x = 10; x != 10: #...`
@@spontanurlaub he was proposing an alternative
x = val1
if x != val2:
do something
if you like one liners
x = val1; if x != val2: statement
Thanks Lex for this video, which is a nice side car tangent to the topic that you brought up toward the end of #6. Seems the elements of the Zen covered to some degree Guido's resistance to the operator, along with your Criticisms slide, which I'm assuming also matched Guido's thoughts on the matter. I'm not sure though if I understood from the video, the other side, meaning why those fighting for PEP 572 dug their heels in on it. Why they thought that Python was worse or hobbled without it. And why they felt Guido was wrong. Also, while I'm relatively new to Python, I noticed when you "import this" to access the Zen statements, the "one and only one" sentence has been changed to these two: "There should be one-- and preferably only one --obvious way to do it." and "Although that way may not be obvious at first unless you're Dutch." Even if that was done in jest, it's disappointing the lack of professional courtesy in its tone.
:= is great, it makes the code more compact, for isntance imagine you have a complicated list comprehension and would like to reuse some value in it.
I think if your list comprehension is complex then you should probably not use list comprehension.
Implying compact code is good by definition
just write a for loop then, it's only 1 line longer usually
If you need to assign a variable in list comprehension, just use normal loops
@@ekrem_dincel Yes, that was what I said
If you have chained assignments then I don't understand why you'd even need a separate operator. It wasn't that bad in C and it's far from python's biggest problem tbh. 😅
I share your puzzlement. I guess the reason why they felt a new operator was needed was to avoid compatibility issues... (?)
I would have thought the problem in C was that something like "if (x = 5)" which should have been "if (x == 5)", but the walrus wouldn't have that issue because := != ==.
Ironically c++17 actually made declarations in the if statement easier so now you can do "if (int x = myFunc(); x > 5)".
great breakdown, and i personally hate the idea of this being incorporated to Python
agree, horrendous idea. code should be simple and "boring" - without elegant shenanigans like this above.
@@nsd1169 Are there not other similar 'shenanigans' in Python? How do you feel about list comprehensions? What about decorators?
@five seven a function would not work in this case, semantically
@@sciencecompliance235 imho production code should be dumb clean. if few months down the line you need to re-read your (or someone's) code and you (someone) needs to apply extra efforts (parse though syntax sugar) to understand what's going then such shenangigans have negative added value. // hello uncle bob;
> How do you feel about list comprehensions? What about decorators?
it depends how complicated /these things are ...
on walrus - just the fact that you can assign value to a variable while evaluating expression in if / else is creepy.. recipe for disastrous bugs.
there is a good metric on the quality of the code - "number of wtf per minute", so imho walrus will be a top contributor
^^ all this above is just my personal opinion formed from experience. i might be wrong.
@@nsd1169 Yes! Your first paragraph - Yes! Your first sentence, which is worth repeating: "imho production code should be dumb clean." - Yes!! People who pay for code will rue the introduction of the walrus operator. If they're sensible, production coders will eschew it, and if the walrus operator is used widely and almost certainly mysteriously, Python's utility and consequent use in production will be diminished.
Didn't knew this was a big issue on python, but i find it useful. This operator actually saves me a lot of code lines.
Just a little note about mathematics and the "=" and ":=" signs:
Mathematically, when you write "c=42" and "f(x)=42", the statement is actually an evaluation of a logical statement with a binary operator "=", and two constants in the first case, and a function with a vairable in the second case. It is customary to assume that the expression "c=42" means that this evaluation is *true* so that the two constant values are interchangable. It is not an assignment procedure.
On the other hand, although the ":=" isn't singularly defined, I have seen it used in mathematical logic as a way to define a value as, in such a way that the statment "c:=42" will guarantee that the evaluation of "c=42" will be *true* . This resembles the usage in programming a lot more closely in my opinion.
That is not accurate. Mathematically, the comment above is accurate when describing "="; however, it incorrectly defines ":=". "=", as in "c=42", is a second order relation, which means it takes in two terms and outputs true or false; whereas, ":=", read as "is defined as", functions similarly to macros in C, where for the rest of the document, replacement is used. If the statement "c:=42" is stated, then in any future statement, whenever "c" is used, it actually means just a simple replacement with "42." For example, if "c:=42" is stated, then the formula "c=10" would be replaced by "42=10". The only reason for the use of ":=" is for convenience of writing, so that a really long formula or term can be replaced with a simpler one. Just like with C macros, one can also use ":=" with arguments, if "f(x):=x+1" is used, it also would replace "f(c)" with "c+1" or "f(20x+4)" with "20x+4+1".
Was actually looking for a video like this
Like what? Very specific
Spiderman pointin at Spiderman
Ryan Bruno that explains the walrus operator with some additional info.
Yeaaaaaah Lex! More Python vids please. Love it!
"leaders have to make decisions. we need leaders" You frame a gray issue binary. We need competent leaders + we need competent citizens + we need to be lucky to face issues with clear resolution. #dunbarnumber
True that, and in government democracy has proven the only way to keep a fresh set of leaders coming in who have a chance at proving their competencies. Sometimes we got unlucky, and maybe right now we need to rejuvenate what democracy means as things become stale, but overall we need democracies in government to force out those who will rest on their laurels (or worse, their parents parents parents laurels)
@@MsJeffreyF Democracy is doing worse and worse today. Parties give citizens money for free just to be reelected which is bad for the economy. Other countries manipulate citizens during elections to make the person who will be the most convenient for them win. Democracy was working for a while but now it's not :/
@@Laszer271 I agree democracy is doing poorly in a lot of the world today, although for different reasons. Parties giving mega donors more money, contracts, etc I do agree is bad. I think the problem is that money influences the democracy too much. For it to work better, each person should have a single vote regardless of wealth. Which would mean no more lobbying in America
I think there's other neat things we could try with democracy too, like instead of everyone being elected, have like 10% of the representatives be chosen randomly from the population (like jury duty). That'd help a bit with the whole political dynasty issues with the lack of term limits
@@Laszer271 How is maintaining participation of the general population in the economy bad for the economy?
@@davidwuhrer6704 It's not just bad, it's the worst. Most people just want the government to hand them money "cause they deserve it". So the government just selects the group easiest for manipulation and hand them money in the disguise of "raising social". You know, there was a revolution in France long ago because the nobles were stupid and had too much money on them. People killed the nobles and robbed their properties, then they were starving in Paris because dead nobles surprisingly didn't care about crops and couldn't sell food in the city. That's how wise is the general population. If you want the world to burn and people to starve just let the majority decide everything.
There is never only one obvious way to do anything
For me the walrus operator makes perfect sense: the equal sign (=) to assign and the colon (:) to return, like the "lambda" function that uses both the equal sign and the colon sign to assign and return (eg. "square = lambda x: x ** 2")
I understand the motivation behind the feature, but imo it makes the syntax too dense and requires too much mental strain to remember what it's doing in certain lines.
I will not be using this feature
There's no such thing as "too dense". It's all a matter of familiarity with the syntax.
it's one of those features designed by compiler jocks for compiler jocks, it pushes a language down not up
@@-bamks Actually it cannot save your time and only be to increase the complexity. Consider: `result=re.match(x,y)
if result:...`
and
`if (result:=re.match(x,y)):...`
The latter one requires you to press Shift to type the (, ) and : , which is annoying. I would rather type more English letters than those punctuations.
@@siddat7382 But that's just you. I'm fairly sure for most people it's trivial to press shift a few extra times and would end up being faster.
Most other popular languages have this feature, for me it is more of a strain to remember: 'when in python, don't use assignment like that'. For me it would be better if they even didn't use another operator for it, but is probably needed for backwards compatibility.
There's lots of fun errors you can cause with it that weren't really possible before.
For example, you can assign a variable to have the same name as the function being called, which could potentially be problematic.
Example:
funcname(funcname := some value).
I was also experimenting with function attributes, and if you do the same thing as the example above that has the same attribute names things can get funky.
class TestClass:
def __init__(self, x):
self.x = x
def __repr__(self):
return f"TestClass({self.x})"
Then defining a function with a function attribute of the same name
def test(value):
test.x = value
Then, instantiate a TestClass object to a variable name 'test' while also passing it to the test function with a walrus operator.
test(test := TestClass(5))
This causes a fun circular recursion error whenever the __repr__ method gets called or whenever self.x is directly accessed.
Of course you'd have to be pretty silly to do this, and I have no idea why someone would be abusing function attributes this way, but I can see how this could introduce errors that are not as easily handled yet, and someone being dumb could cause some serious problems if they aren't paying attention. Of course 9 months later I'm not sure if it's caught on enough to even cause any problems at this point, but I think it's existence still merits discussion.
This trend of trying to force the diverse and thriving species of computer languages to follow in every detail the invented language of mathematicians in syntax and semantics comes off as authoritarian. It is a mistake and one that will be seen as such in time.
Perhaps the reason computer language are so diverse boils down to different language designers thinking about logic in different ways.
Mathematics too reduces down to logic, why do we not force, cajole or otherwise emotionally coerce mathematicians to write all their thoughts out not as the higher level mathematical symbols they have grown to love, but rather using the underlying language of logical symbols and the cognitive processes they represent which actually hold mathematics up like pillars from a foundation.
Who is a mathematician to desire autonomy from the language of logicians?
We can play this game for years. It is an unproductive one.
If someone or a community of someones enjoy language X and are productively creating things in language X then it is wrongheaded to go chastising them for ‘incorrect-think’.
God forbid people use == for equality and = for assignment, if one only ever sees mathematical assignment := in graduate school then think about how much ivory tower or faded bargain basement cinderblock tower stairs must be climbed before one is exposed to the mathematical assignment operator.
Do people begin learning the language of reasoning at 22? Or do they begin a decade or more earlier? It utterly wrong to keep aspects of a language inaccessible (k-12 I’m looking at you) to people for a decade and then tell computer programmers “oh hey, yeah we actually have an assignment operator, you have to listen to us now”.
Sorry, No! If you want your symbol to be used, you have to follow the same rules as any other meme, get it into the vernacular and common usage and get it used by many many people.
I suspect this operator was not taught in K-13 because mathematicians don’t want people assigning values to things. That’s for them you see, not you.
Nothing new under the sun.
In all my years working with computers, Python was the only language that actually got me excited about programming. I've just learned about the Walrus operator and damn, that's awesome! I can't wait to update my code to make use of it. :D
If they'd just initialize variables in WORKING-STORAGE SECTION as God and COBOL intended there wouldn't be all this drama.
Back in your basement!
Yeah, and explicitly allocate memory for every iterable object created!
> God
I've never seen “Grace Hopper” spelled this way before.
Awesome video! Just a suggestion: In the end, when you finished quoting Guido and started giving your thoughts on subject, you could've removed the quote/image from the screen and showed your webcam while saying the final thoughts =]
Interesting. In JavaScript you can do the same with just the regular assign operator "=". I'm curious why Python wouldn't just do that too?
It doesn't throw an error when you mistakingly use = instead of ==
@@telecorpse1957 Ahh that makes sense! Doesn't seem too controversial to me then. Actually seems like a good idea.
Also, if you make it change and the default is now =, it breaks older code. And I think it is a good way to update the language without major destruction like it was when the transition to python 3 happened
In borland(turbo pascal/delphi)
Equal sign = was used as a logical operator(== in python)
And walrus := was used as "be equal to" (= in python)
It was logical, it was awsome and readable....honest I can wrap my head around what it does in python
Is there a reason the regular ‘=‘ assignment operator doesn’t return the value assigned?
Probably to avoid the notorious C mistake of using an assignment when you meant to do an equality comparison.
It does return the value that is being assigned. It just cannot be used for a conditional in an if statement.
@@Danny-sj6es It cannot be used in any expression. Unlike in C, chained assignment is made a special syntactic case.
@Vendicar Kahn Returning a value is a hidden side effect? Are you sure?
@Vendicar Kahn
_> When a single operation performs two functions, then one of those functions is a hidden side effect._
Not necessarily.
Take function composition for example. When applied to pure functions, there is no side effect whatsoever.
_> In this instance it is the return of the r-value that is hidden_
It explicitly returns a value. That's what functions do.
_> no apparent function is being called_
There is no apparent operator that takes a parameter and returns a value?
_> There is also ambiguity since c = op=(a,b) has no clear return value._
_> In this case you have a combined test and assignment._
Where?
I can remember my pascal instructor at UMASS Boston in 1975 (?) introducing us to the ':=' operator. He said that when we read it or use it to say 'gets the value'. So x:=5 reads x gets the value of 5. It was clear that way. Easy to understand. I saw it again in lotus notes formula language, then again in Java, and other languages also. Once understood, any symbol could possibly represent the action of assigning a value. In 20 years of programming in Verizon, I can't remember any bugs resulting from ':='
The arguments against it seem absolutely stupid tbh. Great feature & every language should have it.
I'm learning python atm alongside buildig a small program (i do have programming experience though), and just yesterday I bumped into a situation where I could've used the walrus operator perfectly! I don't think I've seen anything like it before. Interestingly, even searching for a "pythonic" way of handling my problem, it wasn't mentioned anywhere ... where i was looking at least. No clue whats going on with the drama behind it, but I'm so glad i was recommended this video!
Kind of a noob here: PHP uses this by default right, just so I understand? For example, you could do the code below to dump all rows in a MySQL response:
if ($row = $response->fetch_row) {
var_dump($row);
}
Correct, I'm not familiar with Python myself so I was a bit baffled by the issue at first. It seems = doesn't return the value in the same way.
It's like the C '='
Yes it does. It’s a great feature that makes code much easier to read and imo that’s what python is all about, so I do not understand why people are complaining...
@@TopSpeedKertus exactly, in C a lot of std functions are implemented to work this way, i think it improves code a lot
Imo i think people just crying because they don't like to change things they're used to. I'm used to walrus since pascal time in russian schools an it's very clear, intuitive and explicit concept. When you're assigning values, you're not equating them, you're "pooling" value from right to left, so i understand why it would need a different operator to mark that distinction
It's just one more operator, it's not such a big real, just don't use it
I've programmed for long enough, in enough languages, that I've stopped caring. I predict that we'll have editors that will re-write our code on the fly into whatever style (and perhaps language) we choose, similar to syntax highlighting styles. Languages that handle safety and currency elegantly will win out.
Heard about you on JRE, listened to random videos of yours here and there; never knew until today you had videos on Python. Very cool, much appreciated.
I'm not sure if I agree with the notion that just because you can write confusing code with an operator, the operator itself is confusing or bad. The programmer has to take a bit of responsibility to make sure they can understand their own code once they come back to it by either containing the urge to be clever, writing good comments, or both.
Especially when it is a way around that ridiculous "while true" pattern.
Exactly. I always found it natural for assignment to return a value and was kinda puzzled why this feature is not present in python-like languages.
Sure, you can (ab)use this operator to write a juggling clown car circus of assignments if you really want to (aka. if you're a pretentious slow-off). But that rarely happens in practice.
A C++ dev friend of mine loves the fact that = returns a value, and uses that fact often. Since I'm not too used to it, I always doubletake when I see it, but sounds like a convenience thing. Like how in js' DOM you can chain together functions because of the method signature
The BDFL should become an anarchy... I would love to see a 2b2t of programming languages
Lol
LESS CODE IS NOT ALWAYS BETTER
It has to be easy to learn to, especially for new user.
Its one thing for experienced programmers to learn just one more thing, but for people at the bottom, it may just add to the growing list of what they have to learn
Ease of use AND learning both have to be factors considered when deciding on new features and design paradigms
Well in matthematics assigment is ":=" and equality is "=" instead of "=" and '==" which are commonly used in CS. I think using ":=" is better from a mathematician point of view and I also think is better of greater levels of abstraction but I can see how people will get confused and write bad code this way.
That is their problem. Software engineers won't misuse it.
The fact that it's a different operator from regular assignment to make it explicitly clear that you're going to immediately use the assigned value makes me like this more than the assignment operator in java and C. Half the devs I know don't even know that assignment returns a value in Java.
IMO typing ":=" takes too much brain power, compared to just writing the logic more openly.
lmao
Agreed. I’d prefer to write it out myself and have it be easier to understand.
Exactly. I'm also iffy about the STL on these grounds.
What about the conditional operator, you get used to these things
That is true I will get used to it and forget that it was a inconvenience in the first place. I'm just worried that I'll have to start learning more JS, because Python will become too complicated for beginners.
I'm an old developer. I've done a lot of C and assembly in my younger days. For many reasons, I like Python better than all the other languages I've touched, BECAUSE IT SIMPLIFIES THE THINGS I WANT TO DO, and is the most easy to understand (go back and read your code a year later). There are a few very useful functions that I missed with Python: Pointers, switches, and this. (I find I get by just fine in Python without pointers, because it's like everything is a pointer!) So when Python adds match/case and walrus, I will gladly use them! It's a great language that just gets better.
= means one thing. == means another thing. := means another thing.
Awesome breakdown.
I remember the := leaving a bad taste in my mouth when I first heard about it (mostly for the reason you mentioned involving the added complexity in the name of brevity) but I had no idea about all the controversy. Shame all the crap that Guido was put through on account of a feature that we could simply choose not to utilize if we weren't fans.
Mathematician here to clear something up:
x = 42 is a statement that you can logically imply that x is equal to 42 (via axiom).
x := 42 is the (probably more accurate as a programmer) statement that x is defined to be equal to 42 (via definition)
You can argue that if something logically follows then it is by definition; this, however, is more commonly differentiated by using a triple line equals (congruent to) ≡
Using “=” for assignment was a mistake. It was a mistake in Fortran, it was a mistake in C, it’s a mistake in all those languages that have copied C (including Python).
Consider also the inconsistency: if “==” is the equality comparison, and negated versions of operators are just supposed to have “!” in front, then why isn’t the inequality comparison “!==”?
The Algol language family (including Pascal and its offshoot Ada) invented “:=” for the assignment operator, reserving “=” for equality comparison. This I think makes much more sense. Perhaps walrus in Python was a backdoor way of introducing this usage, at least in part?
@@benjaminbrady2385 pretty sure congruent is logically equivalent. (As in the truth values are equal under all interpretation). If something logically follows it'd be just an implication.
@@kami_fps it is, for the most part; the "truth values" aren't the same for "all interpretations" rather for the interpretations that we care about given the context. The real term is isomorphic (congruence is a type of isomorphism) denoted ≅. This describes when things are, via implication, identical given any properties which we care about (using this implies that they're not truly identical, usually because they aren't literally the exact same expression; they could be the same though)
So with the limited qwerty what symbol is better to represent assignment in languages that insist on symbols?
There's no explicit assignment notation in math to have parity with compsci. On general keyboards there is complete lack of math symbolism; no congruent|triple-bar(≡), no therefore(∴), or turnstiles(⊨),etc. Even then those example symbols are a stretch to mean assignment. There's cringey combo symbols for assignment that just increases complexity more than necessary they need to be(-> , => ,
2:36 is actually a really good and neat way to use :=
better than the pre 3.8 way to do it
Hours of videos uploaded on TH-cam every minute.
His thumbnail:
8::::::D
Thank you for teaching me something new!
Walrus is great and you fixed a bad assignment trick I was using.
Edit: this will only work for objects that are not modified in place
[A, B, C = integer for i in range(3)] is now:
A = B = C = integer
Thank you!
Walrus operator is a very useful thing. Imagine you've been thinking of moving to another language, but you were hesitating. In this case it can help you to accelerate the decision making process.
I love the adding of walrus operator. It lets me do variable aggignments in lambda function.
But I hate the operator symbol
I really don't think this is a problem or something worth spending a second discussion on, if you don't like it just don't use it and if you like use it. Of course python is not perfect, there is no language ("perfect") any language can have a ("but") but that does not mean it is a bad language, we must not forget that languages are tools, you cannot Saying that a screwdriver is bad because you can't use as a hammer.
I personally believe that 99% of the criticism of languages in these types of forums are pure nonsense.
There is no language perpect. But perfect is what python aim to
Clear and clean code, easily readable. And i believe this is why people love python, and why this little thing become controversial
What i think is, python is just not about the functionality, but more like the language, philosophy and the art in it
If you just use python as a tool, this won't really matter for you. But as a language, little thing can became critical to you
Sadly, "if you don't like it just don't use it and if you like use it" argument breaks when you have to deal with the code written by someone who likes to use things you don't like.
Гарсиан Кузнецов Well, in my programming experience I could say that all languages have syntax that could be a bit confusing or unreadable, however that has never been a real problem, from my perspective once you get familiar with a syntax it is no longer confusing, the real problems in the code at least from my point of view are always the same regardless of the language, infinite classes, little decoupled code, little descriptive names, absence of documentation, absence of any type of tests, poor organization at work, .. .. etc. Actually, when working, it is these last problems that really affect the team's performance, since from my point of view a syntax will be a problem the time it takes for the team to become familiar with it.
I love it how he called it a ‘Permanent Vacation’ because technically; he’ll still be BDFL while on Vacation... and he can decide to end the Vacation at any time...
Technicalities, I love them.
I still don't understand how it passed when the majority opposed it...
I think that's how dictatorships work...
Speaking of influential language designers - have you interviewed Anders Hejlsberg, yet? Amazing guy. I've met him person (NAME DROP!). Worked in the same building, too. Didn't "know" him, really, but we did chat a couple of times. This discussion of the walrus operator made me think of him because of his involvement with Delphi (aka Object Pascal). Personally, I think his design of C# is brilliant.
Anyone else reading walrus as 'which is'?
yeah, 'which is' or 'being'
In the last few months, I've become a big fan of the := way of variable assignment, simply because "=" makes more sense to make "is this equal?" as opposed to an assignment
i totally understood everything in this video
same, bro. same.
thats something that someone who didnt undertand anything would say
@@es_ina That's something "Ni!" Monty Python would say : = ) en.wikipedia.org/wiki/Disambiguation_(disambiguation)
I believe the assign and return from the walrus might be similar to a one line arrow function in js. It's super nice to have those shorter ways to write returns
I personally love the operator, I use it a ton
Using the equals sign for assignment makes sense if you don't think of variables as buckets to put values in, like so many misguided novices do.
You declare the identifier and the value as equal.
The problem begins when you start re-using the identifier for other purposes.
Don't do that! Let the compiler figure out how best to make use of the available registers. That's what it's there for.
Admittedly, with a low-level language like Python or Fortran, there is no compiler to do that for you. (I know that Python has a JIT compiler, but it's still a scripting language.)
So on an old PDP-1, programmers had to compromise to fit their programs in core memory and still get performance.
Python programmers have no such excuse.
Frankly, there is no reason for re-assigning an identifier.
For-loops can be replaced with list comprehensions, which are not only more terse (and yet still readable), but also isolate side effects.
While loops could be replaced with tail recursion, if Guido van Rossum weren't so strictly opposed to the idea. (That is an obstacle that will soon have been overcome.)
And thus, any identifier has one, and only one, purpose, and hopefully an expressive name for it.
(Which would make the JIT compiler quite a bit simpler, too.)
As for confusing the assignment operator for the equality operator:
They could be the same operator with no ambiguity, but that would make chain assignments impossible.
But if you never re-assign identifier values, when would you need chain assignments?
For Python3 that is not an option of course, because it would break existing code.
But only RedHat is still hanging on to Python2. The rest of the world has long since moved on from this unsupported relic.
A new version of Python might even get proper versioning support.
I love the walrus operator. It’s made my code a whole lot cleaner
Can you give a non-contrived example of using it? Because I have yet to find one.
return {kw: _kw_indexes for kw in keywords if (_kw_indexes := find_occurrences(document, kw))}
This was a part of a function which takes a list of keywords and returns a dictionary containing the keywords and index occurrences. The function doesn’t add a key if there are no occurrences. Without the walrus operator you would have to repeat the search (which is expensive) or you would have to use a for loop instead of a generator. In this case the most natural solution is to use the walrus operator.
Lawrence D’Oliveiro See above. Also there were good examples in the video itself.
@@PythonPlusPlus This works for me:
return \
{kw : _kw_indexes
for kw in keywords
for _kw_indexes in (find_occurrences(document, kw),)
}
Lawrence D’Oliveiro yes I missed out the parentheses brackets. I realised after testing my code.
As a non programmer who subbed primarily because of astrophysics podcasts, I feel like I'll be taking Guido's side on this. It's pretty clear to me that PLIP PLOP 1337 operator assignment x + y + z + syntax BBC ABC ᕙ༼ຈل͜ຈ༽ᕗ == (51) pythons was a terrible idea and we need more hello worlds.
2:01 “In Python 3.8, all that gets combined into a single line.” *Writes two lines of code.*
Good addition. This is how lisp forms works by default, and it's a useful feature. The := syntax itself may be kind of ugly but something is necessary in a language like Python.
elegance is antithetical to simple and legible. reduced lines != better
Not necessarily. The most elegant solutions in my mind are all simple, short, and legible. If it isn't all of those, its not elegant.
Can somebody tell this to the Android devs using Kotlin?? I'm learning app development and i can't stand kotlin syntax
It's not "antithetical", it's just not necessarily always the case. More often than not shortness and elegance coincide. I wonder if torturing oneself to write bloatcode is a Python dev thing.
세종대왕 not more often. Clever code means code that maybe you understand, but doesn’t mean that other people will. Clever code is not teamwork code, it’s single work code.
this solves a problem I've hit dozens of times, where I want to store data but also immediately use it in a conditional. I'm not sure why people would throw a shit storm about it
Although python is a great programming language, the more I learn about python, the more happy I am to continue to write my code in ruby.
It's simply much more compatible with how I think and how my brain works.
It's not surprising that the walrus operator encountered stiff resistance among Pythonistas. It goes against the grain of the language. Pythonistas want their code to be as clear as possible, not as concise, as efficient or as pretty as possible. Any statement or operator that does more than one thing is automatically suspect. Furthermore, as stated in the video, there was already a perfectly good assignment operator and Pythonistas don't appreciate language redundancy, they want there to be only one way to do things. Guido should have decided against the walrus operator, no matter how many other languages have something similar. That's just the way Python should be. I would judge its addition to the language as a leadership failure.
Don't appreciate language redundancy? What about the three completely different syntaxes for formatting strings + string formatter module?
"This rule is included to simplify the choice for the user between an assignment statement and an assignment expression -- there is no syntactic position where both are valid. [...] Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions. Conversely, assignment expressions don't support the advanced features found in assignment statements..." --PEP 572
Isn't this just how the regular assignment operator functions in practically every other language? Even Java, which is notorious for excluding tons of common features that "lead to bad code", has an assignment operator that functions this way. I seriously don't understand why this is so controversial.
because it's fun to kick up a fuss
I think its good because it kinda acts a context manager for variables within conditions or loops.
I'm no Eric Weinstein but at first glance it looks like X is the answer to life, the universe, and everything.
Are you sure it isn't 42?
nice pull Doc!
Probably I’m the only one who rly loves it mainly because it allows me to do and if and asignation in the same line . Maybe it isn’t pythomatic etc etc but I quite enjoy it .
Lol what's going on in the Python world?! :D
Personally when I was trying to learn javascript by my own when I first started I couldn't these kind of instructions "x = x+1" because for me it was mathematically invalid. Then in high school we learned Pascal (for some reason we still teach Pascal here). I finally managed to understand that instruction but I don't know if it's because I had a teacher to help (a bad one though) or because Pascal used the := operator making it clear that it's actually assignment and not equality.
As for the operator itself, I'm not sure now. From a side I think that making this mathematically invalid notation is confusing but from another side I think that assignment is probably the I operation we do the most in programming so why make the operator longer ?
In the case of Python, I say why not have them both ? I mean C++ is full of features that few people use but those people love them and it's probably one of the things that make C++ great, the freedom of style.