You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI场景下基于用户输入组合选择函数的Pythonic实现方法

如何用Pythonic方式替代FastAPI参数匹配的冗长if-elif?

我开发了一个小型FastAPI应用,可接收用户传入的4个可选参数,当前通过冗长的if-elif语句根据用户输入匹配执行对应函数,示例代码如下:

def do_function(origin, destination, departure, arrival):
    if departure is None and arrival is None:
        do_a(origin, destination)
    elif departure is not None and arrival is None:
        do_b(origin, destination, departure)
    elif departure is None and arrival is not None:
        do_c(origin, destination, arrival)
    elif departure is not None and arrival is not None:
        do_d(origin, departure, arrival)
    elif departure is not None and arrival is None:
        do_e(origin, departure)  

    # and so on...

请问无需使用冗长繁琐的if-elif语句,实现该逻辑最符合Python风格(Pythonic)的方式是什么?我曾查阅过类似问题,但该方案不适用于我这种仅4个可选输入却对应多个函数的场景。


核心方案:用状态元组映射函数与参数

针对这种基于参数存在状态(是否为None)匹配函数的场景,最Pythonic的方式是构建状态-函数的映射字典:将departure和arrival的存在状态打包成布尔元组((departure is not None, arrival is not None))作为字典的键,每个键对应要执行的目标函数以及需要传递的参数列表。

具体实现代码:

def do_function(origin, destination, departure, arrival):
    # 定义状态映射:键是(departure非空, arrival非空)的布尔元组,值是(目标函数, 参数列表)
    action_map = {
        (False, False): (do_a, (origin, destination)),
        (True, False): (do_b, (origin, destination, departure)),
        (False, True): (do_c, (origin, destination, arrival)),
        (True, True): (do_d, (origin, departure, arrival)),
        # 若需添加更多状态匹配,直接新增键值对即可
        # 若同一基础状态需区分逻辑,可扩展键的维度(比如结合origin/destination的状态)
    }

    # 生成当前输入的状态键
    current_state = (departure is not None, arrival is not None)
    
    # 获取对应的函数和参数,无匹配时执行默认逻辑(这里用空函数占位)
    func, args = action_map.get(current_state, (lambda *x: None, ()))
    func(*args)

扩展说明:

  • 如果同一基础状态(比如(True, False))需要对应多个函数(如示例中的do_b和do_e),可以扩展键的维度,比如加入origin或destination的状态判断,将键从二元组升级为多元组,确保每个唯一场景对应唯一函数。
  • 未覆盖的状态可通过action_map.get()指定默认处理,比如抛出参数异常或返回错误提示,避免程序崩溃。
  • 这种方式逻辑清晰、可维护性强,新增场景只需在字典中添加键值对,无需修改大量条件判断代码。

内容的提问来源于stack exchange,提问作者Daniel Avigdor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:40:33