解散Union的最佳方式



目标是坚持完全静态类型。"解决"问题的最佳方法是什么?一个Union/Optional类型,满足mymyy ?例如:

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:
.....

那么用什么方法来"cast"可选的[str]到str?有没有特定的python方法来实现?

好吧,在发布问题之后,我在"Related"找到了答案。的问题。这是取自:根据可选[Union[str, int]]参数的类型使用属性

正确的代码块应该是:
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:
.....

相关内容

  • 没有找到相关文章

最新更新