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
相关推荐
Hgfdsaqwr3 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
开发者小天4 小时前
python中For Loop的用法
java·服务器·python
老百姓懂点AI4 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
喵手6 小时前
Python爬虫零基础入门【第九章:实战项目教学·第15节】搜索页采集:关键词队列 + 结果去重 + 反爬友好策略!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·搜索页采集·关键词队列
Suchadar6 小时前
if判断语句——Python
开发语言·python
ʚB҉L҉A҉C҉K҉.҉基҉德҉^҉大6 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
喵手7 小时前
Python爬虫零基础入门【第九章:实战项目教学·第14节】表格型页面采集:多列、多行、跨页(通用表格解析)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·表格型页面采集·通用表格解析
0思必得07 小时前
[Web自动化] 爬虫之API请求
前端·爬虫·python·selenium·自动化
莫问前路漫漫7 小时前
WinMerge v2.16.41 中文绿色版深度解析:文件对比与合并的全能工具
java·开发语言·python·jdk·ai编程
木头左7 小时前
Backtrader框架下的指数期权备兑策略资金管理实现与风险控制
python