我有一个很长的那个结构的 Python 函数:
def the_function(lots, of, arguments):
return_value = None
if some_important_condition:
# a lot of stuff here
return_value = "some value"
else:
# even more stuff here
return_value = "some other value"
return return_value
一个问题是 theif
和else
block 都包含不止一屏的代码。很容易忘记缩进,或者不得不向上滚动查看我们目前处于什么状态。
改进这一点的一个想法是将其拆分为几个功能:
def case_true(lots, of, arguments):
# a lot of stuff here
return "some value"
def case_false(lots, of, arguments):
# even more stuff here
return "some other value"
def the_function(lots, of, arguments):
return_value = None
if some_important_condition:
return_value = case_true(lots, of, arguments)
else:
return_value = case_false(lots, of, arguments)
return return_value
但考虑到争论的杂耍,我不确定这是否能解决问题。
另一个想法是使用多个退出点:
def the_function(lots, of, arguments):
if some_important_condition:
# a lot of stuff here
return "some value"
# even more stuff here
return "some other value"
但是有几种编码风格建议不要使用多个退出点,尤其是当它们隔着屏幕时。
问题是:使原始结构更具可读性和可维护性的首选pythonic方法是什么?