我有一个config.py文件,它作为一堆bool参数,如
show_timer = True
display_graph = True
我的主代码在while循环中运行,如果上面的参数为False,循环看起来很混乱。这种配置文件驱动代码的可读性的最佳方法是什么?我目前使用的格式如下:
init_someting() if display_graph else None
while True:
do_something() if show_timer else None
.
.
.
答案 0 :(得分:2)
如Martijn中his comment所述,请勿使用条件表达式;使用正常的if
语句。看起来你已经完成了函数中的所有操作,所以我认为还有很多事情要做。
if display_graph:
init_something()
while True:
if show_timer:
do_something()
if other_option:
do_other_thing()
仅限教育用途 (但此模式有用的地方)
根据您正在执行的操作的详细信息,您还可以使用配置选项来构建要调用的函数列表,然后重复循环。像这样:
if display_graph:
init_something()
functions_to_call = []
if show_timer:
functions_to_call.append(do_something)
if other_option:
functions_to_call.append(do_other_thing)
while True:
for function in functions_to_call:
function()
或者:
if display_graph:
init_something()
all_functions = [
(show_timer, do_something),
(other_option, do_other_thing),
]
functions_to_call = [function for (flag, function) in all_functions if flag]
while True:
for function in functions_to_call:
function()
/仅限教育目的
答案 1 :(得分:0)
如果保留其他对象不是约束,则可以使用dict
配置功能映射。
func_dict = {'show_timer': timer_func,
'display_graph': display_graph_func}
现在迭代func_dict以检查配置值。类似的东西: -
for config_param, func_obj in func_dict.items():
if config[config_param]:
func_obj()
或简写: -
[func_obj() for config_param, func_obj in func_dict.items() if config[config_param]
但是再次将参数传递给函数将是一个问题。检查一下你是否可以解决它。