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

constrained TypeVar does not allow default of one of the constraint choices #18017

Open
asottile-sentry opened this issue Oct 22, 2024 · 2 comments
Labels
bug mypy got something wrong topic-type-variables

Comments

@asottile-sentry
Copy link

I suspect this is related to #3737 but seems to be a specific sub-case that should be unambigious (and pyright accepts the code unchanged)

Bug Report

a constrained TypeVar T: (U, V) "T must be either U or V" does not accept either U or V as a default value

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=b7cc5486d300e5869277d59fa33a2b03

class U: pass
class V: pass

class C[T: (U, V)]:
    def __init__(self, tp: type[T] = U) -> None:
        self.x: dict[int, T] = {1: tp()}

(I kinda understand that mypy wouldn't know well enough that C() would actually be C[U] -- I've omitted overloads that make that work with mypy -- but the error on the default parameter still remains)

Expected Behavior

(no errors)

Actual Behavior

main.py:5: error: Incompatible default for argument "tp" (default has type "type[U]", argument has type "type[V]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

I'm guessing that for a constrained typevar mypy is just checking each possible constraint against the default value?

Your Environment

  • Mypy version used: 1.12.1
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12.x
@asottile-sentry asottile-sentry added the bug mypy got something wrong label Oct 22, 2024
@JelleZijlstra JelleZijlstra added the topic-pep-696 TypeVar defaults label Oct 23, 2024
@asottile-sentry
Copy link
Author

(fwiw I don't think this is PEP 696 related)

@JelleZijlstra JelleZijlstra added topic-type-variables and removed topic-pep-696 TypeVar defaults labels Oct 24, 2024
@apowers313
Copy link

I think I have another flavor of this same bug:

class Thing:
    pass

ThingCls = TypeVar("ThingCls", bound=type[Thing])

def thing_class_modifier(base: ThingCls = Thing) -> ThingCls:
    return base

Yields the error:

Incompatible default for argument "base" (default has type "type[Thing]", argument has type "ThingCls")

I've been told it works fine on pylance.

Mypy version: 1.11.1
Python version: 3.11.10
(can reproduce on mypy-play.net with mypy 1.13.0 and Python 3.12)

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

No branches or pull requests

3 participants