Skip to content

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

Closed
@glyph

Description

@glyph

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions