英文:
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'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'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) -> 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 doesn't complain
safe_format("FOO", **{"kwarg1": "bar", "kwarg2": "BIGBAR"})
# mypy does complain because of kwarg1
safe_format("FOO", **{"kwarg1": 42, "kwarg2": "BIGBAR"})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论