[Python] mypy type hinting between calling function with different types

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have two functions, one which accepts lists or strings and returns the type that was input and another which accepts a string and calls the first function which is used in the result.

    A simplified example of this is:

    def accepts_string_or_list(inputs: str | list) -> str | list:
    if isinstance(inputs, list):
    return inputs + ['1']
    return inputs + '1'


    def accepts_string(inputs: str) -> str:
    # do something to inputs string
    return accepts_string_or_list(inputs)


    Mypy complains on the very last line that "Incompatible return value type (got "str | list[Any]", expected "str") [return-value]mypy". I know that the accepts_string function will always accept a string which implies that the return value of accepts_string_or_list (when used in accepts_string) will always return a string. Mypy doesn't know this, but how do I make type hinting work correctly here?

    I know I could change the output type of accepts_string to be str | list instead of str. This would remove the error message, but would be untrue because only strings will be returned. For this reason, I would not want to do this.

    Continue reading...

Compartilhe esta Página