分解工会的最佳方法

发布于 2025-01-29 00:14:50 字数 602 浏览 0 评论 0 原文

目标是坚持完全静态打字。 “解决”工会/可选类型并满足Mypy的最佳方法是什么? 例如:

from typing import Optional

def foo() -> bool:
    item: Optional[str] = find() # here find is some arbitrary search which returns a string in case something was found or None if nothing found.
    if(item == None):
        return False # Nothing found in the first place, could not execute bar()
    else:
        return bar(item) # here mypy is unsatisfied and tells me, that type Optional[str] is not applicable to type str.

def bar(str) -> bool:
    .....

那么,将可选的[str]“铸造”到str的最佳方法是什么?这是一种特定的毕pythonian方法吗?

Goal is to stick to fully static typings. What is the best way to "resolve" a Union/Optional type and satisfy mypy?
For Example:

from typing import Optional

def foo() -> bool:
    item: Optional[str] = find() # here find is some arbitrary search which returns a string in case something was found or None if nothing found.
    if(item == None):
        return False # Nothing found in the first place, could not execute bar()
    else:
        return bar(item) # here mypy is unsatisfied and tells me, that type Optional[str] is not applicable to type str.

def bar(str) -> bool:
    .....

So what would be the best way to "cast" the Optional[str] to str? Is tehre a specific pythonian way to do that?

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

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

发布评论

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

评论(1

野生奥特曼 2025-02-05 00:14:50

好的,在发布问题后,我在“相关”问题中找到了答案。
因此,这取决于:

正确的代码块将是:

from typing import Optional

def foo() -> bool:
    item: Optional[str] = find() # here find is some arbitrary search which returns a string in case something was found or None if nothing found.
    if(isinstance(item, str)):
        return bar(item) # OK for mypy
    else:
        return False # Nothing found in the first place, could not execute bar()

def bar(str) -> bool:
    .....

Okay, after Posting the question I found an answer in the "Related" questions.
So this is taken from:
Use attribute from Optional[Union[str, int]] parameter depending on its type

The correct code block would be:

from typing import Optional

def foo() -> bool:
    item: Optional[str] = find() # here find is some arbitrary search which returns a string in case something was found or None if nothing found.
    if(isinstance(item, str)):
        return bar(item) # OK for mypy
    else:
        return False # Nothing found in the first place, could not execute bar()

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