Skip to content

dataclasses: optional generic fields with non-None defaults #15887

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
eltoder opened this issue Aug 16, 2023 · 4 comments
Closed

dataclasses: optional generic fields with non-None defaults #15887

eltoder opened this issue Aug 16, 2023 · 4 comments
Labels
bug mypy got something wrong topic-dataclasses topic-type-context Type context / bidirectional inference

Comments

@eltoder
Copy link

eltoder commented Aug 16, 2023

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=bcf4de945268517a0cd8b6b9835e852f

from dataclasses import dataclass, field
from typing import Generic, TypeVar

T = TypeVar("T")

class V(Generic[T]):
    def __init__(self, *v: T) -> None:
        pass

class C:
    x: dict[str, int] | None = field(default_factory=dict)
    y: V[int] | None = field(default=V())

Expected Behavior

This should produce no errors.

Actual Behavior

main.py:11: error: Incompatible types in assignment (expression has type "dict[_KT, _VT]", variable has type "dict[str, int] | None")  [assignment]
main.py:12: error: Incompatible types in assignment (expression has type "V[<nothing>]", variable has type "V[int] | None")  [assignment]
Found 2 errors in 1 file (checked 1 source file)

If I remove | None, mypy works as expected. However, AFAICT, outside of dataclasses such assignments are accepted.

Your Environment

  • Mypy version used: 1.5.0
  • Python version used: 3.11
@eltoder eltoder added the bug mypy got something wrong label Aug 16, 2023
@AlexWaygood AlexWaygood added topic-dataclasses topic-type-context Type context / bidirectional inference labels Aug 16, 2023
@eltoder
Copy link
Author

eltoder commented Aug 16, 2023

Also, if I change y to use direct assignment instead of using field, the second error disappears:

class C:
    x: dict[str, int] | None = field(default_factory=dict)
    y: V[int] | None = V()  # no error this way

@erictraut
Copy link

Here's a workaround that type checks without errors:

class C:
    x: dict[str, int] | None = field(default_factory=dict[str, int])
    y: V[int] | None = field(default=V[int]())

@Viicos
Copy link
Contributor

Viicos commented Nov 24, 2024

Can be closed as it seems to work as expected on mypy 1.13.

@brianschubert
Copy link
Collaborator

Thanks! FTR, this was fixed #16345

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-dataclasses topic-type-context Type context / bidirectional inference
Projects
None yet
Development

No branches or pull requests

5 participants