[英]Best practice: should I use exception handlers a lot in Python code, or should I avoid if it's possible?
I have got a project, where I have to do this very frequently: 我有一个项目,我必须经常这样做:
if "something" in dict:
some_var = dict["something"]
del dict["something"]
else:
error_handler_or_other_stuff()
However I have the idea to use this: 但是我有使用这个的想法:
try:
some_var = dict.pop("something")
except KeyError:
error_handler_or_other_stuff()
My question is: in general, how "fast" try - except constructs are to handle exceptions? 我的问题是:一般来说,除了构造要处理异常之外,如何快速尝试? Is it OK to use it a lot, or it's still faster to do the stuff "manually". 可以经常使用它吗,还是“手动”执行该操作更快。 Also sometimes I have the situation where I have to convert value to integer: 另外有时我不得不将值转换为整数的情况:
try:
some_var = int(dict.pop("something"))
except KeyError:
error_handler_or_other_stuff("no such key")
except ValueError:
error_handler_or_other_stuff("bad value for key")
Now the solution with exceptions seems to be quite nice, since I can do both of the checks in one step, also I removed the original key/value pair from dict, which is part of the problem. 现在带异常的解决方案似乎非常不错,因为我可以一步完成两项检查,所以我也从dict中删除了原始键/值对,这就是问题的一部分。 So I can tell at least: it looks like an elegant solution. 因此,我至少可以说:这看起来像是一个优雅的解决方案。 However I am not sure it's faster or if it has other disadvantages I should worry about. 但是,我不确定它是否速度更快,或者它是否还有其他缺点我应该担心。
Which construct makes your code easier to understand and maintain? 哪种构造使您的代码更易于理解和维护? Pick that one. 选择那个。
If the resulting code is too slow, then go back and consider whether a different error handling strategy is more efficient. 如果生成的代码太慢,请返回并考虑其他错误处理策略是否更有效。
Exceptions are not particularly slow. 异常并不是特别慢。 Obviously there is a lot more going on in exception handling than in a simple if, but unless you're doing it literally a million times per second, the speed difference is negligible. 显然,异常处理要比简单的if处理得多,但是除非您每秒进行一百万次的处理,否则速度差异是可以忽略的。
Your example is so trivial that there is no reason to worry about speed to begin with. 您的示例是如此琐碎,以至于没有理由担心速度的开始。 Micro-optimizations like that cost more time just thinking about them than you could ever save using them. 这样的微优化花在思考它们上的时间比使用它们所节省的时间更多。
The code you've given is absolutely fine, that's what exceptions are there for. 您提供的代码绝对不错,这就是例外的原因。
These kind of performance questions are easily answered using the timeit module: 使用timeit模块可以轻松回答以下这类性能问题:
setup = '''
d = {'a': 1}
k = 'b'
'''
LBYL = '''
if k in d:
pass
else:
pass
'''
EAPF = '''
try:
d[k]
except KeyError:
pass
'''
from timeit import Timer
print min(Timer(LBYL, setup).repeat(7, 1000000))
print min(Timer(EAPF, setup).repeat(7, 1000000))
The results show 0.0546 for the if/else approach and 1.3370 for the try/except approach. 结果显示,if / else方法为0.0546,try / except方法为1.3370。 The latter is about 25 times slower than the former. 后者比前者慢25倍。
That being said, you should generally use whatever expresses the clearest code. 话虽如此,您通常应该使用最清晰的代码。
Sidenote : the two approaches give different answers for subclasses of dict that define missing to return a value. 旁注 :两种方法对dict的子类给出不同的答案,这些子类定义了缺少值以返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.