我有一个打开文本文件,解析一堆数据并在数组中返回数字结果的函数。现在,我还希望该函数即时进行一些可选的计算,并在需要时返回这些值。
对于单个标志,这是相当干净的,例如:
def read_data(file_name, calc_a=False):
# do normal parsing and store data in 'xyz'
if calc_a:
# calc some other stuff and store in 'a'
return xyz, a
else:
return xyz
现在,如果我要使用多个可选标志,事情很快就会变得混乱,例如:
def read_data(file_name, calc_a=False, calc_b=False):
# do normal parsing and store data in 'xyz'
if calc_a:
# calc some other stuff and store in 'a'
if calc_b:
# calc some other stuff and store in 'b'
if calc_a and calc_b:
return xyz, a, b
elif calc_a:
return xyz, a
elif calc_b:
return xyz, b
else:
return xyz
有没有更清洁的方法来处理这种情况?
最佳答案
def read_data(file_name, *extras):
# Read the data from file_name, organizing in a dict,
# using the key names that your caller will pass into the function.
# In this example, we have the main data that will always be
# returned, plus optional data stored under keys a, b, c, d.
data = dict(_main = 'MAIN', a = 'AA', b = 'BB', c = 'CC', d = 'DD')
# Return a tuple, list, or even dict of that data.
ks = sorted(data.keys())
return tuple(data[k] for k in ks if k in extras or k == '_main')
# Caller requests the optional data they want.
# This example shows the caller passing a list of optional data keys.
# You could also have them pass keyword args instead.
wanted = 'a b d'.split()
print read_data('data_file', *wanted) # ('MAIN', 'AA', 'BB', 'DD')