经常重复尝试/除了Python [英] Frequently repeated try/except in Python

查看:120
本文介绍了经常重复尝试/除了Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我不知道我的方法是否正确,所以我可以接受各种建议。



如果try / except语句经常重复在代码中,有什么好的方法来缩短他们,还是避免完全写出来?

  try:
#类似的东西
os.remove('/ my / file')
除了OSError,e:
#同样的异常处理
pass

try:
#做类似的事情
os.chmod('/ other / file',0700)
除了OSError,e:
#Same异常处理
pass
例如,对于一行操作,您可以定义一个异常处理包装器,然后传递一个lambda函数:



  def may_exist(func):
使用您不确定的文件是否存在。
try :
func()
除了OSError,e:
#同样的异常处理
pass

may_exist(lambda:os.remove('/ my /文件' ))
may_exist(lambda:os.chmod('/ other / file',0700))



这个解决方案是否使事情不那么清楚?我应该完全写出所有的try / except语句?

解决方案

抽象异常处理的最好方法是使用上下文管理器:









$ b尝试:
yield
finally:
#无论你的常见处理是

然后:

  with common_handling():
os.remove('/ my / file')

with common_handling():
os.chmod('/ other / file',0700)

这样做的优点是可以在每个common_handling块中放置完整的语句和其中一个以上的语句。



请记住,您需要一次又一次地使用相同的处理方式,就像过度处理异常一样。你确定你需要这么做吗?


Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.

If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?

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

For example, for one line actions you could define a exception handling wrapper and then pass a lambda function:

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))

Does this 'solution' just make things less clear? Should I just fully write out all the try/except statements?

解决方案

The best way to abstract exception handling is with a context manager:

from contextlib import contextmanager
@contextmanager
def common_handling():
    try:
        yield
    finally:
        # whatever your common handling is

then:

with common_handling():
    os.remove('/my/file')

with common_handling():
    os.chmod('/other/file', 0700)

This has the advantage that you can put full statements, and more than one of them, in each common_handling block.

Keep in mind though, your need to use the same handling over and over again feels a lot like over-handling exceptions. Are you sure you need to do this much?

这篇关于经常重复尝试/除了Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