美文网首页
2020-10-04 Python 3.9

2020-10-04 Python 3.9

作者: 春生阁 | 来源:发表于2020-10-04 17:02 被阅读0次

The full release of Python 3.9 is just next week — 7th October 2020.
It’s clear that this version marks a breaking point from the old route of Python’s evolution, onto a new path. We’ll cover:

New Features
Type Hinting
String Methods
Dictionary Unions

New Features

Alongside these behind-the-scenes changes, we also get to see some new Python features!

Type Hinting

Way back in 2008, Python 3 introduced function annotations — the precursor of type hinting. It wasn’t particularly robust, but it was a start.

Following this, more features were added over time. But now, 3.9 brings all of these different features together with a tidy new syntax to produce the newest development to Python type hinting.

We can easily specify the expected data types of our variables. If we then write something that doesn’t make sense (like we pass a string to an integer) then our editor will flag the issue.

No errors will be raised (unfortunately), but it’s incredibly useful when working with complex code bases. Let’s take a look at the new syntax.

String Methods

Maybe not as flashy as the other changes, but I see it being used a lot. We have two new methods for removing string prefixes and suffixes:

"foo bar".removeprefix("fo")

[Out]: 'o bar'

"foo bar".removesuffix("ar")

[Out]: 'foo b'

Dictionary Unions

We now have two new operators for performing dictionary unions.
The first is the merge operator |:

a = {1: 'a', 2: 'b', 3: 'c'}
b = {4: 'd', 5: 'e'}
c = a | b
print(c)

[Out]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

And the update operator, which performs the merge in-place:

a = {1: 'a', 2: 'b', 3: 'c'}
b = {4: 'd', 5: 'e'}
a |= b
print(a)

[Out]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

相关文章

网友评论

      本文标题:2020-10-04 Python 3.9

      本文链接:https://www.haomeiwen.com/subject/nipnuktx.html