Python Morsels: Python 3.15's best new features

1 month ago 41
Club.noww.in

Python 3.15 includes a UTF-8 default encoding, explicit lazy imports, * unpacking in comprehensions, a new sampling profiler, sentinel, frozendict, and more!

A UTF-8 default encoding

The best feature might be one of the most boring ones.

As of Python 3.15, UTF-8 is the default file encoding on all operating systems, which means... Windows.

Linux and Mac already used UTF-8 as their default file encoding in Python. But on Windows, Python used a legacy code page, which depended on your system's language settings. With English language settings, it was usually CP-1252.

Say a coworker on a Mac writes a file with an accented character in it:

>>> with open("cafe.txt", mode="wt") as f: ... f.write("café") ... 4

What happens if we read that file from Python running on a Windows machine? Using the Windows default encoding of CP-1252, this is what we'd see:

>>> open("cafe.txt", encoding="cp1252").read() 'café'

We don't get an error... but we do get garbled text. UTF-8 stores é as two bytes, and CP-1252 happily reads those two bytes as two separate characters.

And if the file had an emoji in it, the old default encoding on Windows couldn't even write the file to begin with:

>>> with open("snake.txt", mode="wt", encoding="cp1252") as f: ... f.write("🐍") ... Traceback (most recent call last): File "<stdin>", line 2, in <module> f.write("🐍") ~~~~~~~^^^^^^ File "/home/trey/.local/share/uv/python/cpython-3.15.0rc2-linux-x86_64-gnu/lib/python3.15/encodings/cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f40d' in position 0: character maps to <undefined>

In Python 3.15, the open function uses UTF-8 as its default encoding on every operating system, so a file written on one machine reads the same on every other machine.

If your code also needs to run on older versions of Python, it's still a good idea to explicitly pass encoding="utf-8" to the open function.

Sentinel objects

There's also now an official …

Read the full article: https://www.pythonmorsels.com/python315/

Read Entire Article