Python 3.12 引入了一些新的特性和改进,提升了开发体验和代码性能。以下是其中一些值得注意的新函数和改进:
虽然这些函数在 Python 3.9 就已引入,但它们在 Python 3.12 中变得更加广泛使用。
**str.removeprefix(prefix)**:如果字符串以指定的前缀开头,则返回去掉该前缀的字符串。
**str.removesuffix(suffix)**:如果字符串以指定的后缀结尾,则返回去掉该后缀的字符串。
s="HelloWorld"print(s.removeprefix("Hello"))# 输出:Worldprint(s.removesuffix("World"))# 输出:Hello
返回从 x 开始,到 y 方向的下一个浮点数。这个函数对需要精确控制浮点数计算的场景非常有用。
importmathprint(math.nextafter(1.0,2.0))# 输出:1.0000000000000002print(math.nextafter(1.0,0.0))# 输出:0.9999999999999999
这个属性允许你访问原始的命令行参数列表,包括解释器自身的参数,而不仅仅是脚本和传递给脚本的参数。
importsysprint(sys.orig_argv)
在 Python 3.12 中,functools.cache_clear() 方法被添加到 functools.lru_cache 修饰器中,用于清除缓存。
from functoolsimportlru_cache @lru_cache(maxsize=32)deffibonacci(n):ifn<2:returnnreturnfibonacci(n-1)+fibonacci(n-2)# 清除缓存 fibonacci.cache_clear()
Python 3.12 对 typing 模块进行了多项改进,包括更好的类型推断和新的类型提示功能。例如,可以使用 Self 类型提示方法的返回类型为类实例本身。
from typingimportSelfclassMyClass:defmy_method(self)->Self:returnself
类似于 contextlib.closing 但用于异步生成器对象。
importcontextlibclassAsyncGenerator:asyncdef__aenter__(self):print("Entering")returnselfasyncdef__aexit__(self,exc_type,exc,tb):print("Exiting")asyncdef__aiter__(self):foriinrange(5):yieldiasyncdefmain():asyncwithcontextlib.aclosing(AsyncGenerator())asagen:asyncforiteminagen:print(item)# 运行异步主函数importasyncio asyncio.run(main())
产生一对连续元素的迭代器。
importitertoolsforpairinitertools.pairwise([1,2,3,4]):print(pair)# 输出:(1,2),(2,3),(3,4)
对时区信息进行了增强,更好地支持时间相关操作。
from zoneinfoimportZoneInfo from datetimeimportdatetime dt=datetime(2024,6,14,tzinfo=ZoneInfo("America/New_York"))print(dt)
这些新特性和改进使得 Python 3.12 更加强大和易用,为开发者提供了更多工具来编写高效、可维护的代码。建议大家尽早升级并尝试这些新特性。