Skip to content

generic parameter with None default populates its TypeVar as Optional when it should just be None sometimes #9468

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
glyph opened this issue Sep 22, 2020 · 2 comments
Labels
bug mypy got something wrong

Comments

@glyph
Copy link

glyph commented Sep 22, 2020

Bug Report

This program

from typing import TypeVar
T = TypeVar("T")

def returner(x: T = None) -> T:
    return x

produces this error

...:5: error: Incompatible return value type (got "Optional[T]", expected "T")

But returner(None) is not Optional; it should just populate T as None in that case and carry on. I don't want it to be Optional for other types since that just complicates passing through T.

If I change the None to, say, 0, I get instead:

...:4: error: Incompatible default for argument "x" (default has type "int", argument has type "T")

I assume the way to work around this for now is with overrides, but I don't understand if there's some type-theoretic underpinning to this behavior or it's just a bug.

Your Environment

  • Mypy version used: 0.782
  • Mypy command-line flags: (None)
  • Mypy configuration options from mypy.ini (and other config files): (None)
  • Python version used: 3.8.5
  • Operating system and version:
ProductName:	Mac OS X
ProductVersion:	10.15.6
BuildVersion:	19G2021
@hauntsaninja
Copy link
Collaborator

Dupe of #3737, #8708, #8739, #9179, #9432 and others. First of those has the most discussion (see Guido's and Anders' comments)

@glyph
Copy link
Author

glyph commented Sep 22, 2020

Thank you @hauntsaninja. I swear I looked for those first, and I did have a feeling they were there :)

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