What’s New in Python 3.11

Sarper Makas
3 min readFeb 19, 2023

--

Python 3.11.2 is the most latest version of the popular programming language, and it includes a number of new features and improvements. In this blog article, we’ll look at some of the new features in Python 3.11 and give some sample code to get you started.

Summary

Python 3.11 is 10–60% faster than 3.10. Measured a 1.25x speedup on the standard benchmark suite. There is exception , speed , syntax improvements.

Exceptions

From now on you can raise multiple exceptions by using exception groups.

PEP 654 introduces language features that enable a program to raise and handle multiple unrelated exceptions simultaneously. The builtin types ExceptionGroup and BaseExceptionGroup make it possible to group exceptions and raise them together, and the new except* syntax generalizes except to match subgroups of exception groups.

https://docs.python.org/3/whatsnew/3.11.html#whatsnew311-pep654

Also you can add notes to your exception by using this you can give more information easly. You need catch the exception by using try except then you need to add a note, and raise it again

try:
i = 1 / 0
except Exception as e:
e.add_note("New Note: Zero Division Error")
raise
Traceback (most recent call last):
File "C:/Users/Sarper/Desktop/test.py", line 2, in <module>
i = 1 / 0
ZeroDivisionError: division by zero
New Note: Zero Division Error

Typing

New type is add Self which is normal self .

New Features Related to Type Hints

This section covers major changes affecting PEP 484 type hints and the typing module.

Here is an example:

from typing import Self

class MyClass:
def __init__(self, num):
self.num = num

def create_class(self) -> Self:
return MyClass(3) # returning new class

my_class = MyClass(2)
print(my_class.create_class())

# OUTPUT:
# <__main__.MyClass object at 0x000002477E1D0250>
from typing import Self

class MyClass:
def __init__(self, num):
self.num = num

def return_class(self) -> Self:
return self # returning self

my_class = MyClass(2)
print(my_class.return_class())

# OUTPUT:
<__main__.MyClass object at 0x0000014B89E71350>

Marking individual TypedDict items as required or not-required

Required and NotRequired provide a straightforward way to mark whether individual items in a TypedDict must be present. Previously, this was only possible using inheritance.

All fields are still required by default, unless the total parameter is set to False, in which case all fields are still not-required by default. For example, the following specifies a TypedDict with one required and one not-required key:

Creating special dictionaries is a powerful ability if you want to build libraries and reducing error that may occur from user.

class Movie(TypedDict):
title: str
year: NotRequired[int]

m1: Movie = {"title": "Black Panther", "year": 2018} # OK
m2: Movie = {"title": "Star Wars"} # OK (year is not required)
m3: Movie = {"year": 2022} # ERROR (missing required field title)

The following definition is equivalent:

class Movie(TypedDict, total=False):
title: Required[str]
year: int

Improved Modules

asyncio contextlib dataclasses datatime enum fcntl fractions functools haslib inpect locale logging math operator os pathlib re shutlit socket sqlite3 string sys sysconfig tempfile threading time tkinter traceback typing unicodedata unittest venv warnings zipfile

Look here for more information

Operation Speedups

  • Binary operations x+x; x*x; x-x; 10%
  • Subscript a[i] 10–25%
  • Store subscript a[i] = z 10–25%
  • Calls f(arg) C(arg) 20%
  • Load global variable print len[1]
  • Load attribute o.attr [3]
  • Load methods for call o.meth() 10–20%
  • Store attribute o.attr = z 2% in pyperformance
  • Unpack Sequence *seq8%

Look for more information

Source

https://docs.python.org/3/whatsnew/3.11.html

--

--