Python3中装饰器@typing.overload的使用

      typing.py的源码在:https://github.com/python/cpython/blob/main/Lib/typing.py 。此模块为类型提示(Type Hints)提供运行时支持。这里介绍下@typing.overload的使用,从python 3.5版本开始将Typing作为标准库引入。

      python3中增加了Function Annotation(函数注解,能够声明类型)的功能,可以使用类型检查工具如mypy达到类型静态检查的效果。

      @overload装饰器可以修饰支持多种不同参数类型组合的函数和方法。一系列@overload-decorated定义必须紧跟一个非@overload-decorated定义(对于相同的函数/方法)。

      @overload-decorated定义仅是为了协助类型检查工具,因为它们将被非@overload-decorated定义覆盖,而后者在运行时会被类型检查工具忽略。在运行时,直接调用@overload-decorated函数会引发NotImplementedError。

      被装饰的函数的输入类型和输出类型都可以更改,非@overload-decorated定义必须通用。

      以下为测试代码:

from typing import overload, Union
from typing_extensions import Literal

var = 2
if var == 1:
    # python3中增加了Function Annotation(函数注解,能够声明类型)的功能,可以使用类型检查工具如mypy达到类型静态检查的效果
    def foo(name: str) -> str:
        return "csdn id:" + name

    print(foo("fengbingchun"))
    #print(foo(5)) # TypeError: can only concatenate str (not "int") to str
elif var == 2:
    # reference: https://stackoverflow.com/questions/59359943/python-how-to-write-typing-overload-decorator-for-bool-arguments-by-value
    # 被装饰的函数的输入类型和输出类型都可以更改,非@overload-decorated定义必须通用
    # The first two overloads use Literal[...] so we can have precise return types:
    @overload
    def myfunc(arg: Literal[True]) -> str: ...

    @overload
    def myfunc(arg: Literal[False]) -> int: ...

    # The last overload is a fallback in case the caller provides a regular bool
    @overload
    def myfunc(arg: bool) -> Union[str, int]: # Union[str, int] == str | int
        ...

    def myfunc(arg:bool) -> Union[int, str]:
        if arg: return "something"
        else: return 0

    print(myfunc(True))
    print(myfunc(False))

    # Variables declared without annotations will continue to have an inferred type of 'bool'
    variable = True
    print(myfunc(variable))

print("test finish")

      GitHubhttps://github.com/fengbingchun/Python_Test

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@overload是Python装饰器,用于声明函数的重载。通过使用@overload装饰器,我们可以为同一个函数定义多个不同的签名(即参数列表),从而让函数在不同的情况下执行不同的代码。这可以提高代码的可读性和可维护性。 在Python的标准库typing模块提供了对类型提示的支持,并且从Python 3.5版本开始成为标准库的一部分。你可以在https://github.com/python/cpython/blob/main/Lib/typing.py找到typing.py的源码。这个模块包含了@overload装饰器的定义和使用示例。 如果你想了解更多使用@overload装饰器的示例,你可以参考https://github.com/fengbingchun/Python_Test这个GitHub项目,它提供了关于Python@overload装饰器的更多实例和解释。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Python3装饰器@typing.overload使用](https://blog.csdn.net/fengbingchun/article/details/121959036)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [python@overload的作用](https://blog.csdn.net/weixin_42608299/article/details/129595925)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值