Share

Python 3.9 new amazing features ?

Author: neptune | 25th-May-2021 | views: 110
#Python

Top Linux commands.

Newest features of Python 3.9?

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 newest features of Python 3.9 really amazing features here list of some features.

  • Union Operators in dict (PEP 584)
  • String methods to remove prefixes and suffixes (PEP 616)
  • Type Hinting (PEP 585)
  • Buildins like range, tuple, set, frozenset, list, dict are now sped up using vectorcall (PEP 590)

Note: PEP is a “Python Enhancement Proposal”.

1. Dictionary Union (Very Cool)

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.

2. String methods to remove prefixes and suffixes

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.

3. Type Hinting

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

4. Buildins like range, tuple, set, frozenset, list, dict are now sped up using vectorcall (PEP 590)

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.

Python3.8

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 👍.



Related Blogs
Best Python package manager and package for virtual environment ?
Author: neptune | 29th-May-2021 | views: 58
#Python #Anaconda #Virtualenv #Pip
Which is the best package manager for python and Virtual environment management using Virtualenv and Anaconda...
Will, AI kills developers and programmers job ?
Author: neptune | 05th-Jun-2021 | views: 47
#Python #Machine learning #AI
GPT-3’s performance has convinced that Artificial intelligence is closer or at least AI-generated code is closer than we think. It generates imaginative, insightful, deep, and even excellent content...
Python Built-in functions lambda, map, filter, reduce.
Author: neptune | 26th-May-2021 | views: 37
#Python
We are going to explore in deep some important Python build-in functions lambda,map,filter and reduce with examples..
Do you know Jupyter is now full-fledged IDE?
Author: neptune | 25th-May-2021 | views: 32
#Python #Jupyter
Jupyter is a widely used tool by Data scientists. So developers from institutions like Two Sigma, Bloomberg and fast.ai convert it into IDE lets see..
How to download video from youtube using python module ?
Author: neptune | 26th-May-2021 | views: 32
#Python
We will let you know how you can easily download the Youtube high quality videos along with subtitle, thumbnail, description using python package..
What exactly you can do with Python?
Author: neptune | 29th-May-2021 | views: 32
#Python
Well, it's a tricky question to answer because there are lots of application of Python. But, I will tell you about 3 main applications of Python...
How to extract Speech from Video using Python?
Author: neptune | 25th-May-2021 | views: 29
#Python
Simple and easy way to convert video into audio then text using Google Speech Recognition API..
View More