Skip to content

MyPy does not work well with Unions #8383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ayushr2 opened this issue Feb 9, 2020 · 2 comments
Closed

MyPy does not work well with Unions #8383

ayushr2 opened this issue Feb 9, 2020 · 2 comments

Comments

@ayushr2
Copy link

ayushr2 commented Feb 9, 2020

MyPy complains with the following code:

def assert_equals(expected: Union[str, bytes], actual: Union[str, bytes]) -> bool:
    if type(expected) is str:
        expected = bytes(expected, "utf-8")
    if type(actual) is str:
        actual = bytes(actual, "utf-8")

    if expected == actual:
        return True
    else:
        logger.error(f"Expected: {expected!r}, Actual: {actual!r}.")
        return False


def assert_in(look: Union[str, bytes], where: Union[str, bytes]) -> bool:
    if type(look) is str:
        look = bytes(look, "utf-8")
    if type(where) is str:
        where = bytes(where, "utf-8")

    if look in where:
        return True
    else:
        logger.error(f"Looking for {look!r}, but contents are {where!r}.")
        return False

The error is:

line 3: error: Argument 1 to "bytes" has incompatible type "Union[str, bytes]"; expected "str"
line 5: error: Argument 1 to "bytes" has incompatible type "Union[str, bytes]"; expected "str"
line 16: error: Argument 1 to "bytes" has incompatible type "Union[str, bytes]"; expected "str"
line 18: error: Argument 1 to "bytes" has incompatible type "Union[str, bytes]"; expected "str"
line 20: error: Unsupported operand types for in ("Union[str, bytes]" and "Union[str, bytes]")

So even though we convert the variables to a specific type, MyPy still thinks that it is of type Union.

@Michael0x2a
Copy link
Collaborator

This is because mypy does not support type narrowing based on expressions of the form if type(var) == T. You need to do if isinstance(var, T) instead.

#7260 has some more related discussion.

@ayushr2
Copy link
Author

ayushr2 commented Feb 10, 2020

Thank you so much, that fixed the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants