首先,我不确定我的方法是否合适,所以我愿意接受各种建议.
如果在代码中经常重复try/except语句,有没有什么好方法可以缩短它们或避免完全写出来?
try:
# Do similar thing
os.remove('/my/file')
except OSError, e:
# Same exception handing
pass
try:
# Do similar thing
os.chmod('/other/file', 0700)
except OSError, e:
#Same exception handling
pass
Run Code Online (Sandbox Code Playgroud)
例如,对于一行操作,您可以定义异常处理包装器,然后传递lambda函数:
def may_exist(func):
"Work with file which you are not sure if exists."""
try:
func()
except OSError, e:
# Same exception handling
pass
may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
Run Code Online (Sandbox Code Playgroud)
这种"解决方案"是否会让事情变得不那么明确?我应该完全写出所有的try/except语句吗?
我正在尝试像在 Excel 中一样在 python 中定义我自己的 IFERROR 函数。(是的,我知道我可以编写 try/ except 。我只是想为我经常使用的 try/ except 模式创建一个内联简写。)当前的用例是尝试获取一些远程表的几个属性。用于连接到它们的模块会给出各种错误,如果发生这种情况,我只想记录在尝试获取该属性时遇到的错误。
我尝试过的:搜索显示了许多线程,其中最有用的是:
阅读这些主题后,我尝试编写以下内容:
>>> def iferror(success, failure, *exceptions):
... try:
... return success
... except exceptions or Exception:
... return failure
...
>>> iferror(1/0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)
我还尝试使用上下文管理器(对我来说是新的):
>>> from contextlib import contextmanager as cm
>>> @cm
... def iferror(failure, *exceptions):
... try:
... yield
... except exceptions or …Run Code Online (Sandbox Code Playgroud)