New Features In Python 3.10 You Should Know

Pinkal Sanoria
6 min readDec 15, 2021

--

A new version of Python, Python 3.10, was published on October 4th, 2021. You can download the latest version here. Python 3.10 has a number of new and exciting features that make working with Python even more enjoyable. In this article, let’s find out some new Python features that matter the most.

We’ll cover some of the most interesting additions to Python — structural pattern matching, parenthesized context managers, and Clearer error messages

Structural Pattern Matching:

It’s tempting to think of pattern matching as a switch statement on steroids. However, as the rationale PEP points out, it’s better thought of as a “generalized concept of iterable unpacking”. Many people have asked for a switch in Python over the years, though I can see why that has never been added. It just doesn’t provide enough value over a bunch of if … elif statements to pay for itself. The new match … case feature provides the basics of switch, plus the “structural” matching part — and some.

Imagine an if-else statement that looks like this:

statement_elif.py# Declare a variable and initialize it
http_code = "418"
# Program checks if the http_code is "418" or Not
# And displays an appropriate message
if
http_code == "200":
print("OK")
elif http_code == "404":
print("Not Found")
elif http_code == "418":
print("I'm a teapot")
else:
print("Code not found")
#This is the final output
Output:- I'm a teapot

You take that and you modify the syntax so it looks more like this:

statement_case.py# Declare a variable and initialize it
http_code = "418"
# Program checks case the http_code is "418" or Not
# And displays an appropriate message
match http_code:
case "200":
print("OK")
case "404":
print("Not Found")
case "418":
print("I'm a teapot")
case _:
print("Code not found")
#This is the final output
Output:- I'm a teapot

Python evaluates the match expression and then tries each case from the top, executing the first one that matches, or the _ default case if no others match.

But here’s where the structural part comes in: the case patterns don’t just have to be literals. The patterns can also:

Use variable names that are set if a case matcheshttps://medium.com/@_pinkal_/new-features-in-python-3-10-you-should-know-1d60e4853a8e

Match sequences using list or tuple syntax (like Python’s existing iterable unpacking feature)

  • Match mappings using dict syntax
  • Use * to match the rest of a list
  • Use ** to match other keys in a dict
  • Match objects and their attributes using class syntax
  • Include “or” patterns with |
  • Capture sub-patterns with as
  • Include an if “guard” clause

Wow! That’s a lot of features. Let’s see if we can use them all in one go, to see what they look like in a very contrived example (for a more gradual introduction, read the tutorial):

Parenthesized context managers

A context manager in python is used for the allocation of memory when needed and freeing up that memory when its use is over. The ‘with’ statement in python is one of the most common examples of a context manager and its most common use case is the opening of files to read/write data. An example of this is shown below;

manager_9.py# Without context managerwith open("file1.txt",'w') as f1:
f1.write("Writing to only file 1")

Here our file is opened and is recognized by the object variable f1. All the operations we will perform will be using this variable however f1 is only accessible within the indented block. All operations on f1 must be performed within this indented block since once our code leaves the indented block, the file is automatically closed (the purpose of the context manager).

Before Python 3.10 you could only manage context for one object with one ‘with’ statement, the following code would throw a syntax error if executed on python versions less than 3.10.

manager_10.py#Now you can use enclosed parentheses around context managers when #you use the with statements. This allows formatting a long #collection of context managers in multiple lines.with (open(("file1.txt",'w') as f1, open("file2.txt", 'w') as f2):
f1.write("Writing to file 1\n")
f2.write("Writing to file 2\n")

However, this functionality has been added in Python 3.10 and now the above code would open the above files for writing purposes and perform the execution as coded.

Clearer Error Messages

Every coder likely understands the importance of errors while writing code, and how infuriating some error types can be. The previous versions of Python threw error messages as soon as there were problems in the syntax. These could be due to the wrong syntax, missing keywords, incorrect or misspelled keywords, amongst other issues.

Python 3.10 comes with a host of more precise and constructive error messages. In this section, you’ll see some of the newest improvements. The full list is available in the documentation.

The comparisons below explain it perfectly.

Think back to writing your first Hello World program in Python:

hello.py# print Hell, world.print("Hello, World!)

Maybe you created a file, added the famous call to print(), and saved it as hello.py. You then ran the program, eager to call yourself a proper Pythonista. However, something went wrong:

Shell$ python hello.py
File "/home/rp/hello.py", line 3
print("Hello, World!)
^
SyntaxError: EOL while scanning string literal

There was a SyntaxError in the code. EOL, what does that even mean? You went back to your code, and after a bit of staring and searching, you realized that there was a missing quotation mark at the end of your string.

One of the more impactful improvements in Python 3.10 is better and more precise error messages for many common issues. If you run your buggy Hello World in Python 3.10, you’ll get a bit more help than in earlier versions of Python:

Shell$ python hello.py
File "/home/rp/hello.py", line 3
print("Hello, World!)
^
SyntaxError: unterminated string literal (detected at line 3)

The error message is still a bit technical, but gone is the mysterious EOL. Instead, the message tells you that you need to terminate your string! There are similar improvements to many different error messages, as you’ll see below.

A SyntaxError is an error raised when your code is parsed before it even starts to execute. Syntax errors can be tricky to debug because the interpreter provides imprecise or sometimes even misleading error messages. The following code is missing a curly brace to terminate the dictionary:

# unterminated_dict.py
1
2 # Create and print a dictionary:
3 months = {
4 10: "October",
5 11: "November",
6 12: "December"
7 # Print months 10 using formatted string
8
9 print(f"{months[10]} is the tenth month")

The missing closing curly brace that should have been on line 7 is an error. If you run this code with Python 3.9 or earlier, you’ll see the following error message:

ShellFile "/home/rp/unterminated_dict.py", line 9
print(f"{months[10]} is the tenth month")
^
SyntaxError: invalid syntax

The error message highlights line 8, but there are no syntactical problems in line 8! If you’ve experienced your share of syntax errors in Python, you might already know that the trick is to look at the lines before the one Python complains about. In this case, you’re looking for the missing closing brace on line 7.

ShellFile "/home/rp/unterminated_dict.py", line 3
months = {
^
SyntaxError: '{' was never closed

This points you straight to the offending dictionary and allows you to fix the issue in no time.

The new error messages are also a great improvement and can save a lot of time when trying to find the mistake. This could be especially helpful for beginners that previously oftentimes only got confused by the error message.

So, these are some of the key new features being introduced with Python 3. 10! I hope you enjoyed this article! If you have any questions, let me know in the comments below

Happy Pythoning!

hello@crossml.com

--

--