Differences between Python 3.10 and Python 3.9 which you need to know !

Arnab Mondal 16 Aug, 2021 • 5 min read

This article was published as a part of the Data Science Blogathon

Introduction:

For the last couple of decades, Python has created a name for itself in the domain of programming or scripting languages. The major reason why python is being heavily favoured is due to its extreme user-friendliness. Python is also used to handle complex programs or coding challenges. Emerging fields such as Machine Learning(ML), Artificial Intelligence(AI), and Data Science are also feeding to the high demand for learning this language. As compared to traditional languages such as Java, C#, and other languages, Python is a robust programming language that has quickly become a fast favourite for developers, data scientists, and AI/ML enthusiasts.

Python 3.10 and Python 3.9 cover

Source: https://unsplash.com/photos/FCHlYvR5gJI

Python as a programming language has a number of use cases that draw in learners as well as experts in the IT industry. On a basic level, Python can be used as a programming language to practice data structure and algorithms or develop simple projects or games. The versatility of Python as a language allows its users to easily scale up their projects and create websites, software, or predictive models. Automation is taking over a majority of the IT industry and Python takes the lead as the favoured language used to automate tasks in data analytics or data science. Other than this, Python has a massive number of libraries and a robust community of programmers who continuously add more value to Python as a language.

 

Understanding Python and its Usecases:

One of the many reasons why beginners are drawn to python is due to its user-friendliness. Python has banished the feared semi-colon and uses a simple indented structure as its syntax. Python also finds a use case as an extension for applications that need a programmable interface. Some more benefits of Python include its most coveted feature that is its libraries. Python libraries are a vast resource that is used in a number of crucial code writing such as:

  • Regular expression-based codes
  • String handling
  • Internet protocols such as HTTP, FTP, SMTP, XML-RPC, POP, IMAP
  • Unicode
  • File systems and calculating differences between files
  • CGI programming
  • Mathematical modeling
  • Database queries
  • Data analytics
  • Data visualization
  • Automation codes

And all of these features are executable on many Unix, Linux, macOS, and Windows systems.

Analyzing the differences of Python 3.9 V/s Python 3.10

Over the years, Python has had a lot of upgrades and a lot of features have been added across the newer versions. Here, let us focus on two of the most recent versions that Python has added. Exploring the newer features helps you to work smoothly with it and of course, find a smarter way to work using newer libraries. All of the codes attached below are for educational purpose only and has been drawn from the original Python documentation that was released along with the new versions such as Python 3.9 and Python 3.10

Python 3.9 : 

IANA Time Zone Database

A new module named zoneinfo has been created in Python 3.9. This module provides you access to the IANA or the Internet Assigned Numbers Authority time zone database. This module, by default, uses the system’s local time zone data.

Code :

