Python 3.9 new amazing features ?

Author: neptune | 27th-Jan-2023 | Views: 838

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}

>>> {False} | {0}

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")

>>> “NeptuneWorld”.removesuffix(“World”)

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

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


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)

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 | 01st-Dec-2022 | Views: 3101
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: 1851
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: 1059
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...

How to reverse string in Python ?
Author: neptune | 16th-May-2022 | Views: 909
We are going to explore different ways to reverse string in Python...

Python Built-in functions lambda, map, filter, reduce.
Author: neptune | 22nd-May-2022 | Views: 883
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: 832
#Python #Anaconda #Virtualenv #Pip
Which is the best package manager for python and Virtual environment management using Virtualenv and Anaconda...

Deploy Django project on AWS with Apache2 and mod_wsgi module.
Author: neptune | 22nd-May-2022 | Views: 689
#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...

Will, AI kills Developer's jobs?
Author: neptune | 22nd-May-2022 | Views: 634
#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: 582
#Python #Jupyter
Jupyter is a widely used tool by Data scientists. So developers from institutions like Two Sigma, Bloomberg and convert it into IDE lets see..

Core Python Syllabus for Interviews
Author: neptune | 11th-Jun-2022 | Views: 569
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...

Datatypes in Python.
Author: neptune | 22nd-May-2022 | Views: 340
Python have different types of datatypes like Numbers, Strings, Lists, Tuples, Dictionary, Set, Frozenset, Bool, Mutable, and Immutable...

View More