Skip to content

What’s New In Python 3.14

Important

  1. Deferred Evaluation Of Annotations Using Descriptors, 直接支持延迟注解, 不再需要from __future__ import annotations

PEP 734: Multiple interpreters in the standard library

在一个进程中允许不通过C-API运行多个解释器以支持真正的并行能力

  • concurrent.interpreters
  • concurrent.futures.InterpreterPoolExecutor

Current limitations

  1. 解释器启动未优化
  2. 解释器之间的内存共享
  3. 第三方已经支持的不多
  4. 编码方式对于大多数用户比较陌生

PEP 750: Template string literals

用法与f-string 相同,但是返回值并非字符串, 而是一个对象

Example
from string.templatelib import Interpolation, Template


def html(template: Template) -> str:
    parts = []
    for part in template:
        if isinstance(part, Interpolation):
            if isinstance(part.value, dict):
                value = " ".join([f'{k}="{v}"' for k, v in part.value.items()])
                parts.append(value)
        else:
            if part == ">":
                parts.append(" />")
            else:
                parts.append(part)
    return "".join(parts)


attributes = {"src": "limburger.jpg", "alt": "lovely cheese"}
template = t"<img {attributes}>"

assert html(template) == '<img src="limburger.jpg" alt="lovely cheese" />', html(
    template
)

PEP 768: Safe external debugger interface

支持通过 sys.remote_exec 在已运行的 Python 进程中执行代码

Example
import sys
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
    script_path = f.name
    f.write(f'import my_debugger; my_debugger.connect({os.getpid()})')

# Execute in process with PID 1234
print('Behold! An offering:')
sys.remote_exec(1234, script_path)

Asyncio introspection capabilities

通过命令行接口查看指定进程的异步任务列表和调用栈信息

  • python -m asyncio ps PID
  • python -m asyncio pstree PID
Example
import asyncio

async def play_track(track):
    await asyncio.sleep(5)
    print(f'🎵 Finished: {track}')

async def play_album(name, tracks):
    async with asyncio.TaskGroup() as tg:
        for track in tracks:
            tg.create_task(play_track(track), name=track)

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(
          play_album('Sundowning', ['TNDNBTG', 'Levitate']),
          name='Sundowning')
        tg.create_task(
          play_album('TMBTE', ['DYWTYLM', 'Aqua Regia']),
          name='TMBTE')

if __name__ == '__main__':
    asyncio.run(main())

PEP 765: Control flow in finally blocks

finally代码块中使用returnbreakcontinue 会发出 SyntaxWarning警告

Example
def process_file(path):
    f = open(path, "w")
    try:
        # 某些操作可能抛出异常
        return "done"
    finally:
        print("closing file...")
        return "cleanup done"
        # SyntaxWarning: 'return' in a 'finally' block

Nice

  1. 新增annotationlib库获取注解信息

PEP 784: Zstandard support in the standard library

内置的 zstd 压缩算法实现

Example
from compression import zstd
import math

data = str(math.pi).encode() * 20
compressed = zstd.compress(data)
ratio = len(compressed) / len(data)
print(f"Achieved compression ratio of {ratio}")

Trivial

PEP 758: Allow except and except* expressions without brackets

允许在捕获多个异常且未使用as子句时省略括号

Example
try:
    connect_to_server()
except TimeoutError, ConnectionRefusedError:
    print('The network has ceased to be!')

Incremental garbage collection

  1. 未主动调用 gc.collect 的情况下,垃圾回收的触发频率降低
  2. gc.collect(1) 触发增量式回收
  3. yongold

总结