Navigation
Recherche
|
The best new features and fixes in Python 3.14
mercredi 7 mai 2025, 18:56 , par InfoWorld
The first release candidate of Python 3.14 is now available. This article presents a rundown of the most significant new features in the next version of Python and what they mean for Python developers.
Major new features in Python 3.14 These are the most significant new features in Python 3.14: Official support for free-threaded Python, with free-threaded improvements The experimental just-in-time compiler A new Python installation manager for Microsoft Windows Template strings Deferred evaluation of annotations Better error messages A safe external debugger interface to CPython A C API for Python runtime configuration stdlib support for multiple interpreters “Tail-call-compiled” interpreter Incremental garbage collection Official support for free-threaded Python, and free-threaded improvements Python’s free-threaded build promises true parallelism for threads in Python programs by removing the Global Interpreter Lock (GIL). However, originally it was considered an experimental project that needed buy-in from the larger Python community. Although the free-threaded build came bundled with Python 3.13, you had to opt in to use it, and there was no official support. With Python 3.14, the free-threaded build still ships with Python installations and still requires opting in, but it is now considered an officially supported edition of Python. This means free-threaded Python will continue to be shipped as part of Python generally, and will not be removed without a proper deprecation schedule (just as the “dead batteries” were removed from Python recently, for example). If you’re interested in experimenting with the free-threaded build, read our primer on how to start using it and check out our guide to making the most of it in your Python programs. Free threading in Python has also been improved a great deal since Python 3.13. An earlier mechanism for speeding up Python generally, the specializing adaptive interpreter, wasn’t enabled in the free-threaded build, but it’s now active there. The one persistent issue with free threading is poorer performance on single-threaded programs, which tend to run 5% to 10% slower than they do on the GIL-enabled build. The penalty varies across platforms and also with individual programs, so it’s worth trying your applications on both builds to see the advantages or drawbacks. The experimental just-in-time compiler Another new feature for enhancing Python performance is the just-in-time compiler, or JIT. The JIT is a complement to the specializing adaptive interpreter, which speeds up Python by replacing individual bytecodes with type-specialized versions. A more ambitious optimization than the specializing adaptive interpreter, the JIT takes whole sequences of bytecode instructions and replaces them with sections of pre-generated machine code. With Python 3.14, the JIT is available in Microsoft Windows and macOS binary releases of CPython, but disabled by default, as it’s still considered an experimental feature. It can be enabled with an environment variable (PYTHON_JIT=1) or command-line flags. As with the free-threaded build, it’s useful to experiment with the JIT on your workloads, but don’t expect consistent performance improvements. In fact, at this stage you’re likely to see things slow down as speed up. Note that the JIT is not yet available in a free-threaded build. Right now you can have one or the other enabled, but not both. A new Python installation manager for Microsoft Windows Installing Python on Microsoft Windows has long been done using a setup tool that didn’t always manage multiple installations of Python successfully. If you were in the habit of adding and removing different versions of Python and running them side by side, the Python installer for Windows could sometimes break the behavior of older versions. Python’s maintainers have created an entirely new Python installation manager for Windows. Outwardly it works a lot like the original Python installer: You run it and it sets up a given edition of Python. But it also provides expanded powers for removing or updating all previously installed versions, setting which version runs as the default, and invoking a given version for a specific Python command or program. Template strings We’ve long used f-strings in Python to conveniently format variables in a string. Python 3.14 introduces an even more advanced feature in this vein, template strings as defined in PEP 750. A template string, or t-string, lets you combine the template with a function that operates on the template’s structure, not just its output. You could write a template handler that allows all variables placed in the template, or only variables of a specific type, or only variables that match some output, to be manipulated at output time. You could also handle the variables and the interpolating text as separate, differently typed objects. For instance, if you have the template t'My name is {user_name}, and I'm from {user_locale}', you could have the variables user_name and user_locale automatically cleaned of any HTML before display. You could also perform transformations on the My name is and and I'm from portions of the output automatically, as those would be tagged with the special type Interpolation. Template strings will make it far easier to write template engines, e.g., Jinja2, or to duplicate much of the functionality of those template engines directly in Python without the overhead of third-party libraries. Deferred evaluation of annotations Type annotations in Python have historically been evaluated “eagerly,” meaning when they’re first encountered in code. This made it difficult to do things like forward references for a type—e.g., to have a class method that takes a parameter hinted with another type that isn’t defined at that point in the module: class Thing: def frob(self, other:OtherThing):... class OtherThing:... Code like this would typically not pass linting. The workaround would be: class Thing: def frob(self, other:'OtherThing'):... class OtherThing:... Or you could use from __future__ import annotations. With Python 3.14, annotations for objects are now stored in “annotate functions,” which are available through an __annotate__ attribute. This attribute returns the annotation for a given object when it’s needed, so annotations can be evaluated lazily by linters or even evaluated at runtime. The annotationlib module provides tools for inspecting these new annotations at runtime or as part of a linting process. If you’re currently using from __future__ import annotations as your workaround for handling deferred annotations, you don’t need to change anything just yet, although this directive is deprecated and will be removed entirely in future Python versions (most likely sometime after 2029). Better error messages Over the last several Python revisions, error messages have been improved and polished in many ways. This tradition continues with Python 3.14. The biggest improvement: Unknown terms that closely match Python keywords now elicit suggestions. For example: forr a in b: ^^^^ SyntaxError: invalid syntax. Did you mean 'for'? Many other error improvements also have been rolled in: Issues with unpacking, where there is a mismatch between the expected and received number of items, now have more detailed errors in more cases than before. Misplaced elif blocks generate their own specific error message. Statements that illegally combine ternary assignment and control flow (e.g., x = a if b else pass) now generate detailed error messages. Incorrectly closed strings will elicit suggestions for completing the string. A safe external debugger interface to CPython Attaching an external debugger to the CPython interpreter comes at the cost of a lot of runtime overhead, and potential safety issues. Plus, you can’t attach a debugger to CPython spontaneously. In order to use an external debugger, you have to launch CPython with the debugger already attached. With Python 3.14, a new debugger interface provides hooks into the CPython interpreter for attaching a debugger without changing its execution. You can use Python’s pdbdebugging module to attach to another Python process (by way of its process ID) and perform interactive debugging on the target process without having to restart the process with the debugger attached. Aside from the added convenience, the new debugger interface also makes it easier for third parties to write better and more robust debugging tools. They will no longer need to inject their own custom code into the interpreter, which can be brittle and produce new bugs. A C API for Python runtime configuration The Python configuration C API provides a C API to let users set or get information about the current configuration of the Python interpreter, using Python objects rather than C structures. This way, the interpreter can be configured directly from Python itself, making it easier to write Python-level tools to make runtime changes to interpreter behavior. The Python configuration C API is part of a general cleanup of CPython internals and APIs, including the APIs for how CPython is initialized. Note that C users can always drop back to the lower-level APIs if they need them. Easier ways to use `except` for multiple exceptions If you want to catch multiple exceptions in a try/except block, you have had to use parentheses to group them: try: flaky_function() except (BigProblem, SmallProblem):... With Python 3.14, you can simply list multiple exceptions separated by commas: try: flaky_function() except BigProblem, SmallProblem:... The original syntax still works, of course, but the new syntax means a little less typing for a common scenario. stdlib support for multiple interpreters Python has long had multiple options for concurrent programming: threading, multiprocessing, and async. More recently, a long-dormant feature has been refined to be useful to end users: support for multiple interpreter instances inside a single process. For a long time, the “subinterpreter” system had no real end-user interface. As of Python 3.14, the Python standard library now has a module, called concurrent.interpreters, that exposes some basic functionality for using subinterpreters. This provides a halfway house between the full isolation of multiprocessing and the shared contexts of a thread. Right now, concurrent.interpreters doesn’t expose much functionality. For instance, there aren’t many high-level mechanisms for sharing objects between interpreters, and the way subinterpreters work generally doesn’t resemble the way threads or subprocesses work. To that end, subinterpreters should be thought of as an experimental new mechanism for concurrency, where the Python community will discover its best use cases as more functionality for it comes online. ‘Tail-call-compiled’ interpreter The CPython interpreter in Python 3.14 can use a feature in C code that uses tail calls between functions. When compiled with a C compiler that supports these features, CPython runs slightly faster. Note that this feature isn’t the same thing as enabling tail call optimizations in the Python language; it is an internal optimization for the CPython interpreter. Python developers don’t need to do anything except upgrade to Python 3.14 to see a benefit. Unfortunately, the original estimated performance improvements for this change turned out to be wildly off, due to a compiler bug in Clang/LLVM19 (since fixed in subsequent releases). The performance improvement falls in the range of 3% and 5%, well short of the 9% to 15% speedup originally reported. As with any optimization like this, you’ll want to run your own benchmarks to see how well your applications perform. Incremental garbage collection The CPython garbage collector has been reworked to use incremental collection for better performance. Previously, objects could be tracked in up to three different generations for garbage collection, depending on how long they lived. Now the garbage collector only uses two generations, “young” and “old.” Each sweep of the garbage collector processes the whole of the young generation and a portion of the old generation. The net effect is far shorter garbage collection pauses, sometimes down to as little as one-tenth of what they used to be.
https://www.infoworld.com/article/3975624/the-best-new-features-and-fixes-in-python-3-14.html
Voir aussi |
56 sources (32 en français)
Date Actuelle
dim. 27 juil. - 05:18 CEST
|