当前位置:   article > 正文

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

@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定义必须通用。

      以下为测试代码:

  1. from typing import overload, Union
  2. from typing_extensions import Literal
  3. var = 2
  4. if var == 1:
  5. # python3中增加了Function Annotation(函数注解,能够声明类型)的功能,可以使用类型检查工具如mypy达到类型静态检查的效果
  6. def foo(name: str) -> str:
  7. return "csdn id:" + name
  8. print(foo("fengbingchun"))
  9. #print(foo(5)) # TypeError: can only concatenate str (not "int") to str
  10. elif var == 2:
  11. # reference: https://stackoverflow.com/questions/59359943/python-how-to-write-typing-overload-decorator-for-bool-arguments-by-value
  12. # 被装饰的函数的输入类型和输出类型都可以更改,非@overload-decorated定义必须通用
  13. # The first two overloads use Literal[...] so we can have precise return types:
  14. @overload
  15. def myfunc(arg: Literal[True]) -> str: ...
  16. @overload
  17. def myfunc(arg: Literal[False]) -> int: ...
  18. # The last overload is a fallback in case the caller provides a regular bool
  19. @overload
  20. def myfunc(arg: bool) -> Union[str, int]: # Union[str, int] == str | int
  21. ...
  22. def myfunc(arg:bool) -> Union[int, str]:
  23. if arg: return "something"
  24. else: return 0
  25. print(myfunc(True))
  26. print(myfunc(False))
  27. # Variables declared without annotations will continue to have an inferred type of 'bool'
  28. variable = True
  29. print(myfunc(variable))
  30. print("test finish")

      GitHubhttps://github.com/fengbingchun/Python_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/336255
推荐阅读
相关标签
  

闽ICP备14008679号