重复尝试和例外条款 [英] Repetitive Try and Except Clauses
问题描述
我创建了一堆函数,我需要在所有函数中使用非常相似的 except 子句,但我讨厌在每个函数中使用这么多行 try 和 except 子句以及相同的代码.例如:
导入系统随机导入定义 foo():num=random.random()尝试:如果 num>0.5:打印OK"elif num>0.25: raise NameError('Too Small')否则:引发键盘中断除了名称错误:打印%s 有一个 NameError" % sys._getframe().f_code.co_name除了:打印%s 有一个不同的错误"% sys._getframe().f_code.co_name定义栏():num=random.random()尝试:如果 num>0.8:打印OK"elif num>0.6: raise NameError('Too Small')否则:引发键盘中断除了名称错误:打印%s 有一个 NameError" % sys._getframe().f_code.co_name除了:打印%s 有一个不同的错误"% sys._getframe().f_code.co_name
try"后的代码因函数而异,但except"后的代码相同.我想合并那些 except 语句,这样它们就不会让我的代码看起来如此局促.有什么好的办法吗?
Python 装饰器想要.
你说except块总是一样的.制作一个自定义装饰器来做你想做的事.您必须将其应用于每个函数/方法,但它确实可以避免重复.
def handleError(function):定义句柄问题():尝试:功能()除了例外:打印哦不"返回句柄问题@句柄错误定义示例():引发异常(繁荣!")
当调用一个应用了装饰器的方法时:
<前>>>>>>> 示例()哦不>>>您将需要更改异常类型以及您要执行的操作,但您会明白我要做什么.
I've created a bunch of functions and I need very similar except clauses in all of them, but I hate having so many lines of try and except clauses and the same code inside of each function. For example:
import sys
import random
def foo():
num=random.random()
try:
if num>0.5: print 'OK'
elif num>0.25: raise NameError('Too Small')
else: raise KeyboardInterrupt
except NameError:
print "%s had a NameError" % sys._getframe().f_code.co_name
except:
print "%s had a different Error" % sys._getframe().f_code.co_name
def bar():
num=random.random()
try:
if num>0.8: print 'OK'
elif num>0.6: raise NameError('Too Small')
else: raise KeyboardInterrupt
except NameError:
print "%s had a NameError" % sys._getframe().f_code.co_name
except:
print "%s had a different Error" % sys._getframe().f_code.co_name
The code after "try" is different for the functions, but the code after "except" is the same. I want to consolidate those except statements so they don't make my code look so cramped. Is there a good way to do this?
Python Decorators are what you want.
You said the except block is always the same. Make a custom decorator that does what you want. You'll have to apply this to each function/method but it sure does save duplication.
def handleError(function):
def handleProblems():
try:
function()
except Exception:
print "Oh noes"
return handleProblems
@handleError
def example():
raise Exception("Boom!")
When calling a method with the decorator applied:
>>> >>> example() Oh noes >>>
You will need to change the exception types as well as what you do, but you get the jist of where I'm going with this.
这篇关于重复尝试和例外条款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!