Though many minor changes are brought in Python 3.11, We’ll just look at some important changes and features add in this release.
step 1: sudo apt install software-properties-common
step 2: sudo add-apt-repository ppa:deadsnakes/ppa
step 3: sudo apt update
step 4: sudo apt install python3.11
Using Python 3.6.9, the error traces back to the line. In Python 3.11, it becomes much more fine-grained.
#Python3.6.9, filename dummy.py
def dummy(a):
return 1/a
print(dummy(0))
"""
Traceback (most recent call last):
File "dummy.py", line 4, in <module>
print(dummy(0))
File "dummy.py", line 2, in dummy
return 1/a
ZeroDivisionError: division by zero
"""
While in Python 3.11, the error traces back to the exact point of error as follows:
#Python3.11, filename dummy.py
def dummy(a):
return 1/a
print(dummy(0))
""" Error Trace
Traceback (most recent call last):
File "/home/python3_11_venv/dummy.py", line 4, in <module>
print(dummy(0))
^^^^^^^^
File "/home/python3_11_venv/dummy.py", line 2, in dummy
return 1/a
~^~
ZeroDivisionError: division by zero
"""
Here, we can notice the symbol ~ and ^ are used to point the exact place in the line, which triggers the error. Though it might seem like not big deal in this code, but in complex codes this is truly amazing. Another sample code for error tracing.
#python3.6.9, handling keyerror.
a = {"a": "b", "b": "c"}
a["c"]
""" Error Trace
Traceback (most recent call last):
File "dummy.py", line 7, in <module>
a["c"]
KeyError: 'c'
"""
#python3.11, handling keyerror.
a = {"a": "b", "b": "c"}
a["c"]
"""Error Trace
Traceback (most recent call last):
File "/home/python3_11_venv/dummy.py", line 7, in <module>
a["c"]
~^^^^^
KeyError: 'c'
"""
Sample Code with Python 3.6.9
#python3.6.9 running from terminal
> python3 -m timeit '"-".join(str(n) for n in range(100))'
100000 loops, best of 3: 13 usec per loop
Similar code in Python 3.11 environment.
#python3.11 running from terminal
> python3.11 -m timeit '"-".join(str(n) for n in range(100))'
50000 loops, best of 5: 8.41 usec per loop
In benchmarks, “CPython 3.11 is on average 25% faster than CPython 3.10” (Source).
tomlib
module is introduced in 3.11, it has been designed to be easy for humans to read and easy for computers to parse. TOML (Tom’s Obvious Minimal Language) is a popular file format for writing human-readable configuration files.
# units.toml
[second]
label = { singular = "second", plural = "seconds" }
aliases = ["s", "sec", "seconds"]
[minute]
label = { singular = "minute", plural = "minutes" }
aliases = ["min", "minutes"]
multiplier = 60
to_unit = "second"
[hour]
label = { singular = "hour", plural = "hours" }
aliases = ["h", "hr", "hours"]
multiplier = 60
to_unit = "minute"
How to handle toml config file.
>>> import tomllib
>>> with open("units.toml", mode="rb") as file:
... units = tomllib.load(file)
...
>>> units
{'second': {'label': {'singular': 'second', 'plural': 'seconds'}, ... }}
Reference:
...
Feedback is welcomed 💬