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

with-syntax makes mypy confuse int with Any #9750

Closed
Hi-Angel opened this issue Nov 23, 2020 · 4 comments
Closed

with-syntax makes mypy confuse int with Any #9750

Hi-Angel opened this issue Nov 23, 2020 · 4 comments
Labels
bug mypy got something wrong

Comments

@Hi-Angel
Copy link

Bug Report

When an object is declared with with syntax, and then a method of that object is called, mypy thinks that method returns Any, even if the method is properly annotated to return something else. Removing with and declaring the object explicitly makes it work.

To Reproduce (in terms of terminal commands)

 λ cat test.py
class Connection:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    def register_method(self) -> int:
        return 1

def foo() -> int:
    with Connection() as conn:
        return conn.register_method()
 λ mypy test.py --warn-return-any
test.py:13: error: Returning Any from function declared to return "int"
Found 1 error in 1 file (checked 1 source file)

Expected Behavior

mypy would return no errors.

Actual Behavior

mypy returned errors.

Your Environment

  • Mypy version used: 0.790
  • Mypy command-line flags: --warn-return-any
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8.6
  • Operating system and version: Archlinux
@Hi-Angel Hi-Angel added the bug mypy got something wrong label Nov 23, 2020
@hauntsaninja
Copy link
Collaborator

You need to annotate __enter__ for mypy to know what type conn is. If you do that, things work. --warn-return-any is a little finicky, and I don't recommend using it without --strict / --disallow-untyped-defs

@Hi-Angel
Copy link
Author

Hi-Angel commented Nov 23, 2020

You need to annotate __enter__ for mypy to know what type conn is.

Thanks! Could you please elaborate here, I don't see any way to annotate __enter__. I mean, I can do this:

[…]
class Connection:
    def __enter__(self) -> Connection:
        return self
[…]

…but it makes python complain: NameError: name 'Connection' is not defined

@hauntsaninja
Copy link
Collaborator

from __future__ import annotations if on Python 3.7 or better, or -> "Connection" otherwise.

@Hi-Angel
Copy link
Author

Oh, cool, that does the trick, thank you!

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

No branches or pull requests

2 participants