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

本文介绍了Python3.5及以上版本中typing模块的@overload装饰器的使用,该装饰器用于函数重载,以支持不同的参数类型组合。通过示例代码展示了如何利用@overload进行类型提示,以及如何在运行时实现类型检查。同时,文章还探讨了函数注解在Python中的应用,帮助提升代码的可读性和静态类型检查。
摘要由CSDN通过智能技术生成

      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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值