所有的python助手都导致Mypy认为场是可选的

发布于 2025-01-22 20:53:17 字数 616 浏览 2 评论 0原文

当使用Python All()助手时,我会看到Mypy(版本0.942)认为该字段是可选的,即使All()助手都可以确保所有这些都存在。

对于以下代码段,我看到了

def rate_limit(user_id: int, rate_limit_max: int, rate_limit_since_time: int):
    do_something()

def some_func(
    user_id: int = None, 
    rate_limit_max: int = None, 
    rate_limit_since_time: int = None
): 
    if all([user_id, rate_limit_max, rate_limit_since_time]):
        rate_limit(user_id, rate_limit_max, rate_limit_since_time)

此代码段的Mypy的奇怪行为,我会得到这些行:

error: Argument "user_id" to "rate_limit" has incompatible type "Optional[int]"; expected "int"

When using the python all() helper I am seeing odd behaviour with mypy (version 0.942) where it thinks a field is optional even though the all() helper would make sure all of them exist.

For the following code snippet I am seeing odd behavior from mypy

def rate_limit(user_id: int, rate_limit_max: int, rate_limit_since_time: int):
    do_something()

def some_func(
    user_id: int = None, 
    rate_limit_max: int = None, 
    rate_limit_since_time: int = None
): 
    if all([user_id, rate_limit_max, rate_limit_since_time]):
        rate_limit(user_id, rate_limit_max, rate_limit_since_time)

For this code snippet I get something along these lines:

error: Argument "user_id" to "rate_limit" has incompatible type "Optional[int]"; expected "int"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

箜明 2025-01-29 20:53:17

基于上面提供的文档Juanpa,我可以找到( pep-647 )看起来像Mypy无法弄清楚从All()助手返回的类型是什么。

来自文档

在某些情况下,不能仅根据静态信息应用类型缩小。考虑以下示例:

  def is_str_list(val:list [object]) - >布尔:
    “”“确定列表中的所有对象是否为字符串”“”
    返回所有(x中的X in iSinstance(x,str))

def func1(val:list [object]):
    如果IS_STR_LIST(Val):
        打印(“” .join(val))#错误:无效类型
 

此代码正确,但是类型检查器将报告类型错误,因为>传递给联接方法的值val被理解为类型列表[对象]。类型的检查器没有足够的信息来静态验证Val的类型在此时列表[str]。

Based on the docs juanpa provided above I was able to find (PEP-647) looks like mypy can't figure out what the type returned from the all() helper would be.

From the docs

There are cases where type narrowing cannot be applied based on static information only. Consider the following example:

def is_str_list(val: List[object]) -> bool:
    """Determines whether all objects in the list are strings"""
    return all(isinstance(x, str) for x in val)

def func1(val: List[object]):
    if is_str_list(val):
        print(" ".join(val)) # Error: invalid type

This code is correct, but a type checker will report a type error because > the value val passed to the join method is understood to be of type List[object]. The type checker does not have enough information to statically verify that the type of val is List[str] at this point.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文