KEMBAR78
Add narrowing and closures to common issues by hauntsaninja · Pull Request #9956 · python/mypy · GitHub
Skip to content

Conversation

@hauntsaninja
Copy link
Collaborator

This one is on our issue tracker's greatest hits.
Here's the issue I usually link: #2608

This one is on our issue tracker's greatest hits.
Here's the issue I usually link: python#2608
@sirosen
Copy link

sirosen commented Jan 24, 2021

Huge 👍 to adding this.

I think it would be helpful to have an example rather than just saying "assign y = x and use y".

You may need to annotate the type of the reassigned variable, depending on your case. Here's a minimal example of what I mean:

def outer(x: typing.Union[None, int, float]):
    if isinstance(x, float):
        x_: typing.Optional[int] = int(x)
    else:
        x_ = x

    def inner() -> int:
        if x_:
            return x_ + 1
        else:
            return 0

    return inner

Without x_ annotated, mypy will deduce its type -- correctly -- from the first assignment as int. But we're really trying to narrow the union down to Optional[int] in this case.

So maybe it would be best to advise people that you "may need to annotate the reassignment in some cases" or something?

@hauntsaninja hauntsaninja merged commit 8780d45 into python:master Feb 19, 2021
@hauntsaninja hauntsaninja deleted the example branch February 19, 2021 19:17
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

Successfully merging this pull request may close these issues.

2 participants