It’s time for a new version of Python, till 10-08-2020 beta Python 3.9.0b4 is available.
Note: Python 3.9 is under the development phase and not recommended for production environments.
We are going to explore the newest features of Python 3.9 really amazing features.
Here list of some features.
Note: PEP is a “Python Enhancement Proposal”.
Dict union will merge two dict together and return a new dict consisting of the left operand merged with the right operand. If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) will be in final dict.
>>> dict_1 = {'John': 100, 'Jonny': 200, 'David': 300}
>>> dict_2 = {'Elon': '500', 'Jonny': '400'}
>>> dict_1 | dict_2
{'John': 100, 'David': 300, 'Elon': '500', 'Jonny': '400'}
>>> dict_2 | dict_1
{'John': 100, 'Jonny': '200' 'David': 300, 'Elon': '500'}
Augmented assignment version of Union
Augmented assignment also works here, It is going to be similar like list += and list.extend, which accepts any iterable, not just lists.
>>> dict_1 |= dict_2
>>> dict_1
{'John': 100, 'David': 300, 'Elon': '500', 'Jonny': '400'}
>>> dict_1 |= [('Olivia', 900)]
>>> dict_1
{'John': 100, 'David': 300, 'Elon': '500', 'Jonny': '400', 'Olivia', 900}
But, Union will only work with dict operands.
>>> dict_1 | [('Olivia', 900)]
Traceback (most recent call last):
...
TypeError: can only merge dict (not "list") to dict
Dict union is not commutative
Union is commutative, but dict union will not be commutative(dict_1 | dict_2 != dict_2) There is precedent for non-commutative unions in Python
>>> {0} | {False}
{0}
>>> {False} | {0}
{False}
Dict Union will be Inefficient for pipe mapping
Giving a pipe operator to mappings is an invitation to writing code that doesn't scale well. Repeated dict union is inefficient:
>>> dict_1 | dict_2 | dict_3 | dict_3 | dict_4
It creates and destroys three temporary mappings. The same argument applies to sequence concatenation is also inefficient.
Speed comparison
Sequence concatenation grows with the total number of items in the sequences, leading to O(N**2) (quadratic) performance. Dict union is likely to involve duplicate keys, so the temporary mappings will not grow as fast.
If one expects to be merging a large number of dicts where performance is an issue, it may be better to use an explicit loop and in-place merging:
>>> new_dict = {}
>>> for dict in many_dicts:
... new_dict |=dict
Note: Dict union can lose data (values may disappear); no other form of union is lossy.
Python 3.9 comes up with two new methods, removeprefix() and removesuffix(), to work with various string objects. These methods would remove a prefix or suffix from a string, if present.
>>> "NeptuneWorld".removeprefix("Nep")
tuneWorld
>>> “NeptuneWorld”.removesuffix(“World”)
Neptune
It also work in case you want to removes multiple copies of prefix and suffix.
>>> web = “nepnepnepnepNeptuneworld”
>>> prefix = 'nep'
>>> while web.startswith(prefix):
>>> web = web.removeprefix(prefix)
>>> web
‘Neptuneworld’
Just like ltrim, trimprefix, etc."Trim" does in other languages (e.g. JavaScript, Java, Go, PHP) what strip methods do in Python.
Why these functions?
1.Less fragile:
The code will not depend on the user to count the length of a literal.
2.More performant:
The code does not require a call to the Python built-in len function nor to the other expensive str.replace() method.
3.More descriptive:
The methods give a higher-level API for code readability as opposed to the traditional method of string slicing.
We know Python is dynamically typed language, don’t need to specify the variable type. Since Python3.5 we can define the type of variables now in Python 3.9 it will show you what type of variable a function expect.
>>> def fun_add(val: int):
>>> return val+val
>>>fun_add(‘Hi’)
Hint: Expected type ‘int’ got ‘str’ instead
>>> def fun_add_dict(val: dict[str, int]):
>>> return sum(var(dict_key for dict_key in var)
>>> fun_add_dict({“one”:1, “two”:2}) # Run successfully
>>> fun_add_dict({1:1, 2:2})
Hint: Expected type ‘Dict[str, int]’, got Dict[int, int] instead
It introduces a new "vectorcall" protocol and calling convention. This is based on the "fastcall" convention, which is already used internally by CPython. The new features can be used by any user-defined extension class. Most of the new API is private in CPython 3.8. The plan is to finalize semantics and make it public in Python 3.9.
Assignment Expressions or the walrus operator
If you remembered then we have to calculate the expression out side of the conditional if or while or print paranthesis like:-
>>> print(x=1+1)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'x' is an invalid keyword argument for print()# if statement
>>> if x=1+1 in [2]:
File "", line 1
if x=1+1 in [2]:
^
SyntaxError: invalid syntax
>>> if x:=1+1 in [2]:
... print(x)
...
True
Now it not an issue we can use walrus operator ":=" to deal with the issue.
If you have any questions or suggestions, let us know in comment section. Follow us on social media for more such articles.
Thanks for reading!
anonymous | May 26, 2021, 11:21 p.m.
I like walrus operator 👍.