跳转到主要内容

用于特定类型注解的类参数的 `singledispatch()`。

项目描述

class_singledispatch
skeleton Supported Python versions Package version

Tests Coverage Documentation Status

用于特定类型注解的类参数的 `singledispatch()`。

灵感来源于https://github.com/python/cpython/issues/100623

简单示例

虽然 functools.singledispatch 会检查第一个用户参数的类,但 class_singledispatch 使用第一个参数作为类本身,并使用它执行与 functools.singledispatch 相同的任务。

from class_singledispatch import class_singledispatch


class T:
    pass


class OtherT:
    pass


@class_singledispatch
def on_class(cls: type[T], /) -> None:
    print("T!")


@on_class.register
def on_other_class(cls: type[OtherT], /) -> None:
    print("OtherT!")


# Useful for <3.10 without eval_type_backport -- pass the class to the decorator
# not to use the annotation from the function for the targeted class resolution
@on_class.register(SomeOtherT)
def on_some_other_class(cls: type[SomeOtherT], /) -> None:
    print("SomeOtherT!")


on_class(T)  # T!
on_class(OtherT)  #  OtherT!
on_class(SomeOtherT)  #  SomeOtherT!

安装

您可能只需使用pip进行安装

pip install class-singledispatch

[!注意] class-singledispatch 支持现代类型提示
要使用 PEP 585PEP 604 注释在Python <3.10中,请安装 class-singledispatch[modern-type-hints]

如果您使用 Poetry,则可能需要运行

poetry add class-singledispatch

对于贡献者

Poetry Ruff Pre-commit

[!注意] 如果您使用Windows,强烈建议您通过WSL2完成以下安装方式。

  1. Forkclass_singledispatch仓库在GitHub上。

  2. 安装Poetry.
    诗是管理依赖项和虚拟环境、构建包以及发布它们的出色工具。您可能希望使用pipx将其全局安装(推荐)

    pipx install poetry
    

    如果您遇到任何问题,请参考官方文档以获取最新的安装说明。

    请确保已安装Python 3.8——如果您使用pyenv,只需运行

    pyenv install 3.8
    
  3. 在本地克隆您的分支并安装依赖项。

    git clone https://github.com/your-username/class_singledispatch path/to/class_singledispatch
    cd path/to/class_singledispatch
    poetry env use $(cat .python-version)
    poetry install
    

    接下来,只需激活虚拟环境并安装pre-commit钩子

    poetry shell
    pre-commit install
    

有关如何贡献的更多信息,请参阅CONTRIBUTING.md
始终乐于接受贡献!❤️

法律信息

© 版权所有 巴托什·斯劳韦茨基 (@bswck)。
本软件根据MIT许可证许可。

项目详情


下载文件

下载适用于您平台的应用程序。如果您不确定选择哪一个,请了解有关安装软件包的更多信息。

源代码分发

class_singledispatch-1.2.3.post2.tar.gz (6.6 kB 查看哈希值)

上传时间: 源代码

构建分发

class_singledispatch-1.2.3.post2-py3-none-any.whl (6.2 kB 查看哈希值)

上传时间: Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面