1. Anything that is in the world when you’re born is normal and ordinary and is just a natural part of the way the world works.
2. Anything that's invented between when you’re fifteen and thirty-five is new and exciting and revolutionary and you can probably get a career in it.
3. Anything invented after you're thirty-five is against the natural order of things.”
― Douglas Adams, The Salmon of Doubt
I stopped writing C++ at some point in 2008/2009 but I still keep track of it to some extent and I'm continually surprised by the nonsense that is introduced into the language. The whole RAII movement, for example, is just one massive band-aid on top of the previous mistake of allowing exceptions, etc..
It'd be mostly fine in the long run, but you have all these people using like 15% of C++ and complain about it all day long, making their libraries not usable from stuff that understands C (most of which have drastically improved on the whole paradigm). There's a solution here and it's not using whichever arbitrary percentage you've decided on of C++, it's realizing that there are way better languages with real interoperability in mind to talk about lower-level things.
FWIW, I tend to think of comparisons to Perl as being a lot like Nazi comparisons, only for programming languages. And I do think there's some wisdom to the Godwin's Law idea that the first person to make a Nazi comparison is understood to have automatically lost the argument.
It's just that, at this point, Perl is both so near-universally reviled, and so well-understood to be way too optimized for code golf, that any comparison involving it is kind of a conversation-killer. As soon as it shows up, your best options are to either quietly ignore the statement in which the comparison was made, or join in escalating things into a flamewar.
I've never regretted a Perl program that I wrote, used and discarded. And I've never been content with a Perl program I found I was still using a week after I wrote it.
IMO, the more complex a system is, the more fragile it tends to become. The same is true for programming languages. Features will clash with each other. You'll end up having 10 different ways to achieve the same thing, and it won't be obvious which direction to go.
Furthermore, I did my grad studies in compilers. I've thought about writing an optimizing JIT for Python. I really feel like CPython is needlessly slow, and it's kind of embarassing, in an age where single-core performance is reaching a plateau, to waste so many CPU cycles interpreting a language. We have the technology to do much better. However, the fact that Python is a fast moving target makes it very difficult to catch up. If Python were a smaller, more stable language, this wouldn't be so difficult.
Many have tried and failed, Google and Dropbox to name a couple, and countless other attempts.
Lastly, AFAIK, CPython's FFI API is actually more of a problem than the dynamic semantics of the language. You can expose Python objects directly to C code. That makes it very hard for a JIT to represent said Python objects in an efficient way internally.
I disagree with this, which is precisely why I prefer feature rich languages like Java or better yet Kotlin. It doesn't get much more readable than something like:
users.asSequence()
.filter { it.lastName.startsWith("S") }
.sortedBy { it.lastName }
.take(3)
Now try writing that in Go or Python and compare the readability.Probably before then too.
(He'd also written about that more at length in the 1990s in On Lisp, but many more people became acquainted with his language-design ideas in the 2001–2003 period, thanks to Lightweight Languages and his increasingly popular series of essays.)
Anyway, I'm talking specifically about the use of the identifier "it" in Kotlin, not implicitly or contextually defined identifiers in general, which are indeed a much more widespread concept, embracing Perl's $_ and @_, awk's $0 (and for that matter $1 and $fieldnumber and so on), Dyalog APL's α and ω, Smalltalk's "self", C++'s "this", dynamically-scoped variables in general, and for that matter de Bruijn numbering.
Compared to the existence of Perl, yes. Anyone who does any amount of Perl learns that $_ is the implicit argument ("like 'it'") to most functions. It's pretty much one of Perl's main deals. The talk has about 100K views on YouTube, which is pretty good, but Perl is in another league.
I think if you like this idea, you will really like the book. Better still, you can download the pdf for free.
[1] https://en.wikipedia.org/wiki/Anaphoric_macro [2] http://www.paulgraham.com/onlisp.html
users.asSequence()
.filter { user ->
user.lastName.startsWith("S")
}
.sortedBy { user ->
user.lastName
}
.take(3)Though I will conceed that I also find the fluent interface variant nicer.
sorted((u for u in users
if u.last_name.startswith("S")),
key=lambda u: u.last_name
)[:3]
If last_name is a function, which it often would be in Python, it gets better: sorted((u for u in users
if last_name(u).startswith("S")),
key=last_name
)[:3]
However, I think you probably got the sort key wrong if you're taking the first three items of the result. Maybe you meant key=abuse_score, reverse=True, or something.On top of the lessened readability, the Kotlin version makes it very easy to add, subtract, or comment out lines/actions which really helps when debugging. The Kotlin version is almost identical in structure to how you’d do it in Rust, Elixir, etc.
It should also be noted that Python would allow a more functional style, possibly leaving out the list comprehension.
The map filter chaining is obviously simpler, but python code is not that difficult and it's a no brainer task anyway.
It does contain a generator expression though, which is the same as a list comprehension in general structure, but slightly more confusing because it doesn't have the relationship to lists that square brackets in a list comprehension would have given it.
My point, though, was that not being able to tell the difference was a key "tell" that the comment author was not very familiar with Python — in some contexts, that would tend to undermine credibility in their comment (and then it would be rude to point it out), but in this context, it probably makes their opinion more objective.
Python is for the most part overrated when it comes to these things, IMO. It's a nice enough language but it's aged badly and has an undeserved reputation for concision, readability and being "simple".
The method chaining syntax and the query syntax are alternatives. I think most devs lean towards the former, considered to be cleaner... whereas the latter is probably easier to learn in the beginning, to those unfamiliar with piping/functional style - owing to its SQL feel-alikeness.
ReSharper would offer converting the latter to the former, and that's how I learned method-chaining LINQ back in the day.
users.apply {
asSequence()
filter { it.lastName.startsWith("S")
sortedBy { it.lastName }
take(3)
}
(totally untested)That's not universally true. C# has more features than Java but is generally easier to read and the intent of the code is easier to follow. The lack of features, like properties or unsigned integers, leads to Java coders creating much more convoluted solutions.
If languages with less features were universally better we would all be using C and BASIC for everything.
I can plainly see how these changes will actually make my code cleaner and more obvious while saving me keystrokes.
I also don't think these changes are very drastic. They're opt-in, doesn't break anything and looks to lead to cleaner code. I love the walrus operator (not so sure about the name, but hey. C++ is getting the spaceship operator... As has been said, naming things is hard). To me, the change of print from a statement to a function has been the hardest Python chamge over the years. Just too much mental momentum. Even though ive been on Python 3 for years, I still make the mistake of trying to use it as a statement. That said, I think it was the right (if painful) move.
I don't speak for everyone over 35, just myself.
Anecdote : i'm fairly young, but i've been involved with python long enough and traveled to enough pycons to be a bit jaded with regards to change within the language.
I'm fairly certain it's only due to the additional cognitive load that's thrust upon me when I must learn a new nuance to a skill that I already considered myself proficient at.
in other words : i'm resistant to change because i'm lazy, and because it (the language, and the way I did things previously) works for me. Both reasons are selfish and invalid, to a degree.
Yep, I entered the Python world with v2. I eventually reconciled myself to 2.7, and have only recently and begrudgingly embraced 3. Being over 35, I must be incredibly open minded on these things.
My understanding of Python will probably never be quite as good as my understanding of C, but I can live with that.
- Music That Matters: https://omny.fm/shows/kexp-presents-music-that-matters/playl...
- KEXP Song of the Day: https://omny.fm/shows/kexp-song-of-the-day
- All Songs Considered: https://www.npr.org/rss/podcast.php?id=510019
- KCRW Today's Top Tune: https://www.kcrw.com/music/shows/todays-top-tune/rss.xml
I’d argue it’s easier now to stay in sync than even when MTV was popular. MTV you needed a cable subscription and be sitting at a TV, now SiriusXM or Apple/Google/Spotify can stream it right to your phone laptop or tablet, and regular FM radio will play it on the local Top 40 station.
Anyone making this argument should be prepared to to accept every single criticism they make in their life moving forward can be framed as 'their resistance to change'.
This kind of personalization of specific criticism is disingenuous and political and has usually been used as a PR strategy to push through unpopular decisions. Better to respond to specific criticisms than reach for a generic emotional argument that seeks to delegitimize scrutiny and criticism.
The walrus operator makes while loops easier to read, write and reason about.
Type annotations were a necessary and IMO delightful addition to the language as people started writing bigger production code bases in Python.
Data classes solve a lot of problems, although with the existence of the attrs library I'm not sure we needed them in the standard library as well.
Async maybe was poorly designed, but I certainly wouldn't complain about its existence in the language.
F strings are %-based interpolation done right, and the sooner the latter are relegated to "backward compatibility only" status the better. They are also more visually consistent with format strings.
Positional-only arguments have always been in the language; now users can actually use this feature without writing C code.
All of the stuff feels very Pythonic to me. Maybe I would have preferred "do/while" instead of the walrus but I'm not going to obsess over one operator.
So what else is there to complain about? Dictionary comprehension? I don't see added complexity here, I see a few specific tools that make the language more expressive, and that you are free to ignore in your own projects if they aren't to your taste.
x = 0
do:
x += 1
while:
x < 10But I don't think having it all on one line would be that bad.
(Edit: Actually, I think I know what you were saying now, and those aren't quite the same thing as they need a line after them.)
I do think the condition on the next line isn't the way to do solve this problem though (and I don't think it needs solving, while True: ... if ...: break does the job).
do:
body()
body()
while x < 10
It's just a compound statement consumes the trailing while clause.Decorators already precede a function (or class) definition[2], and one alternative for the ill-fated switch statement[1] was to have switch precede the case blocks to avoid excessive indentation.
So there's plenty of precedent in the other direction.
[1]: https://www.python.org/dev/peps/pep-3103/#alternative-3
My main gripe is the indentation. Your code reads as if the while condition is tested after the loop finishes. What if the while statement was part of the loop and could be placed arbitrarily?
do:
body1()
body2()
while x < 10
body3()
IOW `do:` translates to `while True:` and `while x` to `if not x: break`.Addendum: I would also entertain forcing the `while` to be at the end of the loop -- as I'm not sure what this would do
do:
if foo():
while x < 10> What if the while statement was part of the loop and could be placed arbitrarily?
If you're open to that, I had thought this was a bridge too far, but:
do:
body1()
break if some_condition
body2()
continue if some_other_condition
Under that scheme, the semantics translate to: while True:
do_body
break
And, of course, the `break if` and `continue if` syntax would be general. do:
thing()
thing()
continue if condition
And you can now express "skip ahead" with a `break if X` as well. do:
thing()
thing()
if condition:
continueNo, f-strings handle a subset of %-based interpolation. They're nice and convenient but e.g. completely unusable for translatable resources (so is str.format incidentally).
F strings are obviously non-lazy, but _(tmpl).format(_(part)) seems fine?
% only lets you format the values you're given.
> and isn't something like Django's _(str) better anyway
They're orthogonal. You apply string formatting after you get the translated pattern string from gettext. In fact, Django's own documentation demonstrates this:
def my_view(request, m, d):
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
return HttpResponse(output)It's all about the culture. And Python culture has been protecting us from abuses for 20 years, while allowing to have cool toys.
Besides, in that release (and even the previous one), appart from the walrus operator that I predict will be used with moderation, I don't see any alien looking stuff. This kind of evolution speed is quite conservative IMO.
Whatever you do, there there always will be people complaining I guess. After all, I also hear all the time that Python doesn't change fast enough, or lack some black magic from functional languages.
I think this metric is grossly overestimated. Or your scope for "out there" is considering some smaller subset of python code than what I'm imagining.
I think the evolution of the language is a great thing and I like the idea of the type hints too. But I don't think most folks capitalize on this yet.
Of course, in a world of Python 2.7 still being a large code base and Python being used a lot for scripting, this will far from the truth for the entire ecosystem.
There is a bit of learning curve (because, well, it's not shell which is what most people are used to), and you do have to please the compiler before being able to run your script, but OTOH, you'll basically never have that "oops, I just deleted my working directory because I used a bad $VARIABLE" experience.
happy python programmer since 1.5, currently maintaining a code base in 3.7, happy about 3.8.
It was to allow only certain HTTP verbs on a controller function. A pattern adopted by most Python web frameworks today.
The "pow" example looks more like a case where the C side should be fixed.
There's plenty of situations where a named argument does not help, and encoding it can only hurt. It makes little to no sense to name the first argument to `dict.update` for instance. Or the argument to `ord`.
That, incidentally, is why Swift added support for positional-only parameters (though it has no concept of keyword-or-positional).
Yes, it limits your ability to rename a local variable, but that seems minor.
Swift's syntax is a lot more intuitive and consistent:
function(parameterWithImplicitlyRequiredLabel: Int,
differentArgumentLabel internalParameterName: Int,
_ parameterWithoutLabel: Int,
variadicParameterWithLabel: Int...)
which you would call as function(parameterWithImplicitlyRequiredLabel: 1, differentArgumentLabel: 2, 3, variadicParameterWithLabel: 4, 5, 6, 7)
[0] https://docs.swift.org/swift-book/LanguageGuide/Functions.ht...In reality, the 2.x releases had a lot of significant changes. Of the top of my head, context managers, a new OOP/multiple inheritance model, and division operator changes, and lots of new modules.
It sucks that one's language is on the upgrade treadmill like everything else, but language design is hard, and we keep coming up with new cool things to put in it.
I don't know about Python 3.8, but Python 3.7 is absolutely amazing. It is the result of 2 decades of slogging along, improving bit by bit, and I hope that continues.
Doesn't mean nothing good comes out of them, and if it's simplicity that motivates people then eh, I'll take it, but gosh darn the cycle is a bit grating by now.
Projects like qmail discovered the reason in a somewhat _harder_ manner. And yes, I'd argue Python is yet another case, as it grew _at least_ as complex as Perl.
Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp. - Philip Greenspun
The development has been going quite well:
There are lots of issues that are being fixed. Strange nitpicking on alpha software.
If I wanted a language with "only one way to do it", i'd use Brainfuck. Which, btw, is very easy to learn, well documented, and the same source code runs on many, many platforms.
ninjaedit: indeed https://www.python.org/dev/peps/pep-0572/#why-not-just-turn-...
The new operator (like many Python operators) can only be used in expressions (statements can contain expressions, but expressions are not a subset of statements.)
> The fact that there is now an operator that can only be used in certain statements just makes things more confusing
Because the “=” operator is the thing that defines an assignment statement. Even if this could be resolved unambiguously for language parsers, so that “statement defining” and “within expression” uses didn't clash, it would be create potential readability difficulties for human reading. Keeping them separate makes the meaning of complicated assignment statements and assignment-including expressions more immediately visually clear.
I think the major argument (at least, the one I see most frequently) is that the walrus operator does create readability difficulties for humans, which is exactly why many people view it as non-pythonic. This is one of the few times I've seen someone argue that ":=" makes things more readable.
This is in no way contrary to the argument that the walrus operator improves readability of expression assignments compared to using the same operator that defines assignment statements.
>>> locals()['a'] = 1
>>> a
1
If anything, the walrus operator allows for tightly-scoped assignment, which is good in my opinion. x = [1, 2, 3, 4]
def foo():
x[0] += 3 # Okay
def bar():
x += [3] # UnboundLocalError
def qux():
x = [5, 6, 7, 8] # Binds a new `x`. def bar():
x += [3] # UnboundLocalError
This is an especially funky one. x.extend([3]) would be allowed. Presumably x += [3] is not because it expands to x = x + [3]... However, the += operator on lists works the same as extend(), i.e. it changes the list in-place. 0 LOAD_FAST 0 (x)
2 LOAD_CONST 1 (3)
4 INPLACE_ADD
6 STORE_FAST 0 (x)
8 LOAD_CONST 0 (None)
10 RETURN_VALUE
So INPLACE_ADD and STORE_FAST are essentially doing x = x.__iadd__([3])Maybe it would have been better to only have a single := assignment operator to begin with. But it's a few decades too late for that.
For what it's worth, := is for expressions only. Using it as a statement is a syntax error. So there won't be a lot of cases where both are equally elegant options.
a = 17
print("a=", a)
print("a=" + str(a))
print("a=%s" % a)
print("a={}".format(a))
print(f"a={a}")
# python 3.8 =>
print(f"{a=}")
So many ways to do it...But, if it sounds like I agree with you, I actually don't. I feel that the Zen of Python has taken on an almost religious level of veneration in people's minds, and leads to all sorts of unproductive debates. One person can latch onto "there should be one obvious way to do it" and another onto "practicality beats purity" and another onto "readability counts." Who's right? All can be. Or none. All could be applied to this particular case.
The Zen of Python is just a set of rough heuristics, and no heuristic or principle in the field of software development applies 100% of the time, IMHO. <= except for this one ;)
print string.Template("a=$a").substitute(a=a)In cases like this, different ways to do it (all equally good) are needed to get a good coverage of different tastes in obviousness and different nuances in the task.
The point is not uniformity, but avoiding the unpleasant and convoluted workarounds caused by non-obviousness (thus making the language easy to use).
String formatting is not trivial: there is the split (sometimes architectural, sometimes of taste, sometimes of emphasis) between concatenating string pieces, applying a format to objects, setting variable parts in templates, and other points of view; and there is a variety of different needs (cheap and convenient printing of data, dealing with special cases, complex templates...)
You do know that this:
x := 1
Is going to be a syntax error, right? The walrus operator is not permitted in the case of a simple assignment statement. It's only in an expression.When is an expression allowed to have := in it, is
(x := 1)
on its own allowed? (x := 1)
is a valid (but poorly written) statement.But while there are now two ways of doing assignment, I wonder how often people will actually encounter situations where it's difficult to figure out which choice is better.
[0] https://www.python.org/dev/peps/pep-0572/#exceptional-cases
Every possible line of code has an alternate ugly way to write it. This isn't a valid criticism. Anyone who decides to start writing simple assignment statements like that deserves to be ridiculed for writing ugly code.
I just dislike that the simple syntax rule "any expression can be used as a statement" now has an exception.
I haven't been able to think of scenarios where that might have consequences (code generation or refactoring tools?) but that doesn't say much as I'm not that smart.
Edit: having looked at the cases that are disallowed, they remind me of generator expressions. Those are usually written with parens, that can optionally be omitted in some cases. := is the same except they can be omitted in so many cases that it's easier to list the cases where they can't.
I think a generator expression used as a statement already requires the parens, even though they can be omitted e.g. as a single parameter of a function call. So that's probably ok then.
> There should be one-- and preferably only one --obvious way to do it.
There are plenty of ways to do assignments. Walrus assignments are only the obvious way in certain cases, and in general there aren't other obvious ways. For testing and assigning the result of re.match, for instance, walrus assignments are clearly better than a temporary.
I can think of lots of nonobvious ways to do assignments, like setattr(__module__...)
Python is one of the least "only one way to do things" languages I've used. This even extends to its packaging system, where you can choose between virtualenv, pipenv, pyenv, etc. Same goes for the installation method too, do you want to install Python with Anaconda or use the default method?
As for my personal take on this feature: I think it's really useful. When web-scraping in Python, I oftentimes had to do this:
while True:
html_element = scrape_element()
if html_element:
break
sleep(10)
Now I can do this: while not html_element := scrape_element():
sleep(10) for html_element in iter(scrape_element, None):
this calls scrape_element() until it returns None, returning each value.And pyenv is just a version manager, like rbenv or nvm. I wouldn’t consider its existence confusing, not would I say being able to install something in more than 1 way has any relevance to the zen of Python!
Should Python create some cross-platform Uber-installer so that there is only one download link?
Regardless of what pyenv, the rest of my comment about the complexity of Python's tooling still stands. There's too many choices. I also seen people use pyenv as an alternative to virtualenvs, which is something I have never seen with nvm.
I don't understand why the Python community hasn't coalesced around a single solution to package management that has minimal complexity. It seems like pipenv is the solution, but there is controversy around it and it should have come several years ago. The fact that Python packages are installed globally by default is also pretty terrible, I much prefer it when applications bundle their dependencies. When I do `npm install --global`, the resulting program will always work, regardless of what other packages I have installed on my system.
> Any critiques on Python-the-language?
The point of my original comment was not to necessarily critique the Python programming language, rather it was to point out that adhering to the "zen of Python" is a lost cause because the language/development environment is not designed as a curated experience.
And my original comment did make points about Python-the-language. I talked about how there's many ways to do a single task in Python. One of the responses to it even proved my point:
"Prior to that you could use the special two-argument version of the `iter` function which makes it act completely different than the single argument version: <code sample>".
That unfortunately demonstrates my point.
This is one of the reasons I love Python. It's a great exercise to rewrite the same code imperative, recursive, with generators, with iterables, etc. Python is very good at supporting a wide range of programming styles.
Also, I can't bring myself to call it the walrus operator. Sorry, guys. I had a Pascal teacher ages ago who pronounced it "gets" and that has always stuck.
I do agree that Python is moving further and further away from the only-one-way-to-do-it ethos, but on the other hand, Python has always emphasized practicality over principles.