当前位置: 首页 > 科技观察

3个今天仍然有用的Python3.2特性

时间:2023-03-14 10:19:41 科技观察

探索一些未被充分利用但仍然有用的Python特性。这是关于Python3.x的第一个特性的系列文章中的第三篇文章。其中一些Python版本已经发布了一段时间。例如,Python3.2于2011年首次发布,但其中引入的一些很酷、很有用的特性仍然没有被使用。以下是其中的三个。argparse子命令argparse模块最早出现在Python3.2中。命令行解析的第三方模块有很多。但是内置的argparse模块比很多人想象的更强大。要记录argparse的所有功能,需要一系列文章。这是一个如何将argparse用作子命令的示例。想象一个有两个子命令的命令:negate,它接受一个参数,multiply,它接受两个参数:$computebotnegate5-5$computebotmultiply236importargparseparser=argparse.ArgumentParser()subparsers=parser.add_subparsers()add_subparsers()方法创建一个对象,您可以向其添加子命令。唯一要记住的技巧是你需要添加通过set_defaults()调用的子命令:negate=subparsers.add_parser("negate")multiply=subparsers.add_parser("multiply")multiply.set_defaults(subcommand="multiply")multiply.add_argument("number1",type=float)multiply.add_argument("number2",type=float)我最喜欢的一个argparse特性是因为它将解析与运行分开,所以测试解析逻辑特别愉快。parser.parse_args(["negate","5"])Namespace(number=5.0,subcommand='negate')parser.parse_args(["multiply","2","3"])Namespace(number1=2.0,number2=3.0,subcommand='multiply')contextlib.contextmanager上下文是Python中的一个强大工具。虽然很多人都在使用它们,但编写新的上下文通常看起来像是一门黑暗艺术。使用contextmanager装饰器,您只需要一个一次性生成器。编写一个打印出做某事所需时间的上下文非常简单:("took",after-before)你可以这样使用:importtimewithtimer():time.sleep(10.5)take10.511025413870811`functools.lru_cache有时在内存中缓存一个函数的结果是有意义的。例如,想象一下经典问题:“25美分、1美分、2美分和3美分可以用多少种方式兑换1美元?”这道题的代码可以说很简单:defchange_for_a_dollar():defchange_for(amount,coins):ifamount==0:return1ifamount<0orlen(coins)==0:return0some_coin=next(iter(coins))返回(change_for(amount,coins-set([some_coin]))+change_for(amount-some_coin,coins))returnchange_for(100,frozenset([25,10,5,1]))在我的电脑上这需要大约13毫秒:withtimer():change_for_a_dollar()花费了0.013737603090703487`事实证明,当你计算有多少种方法可以做一些事情,比如找零50美分,你重复使用了同一枚硬币。您可以使用lru_cache来避免重复计算。importfunctoolsdefchange_for_a_dollar():@functools.lru_cachedefchange_for(amount,coins):如果amount==0:return1ifamount<0orlen(coins)==0:return0some_coin=next(iter(coins))返回(change_for(amount,coins-set([some_coin]))+change_for(amount-some_coin,coins))returnchange_for(100,frozenset([25,10,5,1]))withtimer():change_for_a_dollar()花费了0.004180959425866604`一条线的成本是三倍的提升。好的。欢迎来到2011年尽管Python3.2是10年前发布的,但它的许多功能仍然很酷且未得到充分利用。如果您还没有将它们添加到您的工具箱中。