Python 3.9 vs Python 3.10: A Feature Comparison | Code Skills

The decade has seen numerous programming languages being developed and updated to make work easier in the programming domain and create the next Artificial Intelligence (AI) or Machine Learning (ML) system. The traditionally known systems were Java, C#, etc. But as time progressed, among all those programming languages, Python has arrived at the top of the list of favourites majorly due to its ease of use with which developers can handle complex coding challenges using Python. Python is a high level, robust programming language and is mainly focused on rapid application development. Because of the core functionalities present, Python has become one of the fastest-growing programming languages and an obvious choice for programmers developing applications using Python on machine learning, AI, big data, and IoT.  

Python as a  computer programming language can be used to build websites, create software, automate tasks, and conduct data analysis & prediction. Python is known as a general-purpose language, i.e. it can be used to create a variety of different programs and is not only limited to or specialized towards only a specific set of problems. The versatility provided and its beginner-user friendliness is also why it is the most used programming language today. It is loaded with support for multiple programming paradigms beyond object-oriented programming, such as procedural and functional programming.

Register for FREE Workshop on Data Engineering

Python combines its remarkable power with very clear and easy to understand syntax. It provides interfaces to many system calls and libraries and various window systems and is extensible to other languages such as C or C++. It can also be used as an extension language for applications that need a programmable interface. Python language is portable and can run on many Unix variants, including Linux, macOS, and Windows.  The language comes with a large standard library that covers several important aspects of code writing such as string processes, including regular expressions, Unicode, calculating differences between files, Internet protocols: HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering methodologies like unit testing, logging, profiling, parsing Python code, and operating system interfaces being system calls, filesystems, TCP/IP sockets. 

Python in recent years has become a staple language being used in data science, allowing data analysts and other professionals to use the language to conduct and perform complex statistical calculations, create beautiful and interactive data visualizations, build and automate machine learning algorithms, manipulate and analyze data, and easily perform other data-related tasks. Python can help build a wide range of data visualizations, like line and bar graphs, pie charts, histograms, and 3D plots. Python provides several libraries that enable coders to write programs for data analysis, exploration and machine learning more quickly and efficiently, like TensorFlow and Keras. Performing a task repeatedly can be time-consuming; therefore one could work more efficiently by automating it with Python. Writing a code to build these automated processes is called scripting in technical terms. 

In the world of coding, automation can be used to check for errors across multiple files, convert the present files as needed, execute simple math, and remove duplicates, if any, from the data. Relative beginners can even use Python in coding and programming to automate simple tasks on the computer, such as renaming files, finding and downloading online content or sending emails or texts at desired intervals. Learning Python has opened new possibilities for less data-heavy professions, like journalists, small business owners, or social media marketers. Python enables even non-programmer to simplify certain tasks in their daily lives. Debugging Python programs is relatively easy; a bug or bad input will never cause a segmentation fault. When the interpreter discovers an error, it raises an exception. A source-level debugger allows inspection of local and global variables in the code, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and much more. The debugger is written in Python itself. Since Python has so many uses and tools to support those uses, you can spend years learning its different applications, and there will still be room for more. It has become a lot easier to be a Python programmer today than it was 20 years ago since there are a lot more sources and pathways to learn from.

The Python source code does the following process to generate an executable code : 

  • First, The python compiler reads a python source code or instruction given. It then verifies if the instruction provided is well-formatted, i.e. the syntax of each line is checked and taken into consideration. If it encounters an error while doing so, it immediately halts the translation and shows an error message.
  • If there is no error and the python instruction or source code is well-formatted, then the compiler translates it into its equivalent binary form in an intermediate language called “Byte code”.
  • The created Byte code is the0n sent to the Python Virtual Machine(PVM), also known as the python interpreter. PVM converts the python byte code into a machine-executable code. If an error occurs during this process, then the conversion is again halted with an error message.

Image Source

Comparing Features:  Python 3.9 V/s Python 3.10

In this article, we will compare the features of two of the most recent versions of the Python programming language, Python 3.9 and Python 3.10, with their respective examples and try to explore what is different and new. Enthusiasts and creators worldwide contribute to the updates of features and help the programming language be a better version of itself than before.  The official Python version documentation has inspired all the code mentioned below.

Python 3.9 

Support for the IANA Time Zone Database

Python 3.9 supports and has added a module named zoneinfo that lets you access and use the entire Internet Assigned Numbers Authority (IANA) time zone database. By default, zoneinfo will use the system’s time zone data if available. 

