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
相关推荐
_.Switch36 分钟前
Python机器学习模型的部署与维护:版本管理、监控与更新策略
开发语言·人工智能·python·算法·机器学习
Hoper.J1 小时前
PyTorch 模型保存与加载的三种常用方式
人工智能·pytorch·python
弱冠少年2 小时前
websockets库使用(基于Python)
开发语言·python·numpy
技术无疆2 小时前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
羊小猪~~2 小时前
机器学习/数据分析--用通俗语言讲解时间序列自回归(AR)模型,并用其预测天气,拟合度98%+
人工智能·python·机器学习·数据挖掘·数据分析·回归·时序数据库
qq_273900232 小时前
解析TMalign文本文件中的转换矩阵
python·生物信息学
阿华的代码王国3 小时前
【JavaEE】——文件IO的应用
开发语言·python
电饭叔4 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
程序猿小D4 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
杰哥在此5 小时前
Python知识点:如何使用Multiprocessing进行并行任务管理
linux·开发语言·python·面试·编程