[英]How do you pythonically tell the program to always do something if no exception was raised
Say I have a setup like this 说我有这样的设置
def add(self, value):
self._length += 1
if isinstance(value, str):
if '\n' in value:
return self.func_a(value)
return self.func_b(value)
return self.func_c(value)
As you can see, many return statements. 如您所见,很多return语句。 Each return statement with its respective function call. 每个return语句及其各自的函数调用。
Whenever the chosen function (out of func_a
, func_b
and func_c
) runs successfully we want _length
to get incremented and the return value of the function to get returned. 每当选定的函数(在func_a
, func_b
和func_c
)成功运行时,我们都希望_length
递增,并希望返回该函数的返回值。
But if the chosen function doesn't run successfully we want _length
to stay the same. 但是,如果所选函数未成功运行,我们希望_length
保持不变。
Obviously, in the code I have shown above _length
will get incremented no matter what. 显然,在我上面显示的代码中, _length
无论如何都会增加。
I took the following approach 我采取了以下方法
def add(self, value):
if isinstance(value, str):
if '\n' in value:
rt = self.func_a(value)
else:
rt = self.func_b(value)
else:
rt = self.func_c(value)
self._length += 1
return rt
which works but it is rather ugly. 可以,但是非常难看。
Is there a more pythonic approach to this? 有没有更Python的方法呢?
If you know which exceptions may be raised, you can do something like the following: 如果您知道可能会引发哪些异常,则可以执行以下操作:
if isinstance(value, str):
fn = self.func_a if '\n' in value else self.func_b
else:
fn = self.func_c
try:
rt = fn(value)
except Exception as e:
# We encountered an error
else:
self._length += 1
finally:
# We want to always run this code
'chosen function doesn't run successfully' is opaque. “选择功能无法成功运行”是不透明的。 If a chosen function raises an error, the entire process will be stopped. 如果所选功能引发错误,则整个过程将停止。 Anyway, both codes mentioned work the same. 无论如何,提到的两个代码都是一样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.