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

在Python multimethod中如何定义空列表的处理分支?

解决空列表的多方法调度问题

调用f([])时,空列表无法被类型推断为list[str]或list[int],导致multimethod匹配到两个候选分支,抛出调度错误。以下是两种可行的解决方案:

方案一:使用守卫条件匹配空列表

利用multimethod的guard参数添加额外判断条件,专门匹配空列表:

from multimethod import multimethod

@multimethod
def f(x: list[str]):
    return 1

@multimethod
def f(x: list[int]):
    return 0

# 专门处理空列表的分支,通过guard判断列表长度为0
@multimethod(guard=lambda x: len(x) == 0)
def f(x: list):
    return -1  # 这里写空列表的处理逻辑

该分支会优先匹配满足len(x) == 0的列表,避免调度冲突。

方案二:通过自定义类型守卫匹配空列表

先定义空列表的类型守卫,再为该逻辑类型实现处理分支:

from multimethod import multimethod, typeguard

# 注册类型守卫:判断传入的列表是否为空
@typeguard(list)
def is_empty_list(x):
    return len(x) == 0

@multimethod
def f(x: list[str]):
    return 1

@multimethod
def f(x: list[int]):
    return 0

# 为"空列表"这个逻辑类型实现处理分支
@multimethod
def f(x: is_empty_list):
    return -1

这种方式把空列表作为独立逻辑类型处理,适合需要多次复用空列表判断的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:43:15