-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Mypy reports incompatible types for an optional dataclass field with generic default factory #11923
Comments
def optional_list() -> list | None:
return list()
@dataclass
class A:
x: Optional[List[int]] = field(default_factory=optional_list) Or even more convenient : from dataclasses import dataclass, field
from typing import List, Optional, TypeVar, Callable
T = TypeVar("T")
def optional(type: type[T]) -> Callable[[], T | None]:
def factory() -> T | None:
return type()
return factory
@dataclass
class A:
x: Optional[List[int]] = field(default_factory=optional(list)) |
Same problem with the default dict factory, which should create an empty dictionary. from typing import Dict, Any
from dataclasses import dataclass, field
@dataclasses.dataclass
class A:
data: Dict[str, Any] = dataclasses.field(default_factory=dict) Error text
|
Another workaround: from typing import Dict, Any, cast
from dataclasses import dataclass, field
@dataclasses.dataclass
class A:
data: Dict[str, Any] = dataclasses.field(default_factory=cast(Dict[str, Any], dict)) |
I think the workaround above has a mistake in it - it tries to cast a callable into a dictionary. The correct one is: from typing import Dict, List, Optional, Tuple, Any, cast, Callable
from dataclasses import dataclass, field
@dataclass
class A:
data: Dict[str, Any] = field(default_factory=cast(Callable[[], Dict[str, Any]], dict)) |
The original examples passes without errors on current master. |
Bug Report
In a dataclass with an optional field with a generic as the default factory, mypy reports that the types are incompatible when there should be no compatibility issue between them.
Expected Behavior
A bare list is compatible with
Optional[List[int]]
, so no error should be reported.Actual Behavior
Your Environment
The text was updated successfully, but these errors were encountered: