---
---June 25, 2020, 2:34 p.m.

What's new in Python 3.9

Table of contents

It is currently in beta (3.9.0b3), and in the future we will see a full release of Python 3.9. A few of the new features are just incredibly cool, and it will be awesome to see them in a full release.


We will cover the following points:

  • Dictionary concatenation operator
  • Typing
  • Two new string methods
  • New parser

Let's look at these innovations and how they can be applied.

Combining Dictionaries

One of my favorite features with good syntax. For example, if we have 2 dictionaries a and b that need to be combined, now we can use a special operator.

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

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

As well as the update operator |= to update an existing dictionary:

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

a |= b

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

If two different dictionaries have the same key, then use | :

a = {1: 'a', 2: 'b', 3: 'c', 6: 'одинаковые ключи'}
b = {4: 'd', 5: 'e', 6: 'но разные значения'}

print(a | b) # {1: 'a', 2: 'b', 3: 'c', 6: 'но разные значения', 4: 'd', 5: 'e'}

Updating dictionaries with generators

Another interesting thing about the |= operator is the ability to update dictionaries with generators that have a key-value pair:

a = {'a': 'one', 'b': 'two'}
b = ((i, i**2) for i in range(3))

a |= b

print(a) # {'a': 'one', 'b': 'two', 0: 0, 1: 1, 2: 4}

When trying to perform such an action with the | we'll get a TypeError because the operator only allows union with dict objects

Ошибка TypeError

Typing

Python is a dynamically typed language, meaning we don't have to specify the type of a variable. This behavior is normal, although it can be confusing at times. And then suddenly Python's flexibility becomes nothing more than an inconvenience.

Since version 3.5, we can specify types for variables, but this approach was somewhat cumbersome. The update changes everything, take a look at the example:

3.9 typing example No typing (left) with 3.9 typing (right)

In the add_int function, we clearly want to add numbers to each other (for some cryptic and inexplicable reason). But our editor does not know this, and it is quite normal to add two lines using the + operator - therefore, we do not see any comments from the interpreter.

Now we can specify the int type we want to expect in the function's input. And now the interpreter will report the error immediately.

We can also specify nested types, for example:

Example of using nested types

Typing can be used everywhere - and all thanks to the new syntax, now it looks much more beautiful.

Example of using nested types

Two new string methods

Not as important as the other innovations mentioned above, but still useful in certain situations. Two new string methods to remove prefix and suffix:

"Hello world".removeprefix("He") # "llo world"

"Hello world".removesuffix("ld") # "Hello wor"

New parser

Although this change cannot be overlooked in any way, it may well become one of the most significant ones for the future development of Python.

Python currently primarily uses the LL(1) parser, which reads code from top to bottom and left to right.

Right now I don't really understand how this works - but I can give you a list of a few problems with this method:

  • Python contains not only the LL(1) parser, for this reason some parsers work bypassing the existing system, creating certain difficulties.

  • LL(1) creates a restriction on Python's syntax (with no way around them). This Issue highlights that the following code cannot be executed with
    current parser (raised by SyntaxError):

with (open("a_really_long_foo") as foo,
      open("a_really_long_bar") as bar):
    pass
  • LL(1) breaks the left recursive parser. So a certain recursive syntax can provoke an infinite loop with a tree structure. Guido van Rossum, creator of Python, explains it here

All of these factors (as well as others I simply can't describe) have a forward-thinking impact on Python; they stop the development of the language.

A new parser based on PEG technology will give developers more flexibility to write code - something we'll start noticing from version 3.10 onwards.

Conclusion

That's all we can expect from the new version 3.9. If you can't wait to try out the new beta release - 3.9.0b3 - you can install it here

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 23, 2024, 3:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks