【问题标题】:return to 'parent' function inside 'child' - python返回到 \'child\' 中的 \'parent\' 函数 - python
【发布时间】: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。

标签: python rasa


【解决方案1】:

一种选择是子函数返回一个状态变量:

def main_function():
    status, location = child_function()
    if status == "pause":
        return [Pause_Event_Dict()]

    return []

def child_function():
    delivery_location = get_location_that_can_be_none_sometimes()

    if delivery_location is None:
        return "pause", ""
    return "continue", delivery_location

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 2016-03-22
    • 2014-04-05
    • 1970-01-01
    相关资源
    最近更新 更多