15

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

代码如下所示:

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

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

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)

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

4

2 回答 2

20

按顺序存储类和文件,将结果存储到字典中:

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)
于 2013-09-06T10:26:51.030 回答
5

你可以尝试这样的事情:

handlers_mapping = {
    Clients: 'Clients.csv',
    Simulator: 'Simulator.csv',
    Indicators: 'Indicators.csv',
    LegalEntity: 'LegalEntity.csv',
    DefaultPortfolio: 'DefaultPortfolio.csv',
    ExcludedProductTypes: 'ExcludedProductTypes.csv'
}

results = {}
errors = []
for handler, file_name in handlers_mapping.iteritems():
    try:
        results[handler] = handler(file_name)
    except Exception, e:
        errors.append(e)
于 2013-09-06T10:32:25.557 回答