【发布时间】:2022-11-29 03:20:26
【问题描述】:
我有一个使用“子”函数的主要函数。子函数获取数据库的值,该值可以是 None。如果是这样的话主功能应该返回 [Pause_Event_Dict()]
但是,我只知道子函数内部的位置是 None 。我怎样才能返回孩子内部的主要功能
def main_function():
location = child_function()
return []
def child_function():
delivery_location = get_location_that_can_be_none_sometimes()
if delivery_location is None:
# the location will be assigned the Pause_Event_Dict value but the main function still returns []
return [Pause_Event_Dict()]
return delivery_location
在理想情况下,我会只使用一个主要功能而忘记孩子:
def main_function():
delivery_location = get_location_that_can_be_none_sometimes()
if delivery_location is None:
return [Pause_Event_Dict()]
return delivery_location
return []
这将是很棒的,除非子函数用于代码的其他部分并且它比此处提供的玩具示例更长。删除子函数将意味着向项目添加大量代码。
我正在研究使用装饰器: Python: Is there a way to force a parent function to return? 但无法让它发挥作用
【问题讨论】:
-
main_function可以简单地返回任何child_function返回的内容,但包装在一个列表中,还是需要先检查返回值? -
@chepner main 函数检查并使用返回值。请注意,child_function 正常返回 delivery_location。