“继续下一步”的Pythonic方式关于例外? [英] A Pythonic way for "resume next" on exceptions?

查看:91
本文介绍了“继续下一步”的Pythonic方式关于例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
我正在读一系列异构输入文件。我为每个人写了一个读者类,它使用 __ init __(self,file_name)读取文件,并在格式错误的输入的情况下抛出异常。

The problem: I am reading a series of heterogeneous input files. I wrote a reader class for each of them, which reads the file using __init__(self, file_name), and throws an exception in case of malformed input.

代码如下所示:

clients              = Clients             ('Clients.csv'             )
simulation           = Simulation          ('Simulation.csv'          )
indicators           = Indicators          ('Indicators.csv'          )
legalEntity          = LegalEntity         ('LegalEntity.csv'         )
defaultPortfolio     = DefaultPortfolio    ('DefaultPortfolio.csv'    )
excludedProductTypes = ExcludedProductTypes('ExcludedProductTypes.csv')

问题是我不想在第一个格式错误的文件中死亡,而是读取所有文件,如果至少有一个格式错误,那么死亡。
我可以找到的唯一方法是看起来很可怕:

The problem is that I want not to die at the first malformed file, but instead read all of them and THEN die if at least one was malformed. The only way to do it that I could find looks horrible:

my errors = []    

try:
    clients              = Clients             ('Clients.csv'             )
except Exception, e:
    errors.append(e)
try:
    simulation           = Simulation          ('Simulation.csv'          )
except Exception, e:
    errors.append(e)
try:
    indicators           = Indicators          ('Indicators.csv'          )
except Exception, e:
    errors.append(e)
try:
    legalEntity          = LegalEntity         ('LegalEntity.csv'         )
except Exception, e:
    errors.append(e)
try:
    defaultPortfolio     = DefaultPortfolio    ('DefaultPortfolio.csv'    )
except Exception, e:
    errors.append(e)
try:
    excludedProductTypes = ExcludedProductTypes('ExcludedProductTypes.csv')
except Exception, e:
    errors.append(e)

if len(errors) > 0:
    raise MultipleErrors(errors)

有更好的方法来解决问题?

Is there a better looking way to approach the problem?

推荐答案

将类和文件存储在一个序列中,结果成字典:

Store the classes and files in a sequence, the results into a dictionary:

inputs = (
    (Clients, 'Clients.csv'),
    (Simulation, 'Simulation.csv'),
    (Indicators, 'Indicators.csv'),
    (LegalEntity, 'LegalEntity.csv'),
    (DefaultPortfolio, 'DefaultPortfolio.csv'),
    (ExcludedProductTypes, 'ExcludedProductTypes.csv'),
)

results = {}
errors = []
for cls, filename in inputs:
    try:
        results[cls.__name__[0].lower() + cls.__name__[1:]] = cls(filename)
    except Exception, e:
        errors.append(e)

if errors:
    raise MultipleErrors(errors)

这篇关于“继续下一步”的Pythonic方式关于例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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