0

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?

Mindxxxd
  • 75
  • 6

1 Answers1

0

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:
    .....
Mindxxxd
  • 75
  • 6
  • Hi. If another Q&A answers your question, you should close your question to avoid duplication. I've voted to close this question – joel May 15 '22 at 12:20
  • As a separate point, I think `if item is None:` is actually what you need. Don't compare with `None` using `==` – joel May 15 '22 at 12:20