317 points · by est · 8y ago · 351 comments
while (bytes := io.get(x)):
and: [bar(x) for z in stuff if (x := foo(z))]
Every time Python adds an expression counterpart to an existing statement (lambdas, intensions, ternary...) there is a (legit) fear it will be abused.But experience tells that the slow and gradual pace of the language evolution combined with the readability culture of the community don't lead that way.
While we will see code review breaking materials in the wild, I believe that the syntax will mostly be used sparingly, as other features, when the specific needs arise for it.
After all, it's been, as usual, designed with this in mind: "=" and ":=" are mutually exclusive. You don't use them in the same context.
The grammar makes sure of it most of the time, and for the rare ambiguities like:
a = b
vs (a := b)
The parenthesis will discourage pointless usage.My bet is that we will see essentially rare but useful and expressive use cases in productions, which is exactly the goal.
Given the month of debates around this, I think it's a fine compromise.
Like many, I would have preferred the use of the "as" keyword instead of a new operator, since it's already used to bind things to names in imports, context managers and try/except.
However, the new syntax has 2 advantages: it reads the same way than the original operator, and it supports type hints out of the box.
while (bytes := io.get(x)):
Would currently be written: bytes = io.get(x)
while bytes:
And likewise: [bar(x) for z in stuff if (x := foo(z))]
is equivalently: [bar(foo(z)) for z in stuff if foo(z)]
Perhaps this is just my personal opinion but I don't really think the ":=" (or "as" for that matter) adds much in the way of clarity or functionality. I guess at the end of the day I am neutral about this addition...but if there isn't a clear upside I usually think it's better to have less rather than add more. while True:
bytes = io.get(x)
if not bytes:
break
...
which I think is objectively less readable.In the second example, you have an extra call to foo for every element of stuff. If foo(z) is expensive, you'd probably want to write this as
[bar(x) for x in map(foo, stuff) if x]
instead - which I personally don't mind, but it's arguably not as clear as having the in-line assignment expression. bytes = next()
while bytes:
# do something ...
bytes = next()
It's possible to use while True and break, but that isn't very elegant. [bar(x) for z in stuff if (x := foo(z))]
is not equivalent to: [bar(foo(z)) for z in stuff if foo(z)]
because here, foo(z) will be called twice. If foo is an expensive operation or performs some other magic in the background that you don't want to call a second time, := lets you express this behavior without having to break your expression out into a huge for-if-append code block: output = []
for z in stuff:
x = foo(z)
if x:
output.append(bar(x))
Of course, the above verbose language might end up being a better code in the end, because mashing together a bunch of terse code is often not very readable. But in real life, transforming a comprehension into a loop is just a bunch of work that gets in the way of me trying to complete a task.When I'm developing out an idea and just want to see if the code works and passes my tests, I would rather have the option to insert behavior swiftly without having to reformat an entire block of code. Then when reviewing my code or deciding whether to make it reusable for something else, I can go back and clean things up.
[bar(x) for x in map(foo, stuff) if x]
I was just trying to be as close to the original as possible.I do find it odd you call out the calling of `foo` twice as a performance drain but then use the chief example of:
> When I'm developing out an idea and just want to see if the code works and passes my tests, I would rather have the option to insert behavior swiftly without having to reformat an entire block of code.
Tests are not something I (personally) consider to be performance sensitive. But like I said I am sort of neutral on this change. I don't really see a massive benefit to it, so I would personally air on the side of "don't add" but I'm not mad it's being added. It's a "meh" for me.
[bar(foo(z)) for z in stuff if foo(z)]
as [bar(y) for y in (z for z in stuff if foo(z))]
or even as [bar(y) for y in filter(foo, stuff)]
... although, I get that `map`, `apply`, and `filter` aren't generally considered pythonic.Overall, I think I agree with you - the new syntax in PEP572 might be handy, but it isn't necessary and I would say that the cognitive overhead of encountering yet another syntax doesn't justify the benefit, much less the technical overhead for the interpreter.
[bar(foo(y)) for y in (z for z in stuff if foo(z))]
(etc.) though, since `bar` takes as input the output of `foo`. This leads to the objectionable duplicate calls to `foo`, hence the new assignment expressions.I like Dunnorandom's
[bar(x) for x in map(foo, stuff) if x]
best for a correct result using existing syntax, or [bar(x) for y in (foo(x) for x in stuff) if y]
if you don't like `map`.What do you mean by "intension"? I haven't seen this referred to in python and googling isn't turning out anything useful (also spelling it as "intention").
The worst for me is OOP. In french it's POO, which, for obvious reasons, does not inspire confidence in an english reader.
From my reading of the PEP, assignment expressions specifically prohibit type annotations.
Someone showed me this in a previous thread:
>> [bar(foo_z) for z in stuff for foo_z in [foo(z)] if foo_z]
Not a common idiom, though. Neither snippet is perfectly clear to me, but yours is closer.
"This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr."
This comment is false. It should say
x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
"...assigns the single resulting object to each of the target lists, from left to right." https://docs.python.org/3/reference/simple_stmts.html#assign...Here is a demonstration of the difference:
>>> class Node: pass
...
>>> node = blue_node = Node()
>>> red_node = Node()
>>> node = node.next = red_node
>>> blue_node.next is red_node
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Node instance has no attribute 'next'If x, y, z are just variables, the order of assignments doesn't make any practical difference.
OTOH, complex assignment targets (such as "a[i]" or "a.b") are not supported for := assignments.
node = node.next = red_node
If assignments were right-to-left, the .next attribute would be set on the blue node.If they were left-to-right, it would be added to the red node.
The AttributeError exception shows it is the latter order.
If Python's gonna have breaking syntax, why not work on bringing it more in line with other modern languages that don't require special breakout syntax for expressions and rely more on functional features?
Are we still maintaining that lambdas are hard but suggesting expression-scoped variables are easy?
We maintain that list comprehensions do all the things lambdas can without the clunky anonymous functions. All while clearly communicating that a sequence is being transformed without any obscure syntax.
However lambdas are mostly discouraged because they're often harder to read for anything non-trivial (and really you can't do much non-trivial with them since they are so dwarfed) and you can just define a function in the same block and pass the function reference in place of a lambda. I think the premise is more that it's clearer to pass a clearly named method describing the intent instead of a lambda describing the how.
We can also see a migration away from list and object comprehensions in languages that support both them and lambdas (e.g., C#, Haskell).
How the Python community has maintained it's opinion that everyone else is stupid and wrong while also suggesting that their tooling is impossible to understand is beyond me. It seems like a contradictory position.
Or, as I like to call it, "The same lie they've been telling for a decade, that everyone knows is false because lots of people learn JavaScript and do not find it excessively complicated."
It's pretty rare that I write multi expression anonymous functions in js, and the language appears to be doing everything in it's power to make them wholly unnecessary.
First class citizen functions, short lambdas, comprehension lists, generators, map(), filter(), itertools, operator and functools are quite a rich toolbox already. But you won't have more. It's a choice.
The idea is to have enough to be productive, and not enough to be dogmatic. The experience of Guido, and it's one that I share, is that too much functional tooling drives a style that favors expressive writing at the expense of ease of reading.
It's not by chance that LISP and Haskell are considered hard languages to get into, while Python is considered easy to start with.
It has a cost, since no language is perfect, but that's the path this language follows and requesting a snake to fly will only bring you disappointments.
Python tries to strike the balance between the importance of a rich expressiveness and the non negotiable necessity of keeping the code readable: you read a line much more often that you write it, after all. It's a key philosophy of the language. It shaped and will shape numerous decisions around it.
This PEP is a perfect example : it tooks years for the concept to be integrated in Python, and the last debate about this concrete implementation took months. The result is a carefully crafted feature with a lot of details to discourage abuse and remove the needs for pondering when to use it or not.
This is absolutely dead on accurate. As a Clojure developer, using one of the most expressive -- dare I say, artistic -- programming languages ever created, I can say that I am totally in the zone writing code which is elegant and terse and really packs a punch, does clever things.... and then just a few days later, it is very hard for my own brain to parse my own code and figure out what it does.
For each line of code you write once, it will be read dozens of times by you or others. Code is for reading. Languages that get this right make things a lot easier for everyone.
and i think you are leaving out functional languages which share python's readability, if not surpass it, while remaining much more expressive. that's f# and ocaml.
f#, in my opinion, is superior in everyway to python and subsumes python's abilities of readability, easiness, oop, and scripting, while greatly raising the ceiling of possibility. it's criminally underused, especially in areas where python has been chosen.
and i disagree lisp is harder to get into. racket is just as easy to learn as python, if not easier, due to its regularity. the how to code / systematic program design course on edX and the book how to design programs showcases this.
The first thing I checked is your very vocal assurance that F# is a better scripting language than Python. That seemed very weird to me, after all it's Python strong point. Since I script a lot, I looked for the most popular F# lib to parse script arguments.
Argu seems the winner, according to http://fsharpworks.com/survey.html. Their tutorial is pretty good (https://fsprojects.github.io/Argu/tutorial.html), and here is their hello world. 24 lines of, packing a dense symbology and using a lot of the specific language features:
open Argu
type CLIArguments =
| Working_Directory of path:string
| Listener of host:string * port:int
| Data of base64:byte[]
| Port of tcp_port:int
| Log_Level of level:int
| Detach
with
interface IArgParserTemplate with
member s.Usage =
match s with
| Working_Directory _ -> "specify a working directory."
| Listener _ -> "specify a listener (hostname : port)."
| Data _ -> "binary data in base64 encoding."
| Port _ -> "specify a primary port."
| Log_Level _ -> "set the log level."
| Detach _ -> "detach daemon from console."
let parser = ArgumentParser.Create<CLIArguments>(programName = "gadget.exe")
let results = parser.Parse [| "--detach" ; "--listener" ; "localhost" ; "8080" |]
printfn "%A" results.GetAllResults();;
The same thing with click, the Python most popular solution, is 11 lines, and it's shaped around almost only regular calls and parameters: import click as cli, base64, urllib.parse as url
@cli.command("gadget.exe")
@cli.option('--working-directory', help='specify a working directory.', type=cli.File('rb'))
@cli.option('--listener', help="specify a listener (hostname : port)", type=url.urlparse)
@cli.option('--data', help='binary data in base64 encoding.', type=base64.b64decode)
@cli.option('--port', help='"specify a working directory.', type=cli.File('rb'))
@cli.option('--log-level', help='set the log level.', type=int)
@cli.option('--detach', is_flag=True, help='detach daemon from console')
def hello(**kwargs):
print(kwargs)
hello(["--detach", "--listener", "localhost:8080"])
I have a hard time finding the motivation to look for the truth behind your other arguments after that.The only dogmatic position here is the Python one, that based on opinion alone, and is leaving a lot of good structures out for no gain at all.
It's only because Python is familiar and Haskell is not. Objectively both Haskell and Lisp are dramatically more simple to comprehend than python.
On the other hand, you have a concept which translates easily to any language with first-class functions and lambdas. Even the syntax stays the same among languages which use "f(x,y)" for function evaluation and parameter passing.
/* This post is for those occasions when a list comprehension style is advocated over a functional style, which I know was not necessarily what you were doing in your comment. But I think the two points are valid enough on their own. */
Could you elaborate on that?
Which shouldn't be that surprising considering originally Netscape were going to port Scheme to their browser before choosing to create a new scripting language with "Java-like syntax" (you can argue amongst yourselves just how Java-like the syntax really is).
Imagine where we'd be if they'd just done that.
Smalltalk also uses ":=" for assignment and "=" for comparison. In Pharo, VA and Dolphin at least does what this Python proposal does - return the value of the last expression.
Python chose a different design trajectory - personally I can't stand it but it certainly follow some sort of internally consistent reason.
In my opinion the Python's explicit self argument is somehow cleaner approach than having distinct block and function/method types. You still need some kind of ugliness in order to implement super(), but for Python 3 that happens at compile time and the resulting syntax is reasonably sane.
As for the aforementioned method context issue CLOS/MOP takes interesting approach of macroexpanding the method definition into something like
(lambda (args next-method)
(labels
((call-next-method &args)
...
(funcall next-method ...)))
(impl (...)
... method body ...))
(funcall impl args)))
Also of note is that in ST, there are no control structures, even if is implemented as method on Boolean instances which takes block argument, with true and false being instances of True resp. False with different implementations of #ifTrue: method.The problem is that if you add blocks, then half of the added syntactic features the last decade is redundant as a block version would simply solve the problem a better. Which would create a lot of dead design, and that makes it a bad solution.
Are you maybe conflating blocks with chained iterator operations? Adding blocks to Python's current functional syntax would be pretty ugly. "foo.filter(bar).map(baz)" is nice even if you can only use named functions.
Python is designed in such a strangly arbitrarily inconsistent, hypocritical and opinionated manner.
Sorry, but it's preposterous to bring up an implementation detail of the standard library that has long been in the process of being fixed. CamelCase was deprecated a long time ago in favour of snake_case; what is left of CC is for backward-compatibility and will eventually disappear. This is all documented.
The standard library is not the language, it's much messier and suffers from all sorts of issues that have nothing to do with the language itself.
> preferably only one obvious way of doing it
I don't think that is true at all. Python allows you to perform many tricks, with overloading operators etc.
Pyhton is not really that kind of language.
from toolz import compose def foo(X):
if bar(foo):
1
FalseFirst of all you have indented 1 and False equally. Is that a typo? Or is it your opinion that the if should always consist of the if and the else branch without using the else keyword?
Secondly, if you want to return a value you need to use the return statement.
Also you wrote bar(foo) but foo was the name of the function, not the name of your parameter.
Perhaps what you are looking for is this:
def foo(x):
return 1 if bar(x) else False (define (foo x)
(if (bar x)
1
#f))
The returned value is the value of the last expression. No need for an else, or a return keyword. 'foo' if foo else 'bar'These examples in the PEP, they all seem bad to me, written to be too clever by someone who doesn't think well.
E.g.:
filtered_data = [y for x in data if (y := f(x)) is not None]
How about: filtered_data = [y for y in (f(x) for x in data) if y is not None]
Or just? filtered_data = filter(None, map(f, data))
(If f() can return non-None "Falsey" values then this would require a predicate function. But maybe f() is badly designed?)Or this:
if any(len(longline := line) >= 100 for line in lines):
print("Extremely long line:", longline)
What's wrong with the "old-fashioned" way? for line in lines:
if len(line) >= 100:
print("Extremely long line:", line)
break
Of course, in the bad old days when loop variables leaked I think you could just write: if any(len(line) >= 100 for line in lines):
print("Extremely long line:", line)
But I'm not sure, and in any event leaking loop vars was fixed at some point. (Good. It was useful but bug-prone. Just like this PEP!)To me this is also a mess:
results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]
It should be: results = [(x, y, x / y) for x, y in zip(input_data, map(f, input_data)) if y > 0]
Maybe all the examples are just poorly chosen, but I don't believe that. I think this PEP is just a bad idea. Badly bad.So, basically, they have a proposal for an expression that explicitly says "I want to leak this variable into the enclosing scope" and it is less useful than the implicit old way?
Python's variable scoping rules are a mess anyway -- some are function level, some are block level and I usually can't tell which is which until the compiler complains...
Goddamnit, I think you just changed my mind. :-)
I use Python the most so maybe I'm just used to it but I always found scoping pretty straightforward.
Do you have an example that you found surprising?
In C it's 100% clear, variables only live inside their respective blocks so if you want to mess with the value in an if-else you have to declare it outside of the block.
In the Python version, the new "(a := 1)" will stand out compare to the canonical "a == 1" as the ':' and '()' are unexpected here, and scream that it's not regular if test.
I made a flake8 plugin to forbid assignment expressions:
https://github.com/Korijn/flake8-assignexp
Will be released once python 3.8 is out and I can test it.
The alternative `f(x) as y` syntax looked nice to my eyes, and doesn't introduce new symbols. However I'm sure they are right, that it would have bad corner cases.
Before there were exceptions `if ($result = query())` was the cleanest error-checking approach.
Also PHP didn't invent that syntax in any way, but followed C (in the end early PHP was a simplified C created by a C programmer) it only later git higher level constructs making this less needed.
I very frequently use something like the following:
[node.find(SOME_XPATH).get("value") for node in tree if node.find(SOME_XPATH) is not None]
Which I can soon rewrite as: [found_node.get("value") for node in tree if (found_node := node.find(SOME_XPATH)) is not None]
There's a certain amount of complexity introduced, but I think removing the duplication makes up for it. This is one of the few remaining cases in Python where I feel like there's not a simple way to avoid repeating myself. found_nodes = (node.find(SOME_XPATH) for node in tree)
[found_node.get("value") for found_node in found_nodes
if found_node is not None]
or as a one-liner: [found_node.get("value") for found_node in (
node.find(SOME_XPATH) for node in tree) if found_node is not None]
It's 15 characters longer than your := version, at 110 characters instead of 95.For more advanced list compherensions, even JavaScript (ES6+) is more readable.
tree.map(node => node.find(SOME_XPATH)).filter(Boolean).map(node => node.get("value"))
I can deal with either language at this level of complexity. Anything more complicated needs more LoC in either language.
tree
.map(node => node.find(SOME_XPATH))
.filter(Boolean)
.map(node => node.get("value"))
I don't use Python on a daily basis, but I find that infinitely more readable than the comprehension version (plus, it's a syntax used in several major languages) [n.get("value") for n in filter(None, (node.find(SOME_XPATH) for node in tree))]
Or just: F0 = lambda node: node.find(SOME_XPATH)
F1 = lambda node: node.get("value")
result = map(F1, filter(None, map(F0, tree))) def F0(node): return node.find(SOME_XPATH)
etc. If you're binding the new function to a name anyway, why bother with `lambda` when `def` works just fine?map & filter work great when one can chain methods (no matter if via methods or %>% pipes like in R) and with decent lambda functions.
If a thing is uglier than in both JS and R... well, it is not a good sign.
tree.xpath(TARGET_XPATH) I beleive. Aa
Point is the comprehension is flawed to start with. If you need f(x) on both side, then f(x) should happen first, rather than doing it inside and assigning it. That requires a new user to know the if part (at the end) gets executed first, which is dirty.
That being said it's another example of how after many years it turns out that C got it right all along. Assignment being an expression (not a statement) makes many useful idioms possible. Sure, there was a problem with typos concerning '=' and '==' being similar but this was solved by convention of requiring parenthesis around assignment if its value is used as boolean. If you turn on warning in modern C compiler you will never make this error again. Interestingly it's also what Python has chosen even though they went with := operator.
Personally I prefer having one assignment operator and assignment being an expression. If it's := or = really doesn't matter in my view.
Hence the former can be used in contexts like "if x := 10: pass", which is the whole point of the PEP.
if ((int test = my_func_call()) == BLAH) { do_foo(); }
You could, but that would turn "syntactic sugar" into a useless phrase with arbitrary meaning.
The phrase "syntactic sugar" is usually reserved for language constructs which can always be rewritten, in-place, to some other construct in the same language, such that the semantics is identical (i.e. we can't tell which construct was used, unless we parse the contents of the file).
Python has examples like `foo += bar` being sugar for `foo = foo + bar`.
As an aside, your mention of "machine language" implies the use of operational semantics. That's where we say the "meaning" of a program depends on what it does to the machine when executed. That's fine, but it's not the only approach to semantics. In particular denotational semantics defines the meaning of a program by giving a meaning to each syntactic element of the language and their combinations, usually by rewriting them into some other, well-defined language (e.g. set theory). I much prefer denotational semantics, since it lets me 'think in the language', rather than making me 'think like the machine'.
Nitpick, but I don't think that's true – AFAIK they translate into different method calls.
`foo + bar` →`foo.__add__(bar)`
`foo += bar` → `foo.__iadd__(bar)`
(note the `i` in the second one)For example, import mod is NOT defined as
mod = eval(open("mod.py").read())
but involves abstract load module operation, which is dependant on the environment.That's why := is just syntactic sugar; there are no new semantics.
There seem to be new semantics in the interaction with comprehensions, which is one of the main sources of controversy in the discussion these linked as the OP.
I don't think that's right; what expression/statement is `x := y` equivalent to? I'm thinking in particular about using mutable collections to emulate assignment in a lambda, e.g.
>>> counter = (lambda c: lambda: (c.append(c.pop() + 1), c[0])[1])([0])
>>> counter()
1
>>> counter()
2
>>> counter()
3
It looks like this could now be done as: >>> counter = (lambda c: lambda: (c := c + 1))(0)
Yet the semantics here are very different: one is pushing and popping the contents of a list, without changing any variable bindings (`c` always points to the same list, but that list's contents changes); the other has no list, no pushing/popping, and does change the variable bindings (`c` keeps pointing to different integers).Maybe it's equivalent to using a `=` statement, but statements are forbidden inside lambdas. Maybe the lambdas are equivalent to `def ...` functions, but what would their names be? Even if we made the outer one `def counter(c)...` the resulting value would have a different `func_name` (`counter` versus `<lambda>`).
Even the `if` examples that are scattered around this page don't seem to have an equivalent. For example:
if (x := foo() is not None):
do_something()
We can't "desugar" this, e.g. to something like the following: x = foo()
if x is not None:
do_something
The reason is that we're changing the point at which the binding takes place. For example, Python guarantees to evaluate the elements of a tuple in left to right order (which we exploited in the above push/pop example). That means we could write: if (sys.stdout.write(x), x := foo() is not None)[1]:
do_something
This will print the current value of `x`, then update `x` to the return value of `foo()`. I can't think of a way to desugar this which preserves the semantics. For example, using the incorrect method from above: x = foo()
if (sys.stdout.write(x), x is not None)[1]:
do_something
This isn't equivalent, since it will print the new value of `x`. Maybe we could float the `write` call out of the condition too, but what about something like: if foo(x) and (x := bar()):
do_something
We would have to perform `foo(x)` with the old value of `x`, store the result somewhere (a fresh temporary variable?), perform the `x = bar()` assignment, reconstruct the condition using the temporary variable and the new value of `x`, then `del` the temporary variable (in case `do_something` makes use of `locals()`).PS: I think this `:=` is a good thing, and writing the above examples just reminded me how infuriating it is when high-level languages distinguish between statements and expressions, rather than having everything be an expression!
The sugar is sprinkled on top of syntax, the stuff the parser deals with. Typing a += 1 instead of a = a + 1 is sugar because it parses the same. This assignment syntax seems different. IMHO.
Does not. One is addition, the other is in-place addition; they're different things and can behave differently. E.g. in "a += b" and "a = a + b", the former might not construct an intermediate object, but mutate the existing a.
Type inference is not.
I'd prefer more lines for readability reasons.
Python's indentation system was so nice for imperative programs. But it gets in the way when functional features are retrofitted. The "everything must be one big expression" style is a total mismatch to Python. The beauty is gone.
https://en.m.wikipedia.org/wiki/Zen_of_Python
For anyone who hasn't read the original PEP link, what do you suppose this does? Guess its meaning:
1.
if (row := cursor.fetchone()) is None:
raise NotFound
return row
2.Next guess the meaning of this - what does it look like it does?
row = cursor.fetchone()
if row is None:
raise NotFound
return row
Answers:The first does the second. The second doesn't need explanation. I literally don't need to tell you what it does.
(The two examples are from the link.)
Now you might think that this means I'm against this PEP.
But actually [EDIT: because I know there is a VERY high bar to being accepted into Python] to me it means this is going to save an incredible amount of time - it must be very good indeed to be accepted.
So if they decided to adopt it - sure, I'll use it. And I bet it's great in practice.
It's also super explicit. If you don't know what := does you will go look it up.
If Python is still driven by Python design philosophy and all that discussion, then this will be very helpful. It surely had a very high threshold to meet.
So at least according to Wikipedia it is a guide. Of course, whether it's applied in practice is a different matter.
It's a condensed definition of the philosophy and goals which went into python at that point. A guide to define the borders of the road to good python, but also a guard against those who wanna change the direction of this road.
So, my reasoning is that I surely must end up liking it, if it ended up accepted despite breaking every rule in the book. They wouldn't accept it for something that wasn't incredibly useful. My first impression is that it's incredibly ugly, unpythonic, and unreadable (what does it even do?), and this is pretty "obvious".
So arguing based on what I know about Python design philosophy, and the fact that this has been so deeply discussed, it must be absolutely fantastic.
I wouldn't think it's great (if you gave me the syntax), I'd recite all the Python Values it breaks -
https://en.m.wikipedia.org/wiki/Zen_of_Python :
- Beautiful is better than ugly.
Nope, this is very ugly.
- Simple is better than complex.
Nope, this isn't simple.
- Flat is better than nested.
Nope, this explicitly exists to let you nest something.
- Sparse is better than dense.
Nope, this explicitly exists to make code denser.
- Readability counts.
Nope: this is literally not readable. You don't know what the first code example I gave does. Normally with Python you just "write pseudocode and make sure you indent it properly."
- Special cases aren't special enough to break the rules.
This is a special case.
but here we get to the next rule, which trumps ALL of the above:
Although practicality beats purity.
- There should be one—and preferably only one—obvious way to do it.
This is broken, as now you can do it on two lines or one line.
- If the implementation is hard to explain, it's a bad idea.
It's kind of hard to explain, look at all our comments.
- If the implementation is easy to explain, it may be a good idea.
This isn't the case here.
I will grant that this is extremely explicit syntax. In this sense it is MUCH better than overloading = based on different contexts or something. As I mentioned above, anyone who sees := knows that it's a "known unknown" -- WTF is this?
So we are left with a single solitary Pythonic value:
- Practicality beats purity.
Based on this alone, I reason that it must be great to have been accepted. It must be extremely practical. It must save a lot of time.
I am quite disposed to thinking (honestly!) that it must be pretty darn great. It will save a lot of time.
There's no way that it made it into the language if it didn't, since it's so obviously ugly and unpythonic.
But practicality beats purity. I'm sure I'll love it!
if reductor := dispatch_table.get(cls):
rv = reductor(x)
elif reductor := getattr(x, "__reduce_ex__", None):
rv = reductor(4)
elif reductor := getattr(x, "__reduce__", None):
rv = reductor()
else:
raise Error("un(shallow)copyable object of type %s" % cls)
especially when you compare it to the existing implementation: reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(4)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error("un(shallow)copyable object of type %s" % cls) # Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
What about filtered_data = [(y := f(x)) for x in data if y is not None]
will that work also?Attempted guess at answer: no, because the "gathering" part of the comprehension is downstream of the "sequence construction" part of the comprehension in the language implementation. But if that's so, I'm a bit concerned that this will be confusing to users.
I'm thinking it could look like this:
import numpy as np
def M1 %*% M2 with same precedence as *:
return M1.matmul(M2)
foo_matrix = np.matrix([[1,1],[1,1]])
bar_matrix = np.matrix([[2,2],[2,2]])
print(foo_matrix %*% bar_matrix)
Also, it would be nice to have a pipe operator `%>%` such that foo %>% f()
is equivalent to f(foo)
The alternative is to make f a method of foo, and then you can write foo.f()
But what happens if I don't want f to be a method? I just want the style of writing the f after the foo, but I don't want the baggage of OOP. Is that anti-Pythonic?I think anything general would probably be considered as cluttering up the grammar or non-pythonic. Completely custom unicode operators was something I loved about Swift (open to abuse, but really useful in moderation).
In toy examples, you can see all that because they'll show the declarations.
Here's a case[1] trying to explain monads by showing a simpler example:
parseP5_take2 s =
matchHeader (L8.pack "P5") s >>?
\s -> skipSpace ((), s) >>?
(getNat . snd) >>?
skipSpace >>?
\(width, s) -> getNat s >>?
skipSpace >>?
\(height, s) -> getNat s >>?
\(maxGrey, s) -> getBytes 1 s >>?
(getBytes (width * height) . snd) >>?
\(bitmap, s) -> Just (Greymap width height maxGrey bitmap, s)
Is all that left or right associative?Generally, to read an expression when you have custom operators, you have to dig up the associativity and precedence. That's why I see many newer libraries avoiding custom operators, [2] vs [3].
I think you can do custom operators in a language, you just need to require that the associativity and precedence be declared in import. I'd also have named levels of associativity, so maybe:
import MyModule.Foo.Bar (op(!$!, additive, right), ...)
Now, that's some boilerplate in your imports, but for readability, it'd be huge. And automated tools can tweak stuff like this.[1] http://book.realworldhaskell.org/read/monads.html
[2] http://hackage.haskell.org/package/pretty-1.1.3.6/docs/Text-...
[3] https://hackage.haskell.org/package/prettyprinter-1.2.1/docs...
Operator overloading in general only seems to be practical for mathematical types like sets or sequences where the rules are well-defined thanks to generations of people thinking about them. Yet, even the set case works poorly for C++ because in addition to associativity new operators also inherit the built-in operator precedence rules. For example should * take precedence over + in set operations? (Assuming you implement * for cartesian product and + for union.)
Maybe C++ has changed since I used it but this sort of thing really gets in the way of writing correct code.
You can absolutely define a pipe operator to apply functions. Something like
class Pipeable(object):
def __init__(self, f: Callable):
self.f = f
def __or__(self, other: Callable):
return Pipeable(other(self.f))
Then use it like composed = Pipeable(foo) | f
Replace `|` with `>>` if you feel that conveys what you want better. Libraries already exist which provide this interface.>Is that anti-Pythonic?
In a sense, yes. Operators and methods are defined in terms of objects, not in terms of abstract types.
foo%$%bar %>%>% f()
is equivalent to (f(foo(bar)), f(bar(foo)))
I'm just kidding, but please no more cryptic symbols in Python's syntax, if it can be solved with functions instead. We have other languages to scratch that itch.I haven't read the PEP, so I don't know the trade-offs, but I'm not loving this (:=) syntactic sugar either.
with file := open('filename'):
data = file.read()
instead of with open('filename') as file:
data = file.read()
I don't know how I feel about this. x = open('filename')
x.closed # False
with x:
print(x.readline())
x.closed # True
I think you're right. I prefer the `as` variant for readability. def __enter__(self):
return self
which is a common pattern (used by open()), but there's no requirement that __enter__() return the same object.In cases where __enter__() does something different, the assignment expression and the 'as' variable would have different values (the object of the 'with' statement, x, and the result of calling x.__enter__(), respectively).
One main reason in my opinion as to why Python 2.7 stuck around for so long was that everyone agreed that it was the last stable version of Python 2, and the devs could make Python 3 changes without worrying significantly about backward compatibility. I've been using Python3 since Python 3.3 but have had to write code that was Python 2 compatible for large code bases for about 5 years because I knew colleagues / users of my packages would not upgrade. This meant using a select subset of features in Python 3 that had been backported to a version of Python 2.7 that I knew I could get my colleagues / users to upgrade to. It has been great to watch the language evolve and Python 3 really gets a lot of things right, but adding breaking syntax features every minor release is extremely annoying. I have to have a mental checklist of all the different possible subsets of features I have access to given a minimum version of Python I want to support. I've spent the last couple of years in my professional career converting large Python 2 only code bases to Python 3.3+. But if someone wants to use async, I need to bump the minor version. If someone wants to use type hinting I have to bump the minor version. If someone wants to use f-strings I have to bump the minor version. If someone wants to use data classes I have to bump the minor version. It's nuts (to me anyway)!
This sounds rant-y but I genuinely want to know what other people are doing to mitigate this. I love Python! I have spent years advocating its merits. But thinking about large codebases in Python just worries me and the future doesn't look promising here. Are Python developers hoping that once 2020 arrives they'll have a stable Python release and work on Python 4. We'll have the Python 2/3 split all over again!
My personal opinion is that Python needs an officially maintained translator for the latest Python features back to older versions. My current favorite package is py-backwards [0] but it is rather unmaintained at the moment.
You seem to be annoyed by lack of forward compatibility.
With 2 vs 3 there were a large number of breaking changes, so effort spent adding new features to the 2.x lineage made sense. But if you're not able to get someone to update from 3.6 to 3.7 for dataclasses, is a 3.6.7 that supports them [but doesn't reserve 'async'] likely to be any different?
> Are you using features that are only available in the version of Python all your colleagues / users have access to? Are you using the latest version of Python and hoping your colleagues and users can upgrade to that version of Python?
If you have access our software, you have access to http://python.org -- that's never the issue.
For colleagues... everyone has 3.6.4-3.6.6 on their work computers unless they've actively prevented it.
We don't have anything using python for external users. If we did, I wouldn't want to assume that they already have python installed at all. I'd be inclined to look into PyInstaller for distributing that, and then we could depend on whatever version we wanted.
Yes, and in situations where I can't do that, I use only the features available in both versions. Currently most of the code I write is python2.7 and python3.6 compatible. Its not that difficult to do so.
Things have gotten much better, thankfully. Python 3 (and 2) have been tweaked over the years to make it much easier to write code that will work on both Python 2 and 3, and to make it easier to tweak existing code so that it will work on both. As a result, it's possible to transition code a file at a time, or even a portion at a time, instead of the impossible "all at once" transition. Almost no one used Python 3 after it was released, or for a number of years later. Now that the developers of Python have started to make transition practical, people have started transitioning.
Still, it takes real effort to transition to Python 3, and many people have "real work" to do instead of transitioning language versions without any real benefit. "3 is larger than 2" is not a real benefit. A real benefit is something like "this transition will radically increase performance" - and no one is claiming that Python 3 has a real-world advantage like that over Python 2. "Python 2 will eventually be unsupported" is a problem, but no one is providing free money to do the transition, so for many people it's just a fact.
Historically Python has been very good about supporting backwards compatibility and smooth upgrades. I hope that the Python 2->3 transition was an anomaly. You can make changes to languages, but you have to make it easy for users to do the transition.
Additionally, Python3 is only really usable for the more professional audiance since 2-3 years ago. Before that they were busy with stabilizing Python3, porting popular libs, portling less popular libs, or creating replacements for dead libs.
Once they actually, truly, genuinely really do properly drop support for python 2.7, maybe I'll be forced into doing something about it.
It’s still pity that Python 3 isn’t more adjusted to that fact.
- libs not available for Python 3 (this is a big problem for some people)
- codebase work and don't need/want any evolution Python 3 provide
- fear of Python 3 being unstable (that was legitimate during the first few Python 3 versions, not that much anymore)
There are probably more.
There's nothing technically compelling in Python 3. It's all developer candy.
Python 2 is going to remain stable for years, even decades. It's FORTRAN. Development on the C interpreter will stall, but what that really means is that it will become asymptotically bug-free. If no one is touching the code except to apply bug-fixes there are no sources of new bugs (okay bug-fixes will introduce bugs themselves, but the net trend will be negative.)
Even if you have to use e.g. Tauthon (a Python 2 that brings in a few select features from 3) you can still expect a more stable environment than Python 3 development.
And there are a lot of Python 2 runtimes and other places where Python 2 syntax is still welcome: Stackless, Pypy, Cython, Nuitka, MicroPython, Brython, etc... Python 2 hasn't gone anywhere.
Frankly, I think it's a damn shame IMHO that the Python 3 interpreter can't run Python 2 code! Not even with a command line switch. It should be able to switch syntax per module/file at least.
Anyway, to repeat, to me Python 3 is full of dubious toys for developers but has no compelling business value to drive adoption. It's cannibalizing the Python 2 community and ecosystem, but without that nobody would use it. It's not better than 2, just different.
If you were to start a new project and had to decide on a language, you would be better off (IMHO) with Rust or Go (or Python 2) than Python 3, generally speaking.
Let me turn the question on it's head: Python 3 adopters, can you give me a reason, a technical reason, why I should chose P3 over P2 for any project?
I'll throw out some things right off:
Performance. No. If you're using Python and worried about performance you've already committed stupidity and I'm not interested. Cython is your friend.
Async. No. I write Twisted code. Async has been done. Adding keywords to the language is stupid. (As an aside, I know Twisted is hard to use, and the docs sucked until recently, but it is a damn fine code base, written by really good and committed people, and it's an unsung under-appreciated treasure chest! Any Python networking code that does anything serious and doesn't use Twisted is probably doing too much work, poorly. The last thing the language needed was "async" as a keyword. "Foooooootguuuuuuun Jenkins!")
F-strings. No. More stupid and there are dozens of libs that do it.
Support? No. I can maintain the P2 code on my own if need be, but I don't need to because there are others, e.g. Tauthon, etc.. and I can support them. Plus as I said above, with no innovation comes no new bugs!
Type hints et. al. Ummm..., No. I was really stoked about this, but the first time I tried to use it (MyPy) I immediately broke it. I was doing things with the default keyword argument dict that just couldn't be represented in the type language. Valid useful Python code that the types can't handle is a thing. I like strong types, but Python has never benefited from over-nicety in typing. Quack, quack. Put another way, the coercive-type subset of Python is great but overly restrictive. (Which is not inherently bad, I think Elm-lang is brilliant!)
I love Python 2 because it has such a clean syntax, it deals sensibly with all the little fiddly bits that e.g. C makes you think about, and its semantics are powerful and flexible but elegant enough that you can hold the model (or a reasonable homologue) in your head.
From my POV Python 3 just messes up 2. I see no compelling technical reasons to use 3.
Perhaps not yet, but soon enough, sure.
The year is 2025. You want to set up a webserver to do something in python2. The Letsencrypt api doesn't have official python2 bindings, SQLAlchemy hasn't provided any database interfaces for python2 in 6 years, and so you can't use recent versions of postgres without writing your own dbapi.
There's been a couple of major security bugs found in various system tools, and sane flags and defaults have changed as a result, but python2's standard library never updated to call them safely, so you're default insecure. And libraries like smtp and BaseHTTPServer don't support modern standards like HTTP3 and extended MIME types.
You're banking on all that maintenance being easier than porting to python3.7 or whatever (which in my experience is actually very easy once you know what you're doing, you can port a decently sized project in a day or so).
That being said, mypy supports type hints in Python 2 code, so that really just adds to your argument.
for n in range(100) if n%2:
print(f'{n} is odd number')
Does anyone know if there is a PEP covering that? for n in range(100):
if n%2:
print(f'{n} is odd number')
You proposal also leads to a more ambiguous grammar because the following is currently allowed: for n in range(100) if n%2 else range(n):
The ambiguity can be extended with multiple if's, compare: for x in range(10) if n%2 if n else range(n):
for x in range(10) if n%2 if n else range(n) else n**2:
A work-around would be to raise something akin to the "SyntaxError: Generator expression must be parenthesized if not sole argument" that occurs with expressions like "f(b, a for a in range(3))", but that's a lot of work just to save a newline, two indents, and ":", isn't it?My point is that it would be nice to have a consistent syntax for all for-loops, either being a part of a comprehension or standing on their own.
EDIT:
> You proposal also leads to a more ambiguous grammar because the following is currently allowed:
for n in range(100) if n%2 else range(n):
Not really, I gives me "NameError: name 'n' is not defined". Unless it is an 'n' defined in the outer scope, of course.A bit poorly. Compare:
>>> f(1, 2 for x in )
File "<stdin>", line 1
f(1, 2 for x in )
^
SyntaxError: invalid syntax
>>> f(1, 2 for x in r)
File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument
See how the first one gives the location of the error while the second does not? As I recall, this is because the first can be generated during parsing, while the second is done after the AST is generated, when the position information is no longer present.That's why the following:
>>> f(2 for x in X) + g(1, 2 for y in Y) + h(z**2 for z in Z)
File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument
doesn't tell you which generation expression has the problem.Yes, I meant that if 'n' is defined in an outer scope. The expression I gave is not a syntax error but a run-time error.
for n in filter(is_even, range(100)):
print(f'{n} is odd number')
for n in (i for i in range(100) if i % 2 == 0):
print(f'{n} is odd number')
Are there any points against these solutions other than verbosity? def odd_range(count):
return (x for x in range(count) if x%2)
for n in odd_range(100):
...
As for the second one, I'm just not too happy with the implied two loops (even if it amounts to only one in practice). for n in range(100):
if n%2:
print(f'{n} is odd number')
Only two more indents. What is the point of your proposed syntax?for odd_numbers in [n for n in range(100) if n%2]:
after a quick "stupid python" comment.
for n in [i for i in range(100) if i%2 == 0]:
print n
Will work (if a bit repetitive looking)Give me the `|>` operator plz
match1 = re1.match(text)
if match1 is not None:
do_stuff()
else:
match2 = re2.match(text)
if match2 is not None:
do_other_stuff()
Which is a bit clunky. you only want to evaluate match2 in case match1 fails, but that means a new level of nesting. Instead, with this proposal, you could do this: if (match1 := re1.match(text)) is not None:
do_stuff();
elif (match2 := re2.match(text)) is not None:
do_other_stuff()
Evaluate and assign in the if-statement itself. This is not dissimilar to the equals operator in C. In C, you would frequently find loops like
`while ((c = read()) != EOF) { ... }`. This would presumably allow a similar pattern in python as well.More information can be found in PEP-572: https://www.python.org/dev/peps/pep-0572/
if (a = b) /* Oooops, meant a == b! */
The use of "=" for assignment has long been a pet peeve of mine. It was a mistake when C did it, and it's been a mistake for so many subsequent languages to copy it.
"=" shouldn't be an operator at all, it makes a lot more sense to use ":=" and "==".
Pascal's use of ":=" for assignment and "=" for equality, strikes me as almost as clear.
Still, at least C makes consistent use of '=' for assignment, unlike that god-forsaken trainwreck of a language, VB.Net, which uses it for both assignment and for equality depending on context.
I like C way of assignment being an expression. I think having separate statement and then assignment expresdion is a mess. It's still useful though as Python was missing where keyword like feature from Haskell which is necessary to avoid duplicating computation in list comprehension.
def foo():
if n := randint(0, 3):
return n ** 2
return 1337
[(x, y, x/y) for x in input_data if (y := f(x)) > 0] def foo():
if randint(0, 3) as n:
return n ** 2
return 1337
which looks a bit better to me.[ {X, Y, X/Y} || X <- Some_Function (), Y <- Some_Other_Function () ]
And people bitch about Erlang syntax.
Edit: "/" is the division operator
if foo := bar[baz]:
bar[baz] += 1
return foo
else:
bar[baz] = 1
return 0
Where foo is a dict keeping track of multiple things, and a non-existing key (baz) is never an error but rather the start of a new count. Faster and more readable than if baz in list(bar.keys()):
....
Similar to Swift’s ‘if let’, it seems. m = re.match(r'\s*(\d+)\s*', args)
if m:
start = int(m.group(0))
end = start + 10
m = re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
if m:
start, end = map(int, m.groups())
With the new syntax this becomes: if m := re.match(r'\s*(\d+)\s*', args):
start = int(m.group(0))
end = start + 10
if m := re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
start, end = map(int, m.groups())
This pattern occurs just often enough to be a nuisance. For another example drawn from the standard library, here's modified code from "platform.py" # Parse the first line
if (m := _lsb_release_version.match(firstline)) is not None:
# LSB format: "distro release x.x (codename)"
return tuple(m.groups())
# Pre-LSB format: "distro x.x (codename)"
if (m := _release_version.match(firstline)) is not None:
return tuple(m.groups())
# Unknown format... take the first two words
if l := firstline.strip().split():
version = l[0]
if len(l) > 1:
id = l[1]collections.Counter is what you want for the counting case.
dict.get() + dict.setdefault() for the general case.
defaultdict is only useful if the factory is expensive to call.
try:
bar[baz] += 1
except KeyError:
bar[baz] = 1
Also you can check if a key is in a dict simply by doing "if baz in bar" no need for "list(bar.keys())", which will be slow (temp object + linear scan) vs O(1) hashmap lookup. while continue = "yes":
instead of: while continue == "yes":
Those mistakes introduce bugs that are hard to spot because they don't cause an immediate error, linters can hardly help with them and even a senior can make them while being tired.Code starts becoming a lot harder to reason about when more than one state is mutated on the same line. The good design of Python makes this harder than in say C and I think this is a step in the wrong direction in that regard.
The two real things this solves are checking for truthyness in an if and reusing values in a filterting comprehension. Instead of the syntax we have now that can be used anywhere, adds a whole new concept and feels kind of out-of-place, I would have much preferred a solution that can only be used in vetted places, doesn't add a new thing people need to learn and follows the style of the language
For example, my preferred solution for `if` would have been:
if thing() as t:
print(t)
Usage of `as` is already established by the `with` block [value for x in y
if value
where value = x * 2]
The order is unfortunately a bit weird here, but there is no need to add the whole concept of a different type of assignment and this syntax will feel instantly recognizable to people familiar mathematical notation, which is where the existing list comprehension syntax comes from and so has been established as well.This PEP solves very little problem, saves a few characters of code, but adds complexity to readability.
Short version.
(x =: y) is an expression that:
1. assigns the value y to the variable x
2. has the value y.
So `print((x := 1) + 1)` prints '2', and sets x=1.
A ton of languages [eg: c, js] have '=' work this way. And a ton of style guides for those languages tell you to avoid using it like that, because it's confusing. So this is a bit controversial.
E.g.
if(x:=f() is not None):
print(x)
You can read more about it here: https://www.python.org/dev/peps/pep-0572/ if (x := f()) is not None:
or as: if x := (f() is not None):The choice of := is to avoid accidentally using assignment where comparison is expected.
EDIT: also, I'm mentioning "in your opinion" because adding that to your own statements indicates that you're open to discussion. It's also good to use it as a reminder to yourself (speaking as a former physics student, and most people who know physics students will agree how "absolute" and unintentionally arrogant they tend to be in their claims until they learn otherwise).
I'm sure your coding experience was frustrating, and I'm sorry to hear that, and I understand that we all need to vent sometimes, but trying to staying open to other viewpoints is better for your own sanity, wisdom, and social connections in the long run.
sorted(enumerate([('a', 1), ('b', 2)]), key=lambda (i, (k, v)): (k, i, v))
in Python 3 drives me nuts. They could fix this. It worked in Python 2.You could do this, although it's admittedly uglier than your example:
In [1]: sorted(enumerate([('b', 1), ('c', 3), ('a', 2)]), key=lambda x: (x[1][0], x[0], x[1][1]))
Out[1]: [(2, ('a', 2)), (0, ('b', 1)), (1, ('c', 3))]
However, if you're flexible about the ordering of the resulting tuples, this seems clearer and reasonably painless: In [1]: sorted((x, i) for i, x in enumerate([('b', 1), ('c', 3), ('a', 2)]))
Out[1]: [(('a', 2), 2), (('b', 1), 0), (('c', 3), 1)]
I know that doesn't address your underlying complaint. This is mainly to note that the flexibility of Python tends allow a variety of approaches and that sometimes finding the clearest one takes some effort. ("There should be one obvious way to do it..." often does not hold, IMHO.)Is there a better example of something that is generally agreed to be "shitty" yet could be fixed in a clean way, without breaking backwards compatibility?
- Instantiating an object from a name in a string. Like instantiate a 'Foo' when you have a string variable that contains 'Foo'. I can't remember the syntax even though I looked it up two days ago, and I never will because it's such a shit show. Not to use PHP here as and example of a great language, but there at least the intuitive '$obj = new $var' works as you expect it. Or, in C++ you have to do it manually, which is also fine - at least be consistent.
- The weird sort-of typing of variables. Variables have types, but you can assign a different value of a different type to them, and the actual types usually doesn't matter except when it does. So you do print "Hey " + var but now you need to know what type var is because you might need to str() it.
- The whitespace-is-important-except-when-it-isn't. OK so braces are the devil's work, but when it's inconvenient, we're not that strict on white space (when initializing lists, when having expressions that span several lines, ...) so now everything can still look out of whack.
- .iteritems(). Really?
- super(ClassName, self).__init__(argument). Wut? Yes when I parse it token by token I understand, but why? Maybe the other magic methods are in this category too, but probably to a lesser degree.
- (I had some other things here about primitive OO capabilities, shitty package system/versioning, and some more, but those were all so far away from 'syntactic sugar' that they didn't fit this list no matter how hard I twisted the argument)
Look, I do understand why they are this way. For each of them, there is a reason that any reasonable person would say 'yeah that makes sense' to, possibly after some explanation of the history or context or whatever. But then at least be honest and stop promoting the language as so 'intuitive' or 'beginner-friendly' or 'much more clean than other languages'. Sure, it's not as bad as R, but it's still just like any other 20+ year old language in wide spread use - crufty, idiosyncratic in many respects, and in general requiring a bunch of frustrating head butting before you can be productive in it.
And to tie it to the OP - it seems this new syntax is promoted as being for 'beginners' or to make it 'easier to teach'. Well good luck with that, I say.
Python doesn't have specific syntax for that. It can be as simple as:
obj = globals()["Foo"]()
That assumes "Foo" is in your global namespace. If you don't care about security then you can do: >>> import math
>>> s = "math.cos"
>>> eval(s)(3)
-0.98999249660044542
If you care about security then you might not want to allow arbitrary objects, like "os.unlink" to be referenced. There are third-party packages which provide different models of how to get objects, like Django's "import_string" at https://docs.djangoproject.com/en/2.0/ref/utils/#django.util... ."The weird sort-of typing of variables. Variables have types,"
Variables have only one type, "reference to Python Object". An expression like 'var = "Hey " + var' may change the type of the value that var references, just like how 'var = var * 234.567' may change the type of the value that var references from an integer/long to a float, or "var = var * "Hey"', if var == 2, causes var to be a reference to the string "HeyHey".
".iteritems(). Really"
This was for a transition phase. It no longer exists in Python 3, where items() returns an iterator instead of a list.
"super(ClassName, self).__init__(argument). Wut?"
In Python 3 this is: "super().__init__(argument)", as in:
>>> class A:
... def __init__(self, s):
... print("A says", s)
...
>>> class B(A):
... def __init__(self, t):
... super().__init__(t*2)
...
>>> B("hello?")
A says hello?hello?
<__main__.B object at 0x10b201630>
"but it's still just like any other 20+ year old language in wide spread use - crufty, idiosyncratic in many respects"A reason for the oft-bemoaned backwards-incompatible changes to Python 3 was to remove some of the crufty, idiosyncratic language features that you rightly pointed out. You are still using Python 2.7, so cannot take advantage of those changes.
In PHP, a class is uniquely identified by its name, everywhere. If you define a class Foo, then new $var will resolve correctly either everywhere or nowhere (the name needs to be fully qualified, to avoid namespace headaches).
That's not the case in Python. A class Foo has the same status as any other object. That means you can't rely on its name - it could be replaced by another value. But it does mean you can pass the class itself around instead of its name. Instead of putting the string 'Foo' or the literal Foo::class into a data structure or an argument list, you can just put Foo in there, and call it later.
I think the Python approach is cleaner, but then again, it's what I already knew when I first learned how PHP did it.
Python doesn't need to instantiate classes based on string values, so it doesn't provide an easy way to do that.
Python almost allowing you to take the PHP approach is a bit of a pattern. Python is dynamic enough to let you do a lot of things you shouldn't be doing. Ugly syntax like globals()[var] is usually (but not always) a sign that you're looking for the wrong kind of solution.
Just leave it to those who have used Python for a while now and actually know what it's missing.
(as to your first point, if you'll allow me to be even more snarky and cynical as I already have been in this thread (might as well go all out now), the fictional 'pep' I would like to see most is 'method and apparatus to instill some realism and humility in the average Python advocate's conception and description of the language'. But here too I will freely admit that I'm probably susceptible to significant observation bias and/or bad luck, and that others could have radically different experiences from myself.)