Sample Code :

 print(datetime(2021, 7, 2, 12, 0).astimezone())2020-07-2 12:00:00-05:00 print(datetime(2021, 7, 2, 12, 0).astimezone()...       .strftime("%Y-%m-%d %H:%M:%S %Z"))2020-07-2 12:00:00 EST print(datetime(2021, 7, 2, 12, 0).astimezone(timezone.utc))2020-07-2 17:00:00+00:00

Merging and Updating Dictionaries 

One of the coolest features that Python 3.9 possesses is merging or updating dictionaries using operators. Two new operators, ( | ) for merge and ( |= ) to update, have been added to the built-in dict class and hence provide ease of writing code, making it simpler and easier to understand. 

Sample Code for Merge :

 a = {‘victor’: 1, 'article’: 2, 'python’: 3} b = {’victor’: 'dey’, 'topic’: 'python3.9’} a | b{’article’: 2, 'python’: 3, ’victor’:’dey’,  'topic’: 'python3.9’} b | a{’victor’: 1,’article’: 2, 'python’: 3, 'topic’:’python3.9’ }

Sample Code for Update :

 a |= b a{’article’: 2, 'python’: 3,’victor’:’dey’}

New String Methods to remove Prefix and Suffixes

Python 3.9 has introduced new methods updated from the previous version to strip off prefixes and suffixes from strings. The two new introduced methods are removeprefix() and removesuffix(). These methods replace the previously used strip method as they showed many errors in code as per reviews.

Sample code to remove prefix :

 "Victor is playing outside".removeprefix("Victor ")‘is playing outside’

Type Hinting For Built-in Generic Types

This release has enabled support for the generics syntax among all the standard collections currently available in the typing module. A generic type is usually defined as a container, e.g. list. It is a type that can be easily parameterized. Generic types have one or more type parameters, and a Parameterized generic is an instance of a generic data type with the expected container elements. list or dict built-in collection types are the types that are supported instead of using typing.List or typing.Dict.

Sample Code :

def print_value(input: str): print(input)

Using the following syntax, we would get notified if the input is not a string.

String Replace Function

The replace function syntax has been changed a little. Python 3.9 has fixed the issue of returning empty strings from the previous version. The replace function works for a given max replace occurrence argument; it replaces a set of characters from the string with a new set of characters.

Sample Code :

 "".replace("", "victor", 1)Returns ’'One would expect to meet victor "".replace("", "|", 1)Returns ’'One would expect to meet |

Python 3.10

Although in development and fully released, the version can still be installed and tested for features. 

Structural Pattern Matching 

Version 3.10 introduces a new feature called Structural Pattern Matching. The matching technique allows us to perform the same match-case logic but based on whether the structure of our comparison object matches a given pattern. This feature completely changes the way one writes if-else cases. 

Sample code for If else cases before :

 http_code = "112"if http_code == "212":    print("OK")elif http_code == "404":    print("Not Found Here")elif http_code == "419":    print("You Found Me")else:    print("Code not found")

Sample code for If else cases in 3.10 :

See Also


 http_code = "414"match http_code:    case "212":        print("Hi")    case "404":        print("Not Found")    case "414":        print("You Found Me")    case _:        print("Code not found")You Found Me

Improved Syntax Error Messages

In Python 3.10 Syntax Error Messages come with an Associative Suggestion to help the user understand or derive a solution from the suggestion. This tells us about the intelligence the latest version poses.  

Sample Code :

 from carprices import namestoplo AttributeError: module 'collections' has no attribute 'namestoplo'. Did you mean: namedtuple? named_car = 77print(new_car) NameError: name 'new_car' is not defined. Did you mean: named_car?

As you can observe, the associative suggestions are very clear and can help identify quick mistakes.

Update On Typing 

There have been more significant feature updates to Python’s typing. A new addition here is the inclusion of a new operator which behaves like an OR logic for types, something for which we previously used the Union method. We don’t need to write from typing import Union, and Union[int, float] has been completely simplified to just int | float which looks much cleaner. 

Sample Code For Older Versions :

 from typing import Union def add(a: Union[int, float], b: Union[int, float]):    return a + b 

Sample Code For Python 3.10 :

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

Improved Context Manager 

Parenthesized context managers have been introduced to Python 3.10. Context managers are special code constructs that allow the simple handling of resources, like files. With the parenthesized context managers feature, you can use multiple contexts in a single with block. This feature will be highly useful for bits of code, as you no longer need to have multiple with statements.

Old Syntax :

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

New Syntax :

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

End Notes 

In this article, we have explored the Python language, its uses and how it works. We also tried to compare the new versions of it and the differences in features in each of the versions. Finally, I would like to recommend the reader install the versions and…

Python 3.9 vs Python 3.10: A Feature Comparison

Post a Comment

Previous Post Next Post