简体   繁体   English

mypy:如何为需要 2 个位置 arguments 的 function 编写类型提示,但仅传递 1 个就足够了?

[英]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.

相关问题 arguments 的 Mypy 类型提示是 pandas 系列 - Mypy type hints for arguments which are pandas series 如何为返回自身的函数编写类型提示? - How to write type hints for a function returning itself? write()接受2个位置参数,但给出了3个 - write() takes 2 positional arguments but 3 were given 使用命名参数定义的函数的 MyPy 类型提示但可以采用 **kwargs? - MyPy type hints for a function defined with named parameters but can take **kwargs? 如何将类型提示添加到 Python 中的仅位置参数和仅关键字参数? - How to add Type Hints to positional-only and keyword-only parameters in Python? Python type hints: How to use Literal with strings to conform with mypy? - Python type hints: How to use Literal with strings to conform with mypy? 当我传递正确数量的参数时,为什么我得到'函数需要 2 个位置参数但 3 个是 gien 错误'? - why am I getting 'function takes 2 positional arguments but 3 were gien error', when I passed the right number of arguments? 如何使用类型提示注释只写属性 - How to annotate a write-only property using type hints 获取类型错误:在使用确实需要6个位置args的函数时,“在Django中“仅接受1个参数,给定6个” - Getting type error: “takes exactly 1 arguments, given 6” in Django when using a function that does take 6 positional args 计算有多少 arguments 作为位置传递 - Count how many arguments passed as positional
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM