[英]mypy: how to write type hints for a function that takes 2 positional arguments but it is enough that only 1 is passed?
Say that I have a function foo
such that it is allowed to take arguments as it follows假设我有一个 function
foo
,这样就可以使用 arguments,如下所示
foo(a,b) -> It is OK
foo(None,b) -> It is OK
foo (a, None) -> It is OK
foo(None,None) -> It is NOT OK!!!
How to write its signature, including its type hints?如何写它的签名,包括它的类型提示?
At the moment I have written the type hints as目前我已经将类型提示写为
def foo(a:Optional[str], b:Optional[str]) -> str
but that is wrong because such signature would be fine with the call foo(None,None)
.但这是错误的,因为调用
foo(None,None)
这样的签名就可以了。
Use @overload
to define different (narrower) signatures for a function. Mypy will check calls to that function against all the overloaded signatures and produce an error if none of them match.使用
@overload
为 function 定义不同的(更窄的)签名。Mypy 将根据所有重载签名检查对该 function 的调用,如果它们都不匹配,则会产生错误。
from typing import overload, Optional
@overload
def foo(a: str, b: Optional[str]) -> str: ...
@overload
def foo(a: Optional[str], b: str) -> str: ...
def foo(a: Optional[str], b: Optional[str]) -> str:
return (a or "") + (b or "")
foo('a', 'b')
foo(None, 'b')
foo ('a', None)
foo(None, None) # error: No overload variant of "foo" matches argument types "None", "None"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.