A new version of Python is coming! Soon, we'll be using it in our python projects. As of 20/07/2020 Python 3.9 is in beta version(3.9.0b4) and will release the full version of Python 3.9 pretty soon.
Enough of introduction. Let's get started and learn about the new features.
New features in Python 3.9
Dictionary merge and update operators
Python 3.9 introduces merge(|) and update(|=) operators in the dict class. If you have two dictionaries a and b, you can now use these operators to do merge and update them.
a = {1: "Sam", 2: "Alex"}
b = {3: "Daniel", 4: "Tom", 5: "Jimmy"}
You can use | to merge these both dictionaries.
c = a|b
print(c)
**[Output]**: {1: "Sam", 2: "Alex", 3: "Daniel", 4: "Tom", 5: "Jimmy"}
If both the dictionaries have a common key, then the output will display the second key-value pair.
a = {1: "Sam", 2: "Alex", 3: "James"}
b = {3: "Daniel", 4: "Tom", 5: "Jimmy"}
c = a|b
print(c)
**[Output]**: {1: "Sam", 2: "Alex", 3: "Daniel", 4: "Tom", 5: "Jimmy"}
For updating the dictionary, you can use the following operator.
a = {1: "Sam", 2: "Alex"}
b = {2: "Daniel"}
a|=b
print(a)
**[Output]: {1: "Sam", 2: "Daniel"}**
removeprefix() and removesuffix() string methods
In Python’s str class, the new update introduces new removeprefix()
and removesuffix()
methods.
You can remove the prefix from any string using the removeprefix()
method.
'HelloWorld'.removeprefix('Hello')
**[Ouput]: 'World' **
If the string doesn’t start with the input prefix, the copy of the original string will be returned.
'BaseTestCase'.removeprefix('Test')
**[Ouput]: 'BaseTestCase' **
If the string ends with input suffix, the output will look like string[:-len(suffix)]
.
'MiscTests'.removesuffix('Tests')
'Misc'
If the input suffix is empty or the string doesn’t end with it, the output will be a copy of the original string.
'BadTestCase'.removesuffix('Tmp')
'BadTestCase'
New parser
Python 3.9 uses a new parser which is a PEG-based parser. Previously, Python used LL(1). PEG is more flexible than LL(1) when it comes to building new features in the language. The official documentation says that this flexibility will be seen in Python 3.10 and later.
Type hinting
Python dynamically specifies datatypes to a variable. For static allocation of data types, type hinting is used. This was introduced in Python 3.5.
You can now use built-in collection types (list
and dict
) as generic types. Earlier, you had to import the capital types (List
or Dict
) from typing
.
def greet_all(names: list[str]) -> None:
for name in names:
print("Hello", name)
Now there is no need to call List
from typing.List
.
Top comments (0)