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

Parsing of Walrus Operator #8053

Closed
rvanlaar opened this issue Dec 2, 2019 · 7 comments
Closed

Parsing of Walrus Operator #8053

rvanlaar opened this issue Dec 2, 2019 · 7 comments

Comments

@rvanlaar
Copy link
Contributor

rvanlaar commented Dec 2, 2019

Mypy doesn't seem to handle variable type changes that happen with a walrus operator.

What happens here is: the walrus operator makes it a boolean:
while i:= update(i) > 0.

This is what needs to happen to check for i > 0 and i still being an int.
while (i:= update(i)) > 0 .

The following python code doesn't give any errors with mypy 0.750:

def walrus1(i: int) -> int:
    """Actually returns bool"""
    while i:= i > 0:
       return i 
    return i

def walrus2(i: int) -> int:
    """Works correctly."""
    while (i:= i) > 0:
        return i
    return i

assert walrus1(5) == True
assert walrus1(0) == False
assert walrus2(5) == 5
assert walrus2(0) == 0
@rvanlaar
Copy link
Contributor Author

rvanlaar commented Dec 2, 2019

Where in the mypy code can I loop If I were to try to make a pull request?

@JelleZijlstra
Copy link
Member

I don't know exactly, but #6899 is the PR where I added (limited) support for the walrus operator, so the bug may be in the code added there.

@rvanlaar
Copy link
Contributor Author

rvanlaar commented Dec 2, 2019

It seems that bool is a covariant of int.

In the following example: x and is alright, y and z aren't.

x: int
x = True

y: bool
y = 5

z: str
z = True

@JelleZijlstra
Copy link
Member

Right, bool is a subclass of int, so mypy sees that the function still returns a kind of int.

@rvanlaar
Copy link
Contributor Author

rvanlaar commented Dec 3, 2019

Which wasn't what I expected. Even with years of python experience.

Could the table on https://mypy.readthedocs.io/en/latest/builtin_types.html be updated?
That's were I looked for an explanation.

I would expect that the definition of bool there would be a subtype of int.

@JukkaL
Copy link
Collaborator

JukkaL commented Dec 3, 2019

@rvanlaar Sure, updating the table is good idea. Would like to create a PR (or a separate issue to track it)?

@rvanlaar
Copy link
Contributor Author

rvanlaar commented Dec 4, 2019

Closing this issue, continue with issue #8069 to document it.

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

3 participants