547 points · by sertsa · 6y ago · 263 comments
Now you can use list, dict, tuple instead of typing.List, typing.Dict, typing.Tuple.
The system has been rolled out slowly in general, without hasty changes to the core language.
There's a similar change coming in 3.10: https://docs.python.org/3.10/whatsnew/3.10.html#pep604-new-t...
def square(number: int | float) -> int | float:
return number ** 2
A TypeVar constrained to int and float, T = TypeVar('T', int, float), should be used instead to indicate that the return type is the same as the argument type, no?Wow, this is pretty exciting. Hope we also see match being accepted in Python 3.10, so this would make (for me at least) one of the best Python releases in years.
Why though? Even in 2.7, isn't the : type and -> type part just taken as annotation (that is, could just be ignored and not clash because it's a valid type)? Or was it some parser shortcoming?
If only they'd had that idea a bit earlier in the Python 3 life cycle...
One of the reasons was that `list[int]` could not be done, as that would refer to a list index. Same as you would do `my_var = [1,2,3]` `my_var[0]`
Therefore it was possible to use just `int` as a type.
From python 3.9 (unless you used from __future__ import annotations in 3.7+) type hints are not parsed "as python", at function definition time, but more or less as text. In 3.9 `list[int]` does not want an item from object `list` at index 'int' when using it as a type annotation.
The typing library did not have these issues because the `types` altered the way the objects worked. Probably (didnt check it!) by overriding __getitem__ and the likes.
I think it was the right choice.
from typing import List
List[int]
Now you can just write this: list[int]But humans do understand what a city is, and if they live in or near one they understand what the time is in that city, adjusting for any weird local political rules like "Daylight saving" because those rules affect their life.
It's the right granularity practically too. Can politicians decide that Dublin and Belfast are in different timezones? Yeah, it'd be difficult but I think they could make that happen. How about Queens and Brooklyn? Ahahaha No. The residents will defy any pretence that clocks change between one city block and the next, it would never stick.
Years ago we visited my wife's family in Columbus with some frequency, once we visited the Wal-Mart supercenter in Phenix City (yes, it's spelled way wrong) Alabama, which is right on the eastern border of Alabama, also next to the river. Since I worked in Wal-Mart Information Systems at the time, I had quite a bit of access and noted that the store's systems were on Eastern time, even though the entire state of Alabama is on Central.
Sure enough: https://en.wikipedia.org/wiki/Phenix_City,_Alabama "Phenix City lies immediately west across the Chattahoochee River from the much larger Columbus, Georgia and observes Eastern Time on a de facto basis (in contrast to the rest of Alabama, which observes Central Time) due to Phenix City's strong economic ties to Columbus."
The Olson Database is amazing; I've non-trivially interacted with it a number of times in my career.
Even so, the final, on the ground authority is the people who use and are affected by time zones.
Going from the example of "Europe/Lisbon", Valença and Tui have 1h of difference, but are located on the same longitude, <3km from one another...
- https://en.wikipedia.org/wiki/Valen%C3%A7a,_Portugal - https://en.wikipedia.org/wiki/Tui,_Pontevedra
Take Indiana. Indiana is in the US Eastern time zone, except for some places near the Illinois border, which are US Central. But Indiana also didn't observe DST until 2006 (although some counties did observe DST). Consequently, what could generally be described as three timezones (as in the MS timezone selector) is actually described as 11 timezones: https://en.wikipedia.org/wiki/Time_in_Indiana#tz_database
From what I understand, locals in Indiana actually refer to time simply as Eastern or Central (with non-observance of DST meaning you shift from Eastern in winter to Central in summer).
I found the Pendulum library [0] very intuitive when it comes to working with time. It makes it easy to do the right thing. For example, if you call `pendulum.now` it gives you a timestamp including your local timezone information. In other words, it preserves "the time on the clock on the wall", which is lost if you do what so many people do and just take UTC timestamps.
pendulum.now()
# DateTime(2020, 5, 28, 13, 32, 1, 303100, tzinfo=Timezone('Europe/London'))
Doing this in the standard library, or with pytz, is very unintuitive and often done incorrectly in practice.– zoneinfo
– dict update operators
– str.removeprefix and str.removesuffix
– “Any valid expression can now be used as a decorator. Previously, the grammar was much more restrictive.”
– “Python now gets the absolute path of the script filename specified on the command line (ex: python3 script.py): the __file__ attribute of the __main__ module became an absolute path, rather than a relative path.”
On the last one I rarely if ever use __file__ as a relative path and have definitely typed os.path.abspath(__file__) many many times.
Good lord, finally! The number of times I've tripped over this.
Because in the context of imports it does: https://docs.python.org/3/tutorial/modules.html#the-module-s...
> Note: On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is not added to the module search path.
"There have been repeated issues on Python-Ideas [2] [3], Python-Dev [4] [5] [6] [7], the Bug Tracker, and StackOverflow [8], related to user confusion about the existing str.lstrip and str.rstrip methods. These users are typically expecting the behavior of removeprefix and removesuffix, but they are surprised that the parameter for lstrip is interpreted as a set of characters, not a substring."
'prix fixe'.lstrip('prefix')
truncating 'prix fixe' to ' fixe'. "aaamap".rstrip("map") != "aaa"Pretty useful for DP interview questions when implementing top down.
See: https://docs.python.org/3.2/library/functools.html#functools...
(This is a great addition and I'm very excited for it. Just a little sore haha.)
I have mixed feelings about a 12 month development cycle. From the perspective of a library maintainer but not a core contributor, this seems like a headache to support up to five versions concurrently. I understand we want to avoid the Python 2.7 debacle, but seems pretty rapid no?
I seems to have worked out well but they only support the two most recent (stable) versions - https://perldoc.perl.org/perlpolicy#MAINTENANCE-AND-SUPPORT
- 3.1 in September 2018
- 3.2 in November 2018
- 3.3 in January 2019
- 3.4 in March 2019
- 3.5 in May 2019
- 3.6 in August 2019
- 3.7 in November 2019
- 3.8 in February 2020
- 3.9 in May 2020
- 4.0 in August 2020
I'm not saying that this doesn't cause headaches, but do we really want less progress?
disclaimer: I like Python and find it a lot more fun than C++, although C++/STL are getting better over time!
(Because the C++ program is too hard to write and doesn't come into existence!)
There is value to being able to say "I'm done" and walking away knowing my code will happily chug along for the next 20 years.
I don't understand why programming languages need to be released like other "software". I see it a lot for modern languages like Rust.
To me, a programming language should have a major revision only once in 5-10 years. All other changes should be performance improvements or implementation changes which do not affect the end user which in this case is the programmer.
As a former package maintainer I can assure you that every update of gcc breaks the build of some other package. And we are talking about C or c++, languages existing longer than Python and having much stronger backward compatibility story. And no one ever said that upgrade to recent gcc is a problem.
Iow there is hardly any up to date system which do not require constant maintenance.
If you use RedHat or CentOS I would highly recommend ius.us repo, it contains latest versions of python and it's pretty much all what's needed.
I can't say how much of a nice improve removeprefix() and removesuffix() is. lstrip and rstrip prefix and suffix trimming bugs crop up in people's code constantly. This seems like a nice change, especially since the alternatives are so ugly.
{**a, **b}
You could see this as an improvement.The dict literal with dict-splats conveys a sense of ordering that makes the behavior of taking values for overlapping keys from the lattermost dict make more sense to me.
I'm also a fan of the walrus operator. These are small, rare, clear, useful, idiomatic new features, in my opinion.
One frets that Python could become a victim of 'featuritis' as the devs try to shop for a new kitchen sink for each release.
But of course, both are very welcomed!
What do you mean by that? Can't we clear a list by doing:
L[:] = []
(useful when L is defined in another scope, or when you want to keep a reference to the same list object)Unfortunately it's not possible to search for "[:]", so pointers appreciated
if "foobar".startswith("foo"): "foobar"[len("foo"):] > "foobar".lstrip("foo")
"bar"
Of course, if the developer making this mistake tested with "foofbar" instead then they would realise their mistake. A more typical example of this type of mistake would be url.lstrip("http://"). > "foobar".lstrip("wooowweeezoweeef")
bar >>> "foobarbaz".lstrip("fo")
'barbaz' >>> {0} | {False}
{0}
>>> {False} | {0}
{False}A nice side effect is that bools can used with sum:
sum(x % 10 for x in range(1000)) >>> {1} | {1.0}
{1}
>>> {1.0} | {1}
{1.0}
>>> import fractions
>>> x = fractions.Fraction(1)
>>> {x} | {1}
{Fraction(1, 1)}
>>> {1} | {x}
{1}If you read the dict union operator "|" as something similar to "or", (like me), you are in for a surprise:
>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
What I expect is
>>> x | y
{"key1": "value1 from x", "key2": "value2 from x", "key3": "value3 from y"}
Are you also surprised when the original bitwise meaning of "|" does not return either of the two arguments?
>>> 5 | 3
7
Here's the same thing as binary: >>> bin(0b101 | 0b011)
'0b111' >>> bin(0b011 | 0b010)
'0b11'
Does the leading 1 come from the first argument or the second argument? It isn't really a sensible question for bits, since the 1s are indistinguishable. However the values in the hash table are distinguishable, so it's a valid question.Also, taking an example from another comment:
>>> {0} | {False}
{0}
>>> {False} | {0}
{False}
This is another example where the union operator is used, but here it picks the first value, rather than the second value.EDIT: Previously had a typo "3.8" instead of "3.9", my apologies.
It's a strange HN-ism that puzzles me - "OK, what's so important about Foo 3.14?" There is a rule that is (barely IMO) on point though in the posting guidelines you linked to:
> If the title begins with a number or number + gratuitous adjective, we'd appreciate it if you'd crop it. E.g. translate "10 Ways To Do X" to "How To Do X," and "14 Amazing Ys" to "Ys." Exception: when the number is meaningful, e.g. "The 5 Platonic Solids."
https://www.python.org/downloads/release/python-390/
> Release Date: Oct. 5, 2020
> This is the stable release of Python 3.9.0
I love python but these short release cycles can be really annoying.
sums = [s for s in [0] for x in data for s in [s + x]]
Why would you do "for s in" twice? Is that intentional? It would make more sense to me if the variables would have been different. And why would you want to add 0 to numbers?! Curious about a real world use case for this. sums = []
s = 0
for x in data:
s = s + x
sums.append(s)
`for s in [0]` assigns 0 to `s`, as an initial value. `for s in [s + x]` adds `x` to `s`. Both instances of `s` are the same variable, there's no shadowing going on. s
for s in [0] # for every s of 0 (there is only one)
for x in data # for every x in data
for s in [s + x] # s is s + x.
so s = 0 + x[0], then s = (0 + x[0]) + x[1], then (0 + x[0] + x[1]) + x[2] it results in an array of rolling sums.Edit: someone already answered, I am blind.
That's probably gonna be very useful when reusing types with different libraries (such as ORMs or serializers). I think anyway, gonna have to experiment.
I've always wonder why NotImplemented is used in a boolean context in the first place, iirc when it evaluates to True the overrided comparison now becomes a source of hard to spot bug
Compared to Python, good old Windows DLL hell looks like a paradise to me.
print "Hey, they brought back the print statement!"
print("But you can still call the print() function!")
print ("printing", "tuples", "works", "like", "python2")
It would be a massive QoL improvement and also accelerate Python 3 adoption.(I'd actually be OK with allowing keywords to be used as method/function names in general, but that's a more extensive change than
from __past__ import print_statement
)Removing it (and breaking compatibility in general with no easy workarounds) is one of the major footguns in Python 3 that drastically slowed its adoption and basically forked the language.
It's a prime example of ideology trumping usability and practicality, resulting in the waste of probably millions of programmer hours, and orphaning millions of lines of code in Python 2 programs and libraries.
Other languages have managed to evolve effectively for decades without breaking backward compatibility; it's disappointing and embarrassing that Python simply hasn't.
I’ve definitely run into issues 2to3 couldn’t automatically fix (encoding issues in some py2-only lib I needed to use IIRC), but upgrading print doesn’t really have much overhead.
1) it modified the file object's "softspace"
>>> class MyFile(object):
... softspace = "Hello"
... def write(self, s):
... pass
...
>>> f = MyFile()
>>> f.softspace
'Hello'
>>> print >>f, "spam"
>>> f.softspace
0
2) This wasn't a problem until >> was added, because of problem #2 - the print statement didn't originally let you print to anything other than stdout. Which meant that if you wanted to support writing to a file instead of a stdout then you had to re-implement print yourself.In practice, I've also found that having print as a function adds functionality because I can do things like:
print(*data_values, sep="\n")
which is a quick way to print each value in a list on its own line.