What’s new in python 3.11: favourite features


What's new in Python 3.11: My favorite additions - 5 minutes of fame

2 December 2022 @ CzodrowskiLab

Aishvarya Tandon

Python 3.11 came out little more than a month ago. While it has loads of new features, here are 3 of my favorites.

The following work is based on my opinion. Credits of all the software used and demonstrated belongs to their respective authors and the community.

License: MIT

In [1]:
import sys
print(sys.version)
3.11.0 | packaged by conda-forge | (main, Oct 25 2022, 06:18:27) [GCC 10.4.0]

Speed

Official release notes mention:

Python 3.11 is between 10-60% faster than Python 3.10. On average, we measured a 1.25x speedup on the standard benchmark suite.

Few results at:

Why is this so important? *These speedup comes without changing your code! Just continue to write Python code properly :)*

Better error messages

In Python 3.11, the interpreter now point to the exact expression that causes an error when printing tracebacks, instead of just pointing the lines which was done by the previous versions.

python_3.11 error

Compared to Python 3.10 or before:

python_3.10_error

At this moment, it is only visible while using Terminal/console and not inside Jupyter notebook.

Support for parsing TOML in the standard library

tomllib is a module which provides an interface for parsing TOML. With this module now present in the standard library, dependence on external modules for parsing TOML is now redundant.

At this moment, this module does not support writing TOML.

In [2]:
import tomllib
In [3]:
with open("data/load_file.toml", "rb") as f:
    data = tomllib.load(f)
In [4]:
#The TOML file is now parsed as a dictionary

data
Out[4]:
{'Model_Name': 'Best_model_ever',
 'Numbers_of_Folds': 5,
 'Balanced_Accuracy_CV_Metrics': {'Balanced_Accuracy_of_all_Folds': [0.83,
   0.86,
   0.81,
   0.81,
   0.83],
  'Mean_Balanced_Accuracy_CV': 0.83,
  'Standard_Deviation_Mean_Balanced_Accuracy_CV': 0.02},
 'Cohens_Kappa_CV_Metrics': {'Cohens_Kappa_of_all_Folds': [0.83,
   0.86,
   0.81,
   0.81,
   0.83],
  'Mean_Cohens_Kappa_CV': 0.65,
  'Standard_Deviation_Mean_Cohens_Kappa_CV': 0.02},
 'Test_Set_Metrics': {'Balanced_Accuracy_Test_Set': 0.83,
  'Cohens_Kappa_Test_Set': 0.66,
  'Confusion_Matrix_Test_Set': [[129, 20], [23, 85]]}}
In [5]:
#or simply parse a TOML string 

load_string = """
Model_name = "Best_model_ever"
Numbers_of_fold = 5
"""

data2 = tomllib.loads(load_string)
In [6]:
#The TOML formatted string is now parsed as a dictionary

data2
Out[6]:
{'Model_name': 'Best_model_ever', 'Numbers_of_fold': 5}

You can read more about TOML in my previous 5 mins of fame notebook.