赞
踩
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")

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。