Python releases one new major release every 12 months, in October. Each release includes new features, and sometimes removes old features.
In this series, I explore the most exciting new features with you. I’ll include code examples so you can follow along. You can use either an early release candidate build, or wait until October for 3.12’s big production debut!
Improved Error Messages
This especially helps beginners. And, in general, all programmers.
Example of when you forget to import something:
>>> sys.version_info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined. Did you forget to import 'sys'?
Example of when you capitalize an import wrong:
from collections import chainmap
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?
You can read more here.
Faster Comprehension Creation
Dictionary, list, and set comprehensions in previous versions of Python created a new anonymous function, and then called that function for every execution of the comprehension.
The optimization being implemented is called, “inlining,” but if you don’t know what that means no worries. Creating a comprehension will get up to 2x faster without any change from you!
Simple example with Python 3.11:
> python3.11 -m timeit '[i for i in [0]]'
5000000 loops, best of 5: 91.5 nsec per loop
Simple example with Python 3.12:
> python3.12 -m timeit '[i for i in [0]]'
5000000 loops, best of 5: 53 nsec per loop
I saw approximately a 91.5 / 53 = 1.73x speedup.
That’s on my laptop, with an Apple M1 CPU. While your results will vary, you should also see approximately a 2x speedup!
You can read more here.
Gotchas?
Well, the speedup you see also depends on what you were doing inside the comprehension.
The more stuff you do, the less you notice the speedup to the creation time of your comprehension. Sadly, it’s not magic (though Python often feels like magic!)
As an example, even just making a list of 1,000 integers looks almost the same in Python 3.11 and 3.12. Don’t worry that 3.12 is slightly slower here, this is a Release Candidate build (still under development):
> python3.11 -m timeit '[i for i in range(1000)]'
20000 loops, best of 5: 11.9 usec per loop
> python3.12 -m timeit '[i for i in range(1000)]'
20000 loops, best of 5: 14.6 usec per loop
With that said, if you use a lot of comprehensions, and their computation is relatively lightweight, you will notice significant speedups!
Stay Tuned for Part 2-4!
In Part 2, we’ll talk about new updates to format strings, and automated deletion of temp files on close.
In Part 3, we’ll talk about a handy new CLI for sqlite3, and a handy new CLI for UUIDs. Python is becoming the Swiss Army Knife of CLIs!
Finally, in Part 4, we will celebrate the launch of Python 3.12 on October 2, 2023.