python singledispatch 根据传入参数的类型自动选择相应的实现

functools 模块中的 singledispatch 装饰器允许你定义一个函数,并根据传入参数的类型自动选择相应的实现。这在处理不同类型的输入时非常有用。

singledispatch 装饰器提供了一种在 Python 中实现函数重载的方式。虽然 Python 本身不支持传统的函数重载(即在同一个作用域中定义多个同名函数),但 singledispatch 允许你根据参数类型来选择不同的函数实现,从而实现类似重载的效果。

下面是一个简单的示例,展示了如何使用 singledispatch 装饰器:

py 复制代码
from functools import singledispatch

@singledispatch
def process(arg):
    raise NotImplementedError("Unsupported type")

@process.register
def _(arg: int):
    return f"Processing an integer: {arg}"

@process.register
def _(arg: str):
    return f"Processing a string: {arg}"

@process.register
def _(arg: list):
    return f"Processing a list: {', '.join(map(str, arg))}"

# 测试
print(process(10))       # 输出: Processing an integer: 10
print(process("hello"))  # 输出: Processing a string: hello
print(process([1, 2, 3]))  # 输出: Processing a list: 1, 2, 3

在上述示例中,process 函数根据传入参数的类型(int、str、list)选择不同的处理逻辑,这就是一种函数重载的形式。

再看一个实例:

py 复制代码
from functools import singledispatch

from outlines.fsm.guide import StopAtEOSGuide
from outlines.generate.api import SequenceGenerator, SequenceGeneratorAdapter
from outlines.models import MLXLM, VLLM, LlamaCpp, OpenAI
from outlines.samplers import Sampler, multinomial


@singledispatch
def text(model, sampler: Sampler = multinomial()) -> SequenceGenerator:
    """Generate text with a `Transformer` model.

    Note
    ----
    Python 3.11 allows dispatching on Union types and
    this should greatly simplify the code.

    Arguments
    ---------
    model:
        An instance of `Transformer` that represents a model from the
        `transformers` library.
    sampler:
        The sampling algorithm to use to generate token ids from the logits
        distribution.

    Returns
    -------
    A `SequenceGenerator` instance that generates text.

    """
    fsm = StopAtEOSGuide(model.tokenizer)
    device = model.device
    generator = SequenceGenerator(fsm, model, sampler, device)

    return generator


@text.register(MLXLM)
def text_mlxlm(model: MLXLM, sampler: Sampler = multinomial()):
    return SequenceGeneratorAdapter(model, None, sampler)


@text.register(VLLM)
def text_vllm(model: VLLM, sampler: Sampler = multinomial()):
    return SequenceGeneratorAdapter(model, None, sampler)


@text.register(LlamaCpp)
def text_llamacpp(model: LlamaCpp, sampler: Sampler = multinomial()):
    return SequenceGeneratorAdapter(model, None, sampler)


@text.register(OpenAI)
def text_openai(model: OpenAI, sampler: Sampler = multinomial()) -> OpenAI:
    if not isinstance(sampler, multinomial):
        raise NotImplementedError(
            r"The OpenAI API does not support any other sampling algorithm "
            + "than the multinomial sampler."
        )

    return model
相关推荐
circuitsosk7 分钟前
智能体任务拆解与执行:基于ReAct+Plan-and-Execute框架的行业Skill构建实录
前端·javascript·python·react.js·react·llm agent·智能体编排
麻雀飞吧9 分钟前
近期量化工具怎么选,先看你卡在哪一环
人工智能·python
通信仿真爱好者9 分钟前
第【109】期--基于神经网络的OFDM峰均功率比降低方法--python完整代码
python·神经网络·ofdm·限幅滤波·峰均功率比·papr降低
阿图灵10 分钟前
OpenCV 图像特征与匹配:SIFT 特征检测与 BFMatcher 暴力匹配
图像处理·人工智能·python·opencv·计算机视觉·sift
王志来1379447300823 分钟前
工控服务器机箱选型决策要素解析:匀天以“快全准省”构建价值坐标
运维·服务器·python·devops
阿图灵38 分钟前
OpenCV 实用技巧三连:视频转图片、图片转视频、Pillow 与 OpenCV 互转
图像处理·python·opencv·计算机视觉·音视频·pillow
GlueNa2SiO340 分钟前
05-Flask表单处理与文件上传
笔记·python·学习·flask
一晌小贪欢42 分钟前
Python办公16:PDF 强力缝合——将几十个 PDF 合并为单个文档并添加页码
开发语言·python·excel·数据可视化·python办公
qq_1611112743 分钟前
深入理解Python中的Contextlib库
python·装饰器·函数·上下文管理器·contextlib
迷迭香yy1 小时前
回测过拟合检测体系从样本内外到组合稳健性评估 IG50免费开源股票数据API接口
服务器·开发语言·数据库·人工智能·python