Type hints for a function that has both named and unnamed kwargs

huangapple go评论87阅读模式
英文:

Type hints for a function that has both named and unnamed kwargs

问题

我的函数定义包含了命名和未命名的 kwargs

```python
def safe_format(text: str, max_errors: int = 10, **kwargs: str) -> None:
    print(text)
    print(max_errors)
    print(kwargs)

如果我在不指定 max_errors 的情况下调用它:

safe_format(some_str, **some_dict)

我确实得到了预期的结果(首先打印出 some_str,然后是 10,然后是 some_dict)。然而,mypy 不满意,并认为我正在尝试将 some_dict 用作 max_errors 的值:

Argument 2 to "safe_format" has incompatible type "**Dict[str, str]**"; expected "**int**"

是否有特定的语法可以让 mypy 识别我正在做什么?


<details>
<summary>英文:</summary>

My function definition contains both named and unnamed kwargs:

def safe_format(text: str, max_errors: int = 10, **kwargs: str) -> None:
print(text)
print(max_errors)
print(kwargs)


If I call it without specifying max_errors:

safe_format(some_str, **some_dict)


I do get the expected result (some_str is printed, then 10, then some_dict). Yet mypy is unhappy and believes I&#39;m trying to use some_dict as a value for max_errors:

Argument 2 to "safe_format" has incompatible type "**Dict[str, str]"; expected "int"


Is there a specific syntax I can use for mypy to recognize what I&#39;m doing?

</details>


# 答案1
**得分**: 0

基于评论,我成功使用`typing.overload`使其工作。

```python
from typing import overload

@overload
def safe_format(text: str, max_errors: int = 10, **kwargs: str) -> None:
    ...

@overload
def safe_format(text: str, max_errors=..., **kwargs: str) -> None:
    ...

def safe_format(text: str, max_errors: int = 10, **kwargs: str) -> None:
    print(text)
    print(max_errors)
    print(kwargs)

# mypy不会抱怨
safe_format("FOO", **{"kwarg1": "bar", "kwarg2": "BIGBAR"})
# mypy会因为kwarg1而抱怨
safe_format("FOO", **{"kwarg1": 42, "kwarg2": "BIGBAR"})

这是您提供的代码段的翻译部分。

英文:

Based on the comments, I managed to make it work with typing.overload

from typing import overload


@overload
def safe_format(text: str, max_errors: int = 10, **kwargs: str) -&gt; None:
    ...


@overload
def safe_format(text: str, max_errors=..., **kwargs: str) -&gt; None:
    ...


def safe_format(text: str, max_errors: int = 10, **kwargs: str) -&gt; None:
    print(text)
    print(max_errors)
    print(kwargs)


# mypy doesn&#39;t complain
safe_format(&quot;FOO&quot;, **{&quot;kwarg1&quot;: &quot;bar&quot;, &quot;kwarg2&quot;: &quot;BIGBAR&quot;})
# mypy does complain because of kwarg1
safe_format(&quot;FOO&quot;, **{&quot;kwarg1&quot;: 42, &quot;kwarg2&quot;: &quot;BIGBAR&quot;})

huangapple
  • 本文由 发表于 2023年8月4日 21:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定