Share

Python 3.9 new amazing features ?

Author: neptune | 22nd-May-2022 | views: 739
#Python

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 the 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)
  • Builtins 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
How to extract Speech from Video using Python?
Author: neptune | 29th-Aug-2022 | views: 2347
#Python
Simple and easy way to convert video into audio then text using Google Speech Recognition API...
How to download video from youtube using python module ?
Author: neptune | 22nd-May-2022 | views: 1433
#Python
We will let you know how you can easily download the Youtube high quality videos along with subtitle, thumbnail, description using python package..
Mostly asked Python Interview Questions - 2022.
Author: neptune | 25th-May-2022 | views: 855
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...
Python Built-in functions lambda, map, filter, reduce.
Author: neptune | 22nd-May-2022 | views: 693
#Python
We are going to explore in deep some important Python build-in functions lambda, map, filter and reduce with examples...
Best Python package manager and package for virtual environment ?
Author: neptune | 15th-Apr-2022 | views: 627
#Python #Anaconda #Virtualenv #Pip
Which is the best package manager for python and Virtual environment management using Virtualenv and Anaconda...
How to reverse string in Python ?
Author: neptune | 16th-May-2022 | views: 513
#Python
We are going to explore different ways to reverse string in Python...
Will, AI kills Developer's jobs?
Author: neptune | 22nd-May-2022 | views: 511
#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...
Do you know Jupyter is now full-fledged IDE?
Author: neptune | 15th-Apr-2022 | views: 426
#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..
What exactly you can do with Python?
Author: neptune | 15th-Apr-2022 | views: 373
#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...
Deploy Django project on AWS with Apache2 and mod_wsgi module.
Author: neptune | 22nd-May-2022 | views: 322
#Python #Django
In this blog I use the AWS Ubuntu 18.22 instance as Hosting platform and used Apache2 server with mod_wsgi for configurations. We create a django sample project then configure server...
Core Python Syllabus for Interviews
Author: neptune | 11th-Jun-2022 | views: 292
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...
Introduction to Apache Spark
Author: neptune | 09th-May-2022 | views: 206
#Python #Apache Spark
Apache Spark is an open-source, distributed processing system that utilizes in-memory caching and optimized query execution for faster queries...
Datatypes in Python.
Author: neptune | 22nd-May-2022 | views: 192
#Python
Python have different types of datatypes like Numbers, Strings, Lists, Tuples, Dictionary, Set, Frozenset, Bool, Mutable, and Immutable...
Input and Output in Python
Author: neptune | 15th-Jun-2022 | views: 121
#Python
In this article, we will see how Python take input from user and How it display the output to user. First we cover input then output...
TOP 10 PYTHON DEVELOPER SKILLS TO GET HIRED BY FAANG COMPANIES
Author: neptune | 07th-Jul-2022 | views: 94
#Python
In this article, we will explore top 10 Python skills required to get hired in worlds top most companies. The FAANG companies which are Facebook, Amazon, Apple, Netflix, and Google...
Classes and Objects in Python 3 | OOP's
Author: neptune | 31st-Aug-2022 | views: 79
#Python
Object-oriented programming can model real-life scenarios and suit the development of large and complex applications...
Inheritance in Python | OOP's
Author: neptune | 05th-Sep-2022 | views: 25
#Python
Inheritance describes is a kind of relationship between two or more classes, abstracting common details into superclass and storing specific ones in the subclass...
View More