趕緊試試 Python 3.12 吧,真的好用
Python 3.12 引入了一些新的特性和改進,提升了開發(fā)體驗和代碼性能。以下是其中一些值得注意的新函數和改進:
1. str.removeprefix() and str.removesuffix()
雖然這些函數在 Python 3.9 就已引入,但它們在 Python 3.12 中變得更加廣泛使用。
- **str.removeprefix(prefix)**:如果字符串以指定的前綴開頭,則返回去掉該前綴的字符串。
- **str.removesuffix(suffix)**:如果字符串以指定的后綴結尾,則返回去掉該后綴的字符串。
s = "HelloWorld"
print(s.removeprefix("Hello")) # 輸出: World
print(s.removesuffix("World")) # 輸出: Hello
2. math.nextafter(x, y)
返回從 x 開始,到 y 方向的下一個浮點數。這個函數對需要精確控制浮點數計算的場景非常有用。
import math
print(math.nextafter(1.0, 2.0)) # 輸出: 1.0000000000000002
print(math.nextafter(1.0, 0.0)) # 輸出: 0.9999999999999999
3. sys.orig_argv
這個屬性允許你訪問原始的命令行參數列表,包括解釋器自身的參數,而不僅僅是腳本和傳遞給腳本的參數。
import sys
print(sys.orig_argv)
4. functools.cache_clear()
在 Python 3.12 中,functools.cache_clear() 方法被添加到 functools.lru_cache 修飾器中,用于清除緩存。
from functools import lru_cache
@lru_cache(maxsize=32)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 清除緩存
fibonacci.cache_clear()
5. 新的 typing 模塊改進
Python 3.12 對 typing 模塊進行了多項改進,包括更好的類型推斷和新的類型提示功能。例如,可以使用 Self 類型提示方法的返回類型為類實例本身。
from typing import Self
class MyClass:
def my_method(self) -> Self:
return self
6. contextlib.aclosing
類似于 contextlib.closing 但用于異步生成器對象。
import contextlib
class AsyncGenerator:
async def __aenter__(self):
print("Entering")
return self
async def __aexit__(self, exc_type, exc, tb):
print("Exiting")
async def __aiter__(self):
for i in range(5):
yield i
async def main():
async with contextlib.aclosing(AsyncGenerator()) as agen:
async for item in agen:
print(item)
# 運行異步主函數
import asyncio
asyncio.run(main())
7. itertools.pairwise()
產生一對連續(xù)元素的迭代器。
import itertools
for pair in itertools.pairwise([1, 2, 3, 4]):
print(pair)
# 輸出: (1, 2), (2, 3), (3, 4)
8. zoneinfo 模塊改進
對時區(qū)信息進行了增強,更好地支持時間相關操作。
from zoneinfo import ZoneInfo
from datetime import datetime
dt = datetime(2024, 6, 14, tzinfo=ZoneInfo("America/New_York"))
print(dt)
這些新特性和改進使得 Python 3.12 更加強大和易用,為開發(fā)者提供了更多工具來編寫高效、可維護的代碼。建議大家盡早升級并嘗試這些新特性。