print(datetime(2021, 7, 2, 12, 0).astimezone())
print(datetime(2021, 7, 2, 12, 0).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z"))
print(datetime(2021, 7, 2, 12, 0).astimezone(timezone.utc))

Output :

2020-07-2 12:00:00-05:00
2020-07-2 12:00:00 EST
2020-07-2 17:00:00+00:00

Functions to Merging and Updating Dictionaries

Python 3.9 has added another cool feature that has attracted a lot of attention. Python 3.9 can now merge or update dictionaries using operators. The new operators i.e. ( | ) and ( |= ) have been added to Python 3.9 built-in dict class. You can access these operators to merge or update dictionaries using code similar to the ones tagged below.

Code :

>>> a = {‘v’: 1, 'art’: 2, 'py’: 3}
>>> b = {’v’: 'd’, 'topic’: 'python3.9’}

Code for Merge :

>>> a | b
{’art’: 2, 'py’: 3, ’v’:’d’,  'topic’: 'python3.9’}
>>> b | a
{’v’: 1,’art’: 2, 'py’: 3, 'topic’:’python3.9’ }

Code for Update :

>>> a |= b
>>> a
{’art’: 2, 'py’: 3,’v’:’d’}

 

Remove Prefix and Suffixes

String handling problems are easier to solve with the new features added to Python 3.9. The codes tagged below are used to strip the prefixes and suffixes from sample strings. The new methods used in the sample codes below are:

  • removeprefix()– this method is aptly named according to its function which is to strip off the prefixes existing in a given sample string.
  • removesuffix()– this method removes the existing suffixes from the sample string passed to it.

These new methods have been created to replace the older strip() method due to the negative reviews from programmers about its buggy nature. Tagged below is a sample code that can help you understand the implementation of the two new methods.

Code :

print("Victor is playing outside".removeprefix("Victor "))

Output:

‘is playing outside’

 

Using Type Hinting in Python 3.9 for Built-in Generic Types

The Python 3.9 release has enabled the support feature for the generic syntax for all standard collections which are currently available in the typing module. A generic type is often defined as a container, like for example a list. It is a type that can be easily parameterized. Usually, generic types have one or more types of parameters whereas a Parameterized generic is a specific instance of a generic data type with the container elements, for example, list or dictionary built-in collection types are the various types that are supported instead of specifically using the typing.Dict or typing.List

Code :

def print_value(input: str):    # Specifying the passed value will be of type String

By using the following way, we will be able to find if the following input is a string or not

 

Python 3.10 :

Using a Structural Pattern for Matching

A new feature called Structural Pattern Matching has been introduced in the brand new Python 3.10. This matching process operates along with the same match-case logic but it also compares against a comparison object to trace a given pattern.

Code for Python 3.9 :

http_code = "419"
if http_code == "200":
    print("OK")
elif http_code == "404":
    print("Not Found Here")
elif http_code == "419":
    print("Value Found")
else:
    print("Code not found")

Code for Python 3.10 :

http_code = "419"
match http_code:
    case "200":
        print("Hi")
    case "404":
        print("Not Found")
    case "419":
        print("You Found Me")
    case _:		#Default Case
        print("Code not found")

 

Improved Syntax Error Messages

Loads of programmers face difficulties in error matching or debugging their code. Python 3.10 has added a very user-friendly feature called Associative Suggestion which is tagged with Syntax Error messages. This helps you quickly find a fix for the codes which have a bug or error in them.

Code :

named_car = 77
print(new_car)

Output :

NameError: name 'new_car' is not defined. Did you mean: named_car?

 

Better Type Hinting

Upgrading from Python 3.9, we can assign multiple input types of a parameter without using the union keyword and by just using the OR symbol instead. It’s an easier way to define multiple input types for the same variable

Code for Python 3.9 :

def add(a: Union[int, float], b: Union[int, float]):

Code for Python 3.10 :

def add(a: int | float, b: int | float):

 

Improved Context Manager

Context Managers help with the handling of resources such as files. You can now use multiple contexts in a single block. This will highly enhance your code as you no longer need multiple blocks or statements.

Previous Syntax :

with open('output.log', 'rw') as fout:
    fout.write('hello')

Latest Syntax :

with (open('output.log', 'w') as fout, open('input.csv') as fin):
    fout.write(fin.read())

End Notes :

So now we have discussed most of the updates that are there in Python 3.10 and which you will be using the most. The introduction of a switch case was something that was anticipated by many and it is finally here. So let me know if this article helped you in any way and drop me a text if you want me to write about a particular topic in my next article or want to add some information to my existing ones.

Thank you for reading till the end. Hope you are doing well and stay safe and are getting vaccinated soon or already are.

About the Author :

Arnab Mondal

Data Engineer | Python, C/C++, AWS Developer | Freelance Tech Writer

Link to my other articles

The media shown in this article on the difference between Python 3.10 and Python 3.9 are not owned by Analytics Vidhya and are used at the Author’s discretion.
Arnab Mondal 16 Aug 2021

Just a guy who loves to code and learn new languages and concepts

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

sushil
sushil 15 Feb, 2022

thanks Arnab for writing n sharing. side note - you may want to fix the output of a|=b dictionary merge example.

Muruga Valavan
Muruga Valavan 08 Oct, 2022

Information given is pertinent, highly useful

Related Courses

image.name
0 Hrs 70 Lessons
5

Introduction to Python

Free

Python
Become a full stack data scientist
  • [tta_listen_btn class="listen"]