What's new in Python 3.11

Posted by Afsal on 28-Oct-2022

Hello Pythonistas!

Python 3.11 was released on Oct 25, 2022. As per the documentationPython 3.11 is between 10-60% faster than Python 3.10. On average, we measured a 1.25x speedup on the standard benchmark suite”. Python3.11 comes with lots of improvements. I am going to explain 5 features that I found interesting.

1 Better error Location

We get a better error location in 3.11 than before

Code

def hello_world(name):
    print("Hello "+ name)

hello_world(123)
Run using python3.11
Traceback (most recent call last):
  File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/python_311.py", line 7, in <module>
    hello_world(123)
    ^^^^^^^^^^^^^^^^
  File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/python_311.py", line 4, in hello_world
    print("Hello "+ name)
          ~~~~~~~~^~~~~~
TypeError: can only concatenate str (not "int") to str

Run using python3.10

Traceback (most recent call last):
  File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/python_311.py", line 7, in <module>
    hello_world(123)
  File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/python_311.py", line 4, in hello_world
    print("Hello "+ name)
TypeError: can only concatenate str (not "int") to str

We can see that in Python3.11 error location is more clear than in the previous version

2. Exception Note

In the new version, there is a provision to add extra notes to exceptions. A new method add_note is used for the same. Let us check with an example

Code

def divide_function(a, b):
    try:
        return a/b
    except Exception as e:
        e.add_note("You have passed zero as the denominator please change")
        raise

divide_function(1, 0)

Output

Traceback (most recent call last):
  File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/python_311.py", line 13, in <module>
    divide_function(1, 0)
  File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/python_311.py", line 6, in divide_function
    return a/b
           ~^~

ZeroDivisionError: division by zero
You have passed zero as the denominator please change

3 Added new module tomllib

Added a new module called tomllib for parsing TOML documents.

Code

toml_str = """title = 'TOML Example'

[database]
server = '192.168.1.1'
ports = [ 8000, 8001, 8002 ]
connection_max = 5000
enabled = true

"""

import tomllib
data = tomllib.loads(toml_str)
print(data)
print(data["title"])
print(data["database"]["server"])

Output

{'title': 'TOML Example', 'database': {'server': '192.168.1.1', 'ports': [8000, 8001, 8002], 'connection_max': 5000, 'enabled': True}}

TOML Example

192.168.1.1

Using this module we can load  a toml string and access the information easily

4 StrEnum

Added a new type StrEnum in the enum module. We can generate value to string enum automatically using the auto method. Value with be the same as the name of the field

Before Python3.11

from enum import Enum

class PrimaryColors(Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

print(f"PrimaryColors are: {PrimaryColors.RED.value}, {PrimaryColors.GREEN.value}, {PrimaryColors.BLUE.value}")

Output

PrimaryColors are: red, green, blue

In Python3.11

from enum import StrEnum, auto

class PrimaryColors(StrEnum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

print(f"PrimaryColors are: {PrimaryColors.RED.value}, {PrimaryColors.GREEN.value}, {PrimaryColors.BLUE.value}")

Output

PrimaryColors are: red, green, blue

This helps us create string enums very easily

5 Update in the math module

Added 2 new methods for finding cube root and exponent of 2

>>> import math
>>>
>>> math.cbrt(8)   
2.0
>>> math.exp2(3)   
8.0
>>>

There are lots of changes you can refer to the official documentation for this

I hope you have learned something from this post. Please share your feedback with afsal@parseltongue.co.in