Skip to content
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

Branches #8451

Closed
quicknir opened this issue Feb 27, 2020 · 1 comment
Closed

Branches #8451

quicknir opened this issue Feb 27, 2020 · 1 comment

Comments

@quicknir
Copy link

I'm using mypy 0.740 and I'm finding the way it handles branches to be fairly annoying. If you assign a variable along every branch, mypy infers its type but simply looking at the first assignment. This leads to a lot of code that's obviously correct, but that mypy thinks is wrong (in my codebase):

def foo(x: Union[str, int]):
    pass

def bar(b: bool):
    if b:
        x = "hello"
    else:
        x = 7
    foo(x)

I have code very similar to above in my codebase; mypy will infer the type of the local variable x as str, and then complain when I assign an int. I'd suggest instead that if a variable is assigned in every branch, mypy take the union of the types. This comes up a lot with optional as well, where you assign x to some value in one branch, but None in the other. To resolve this, I explicitly set the type of x by writing x: Union[str, int] above the branch. The alternative would be doing it in the first branch, but this is asymmetric between the branches. On the other hand the way I've done it adds a whole line with no purpose except type checking, which is annoying as well (pick your poison).

Anyway quite possibly I'm totally wrong and there are counter-examples showing this is a terrible idea, or maybe it's super hard to implement, or maybe this is already implemented in the latest version. Just throwing it out there; generally mypy works very well with local variables. I generally only annotate functions and dataclasses and everything works fine, but this is proving to be the major exception for me.

@JukkaL
Copy link
Collaborator

JukkaL commented Feb 28, 2020

Closing as duplicate of #6233.

@JukkaL JukkaL closed this as completed Feb 28, 2020
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