dataclass fields with default values misscategorized as class variables
ItsDrike opened this issue · 2 comments
In this example:
@dataclass
class SemanticVersion:
__slots__ = ("version", "prerelease", "build_metadata")
version: tuple[int, int, int]
prerelease: Optional[tuple[str, ...]] = None
build_metadata: Optional[tuple[str, ...]] = None
slotscheck reports a failed import, due to prerelease
(and build_metadata
) being in __slots__
conflicting with class variables.
However clearly, these aren't actually class variables, they're in fact just fields of a dataclass with some default values. Slotscheck should probably be able to distinguish between actual class variables and usage in dataclasses, to prevent this false positive.
Note that sometimes, variables defined like this can actually be considered class variables by the dataclass decorator, but only if they're type-hinted as one, or if they aren't type hinted at all, see this example:
from typing import ClassVar
@dataclass
class Foobar:
FOO: ClassVar[int] = 5 # actual class variable, not present in generated `__init__`
BAR = 10 # another class variable, not present in generated `__init__`
x: int = 2 # instance variable, with default value in `__init__`
Actually, turns out this isn't an issue with slotscheck, it's an issue with python itself.
This ValueError is raised on runtime not just when using slotscheck, as dataclasses just don't seem to properly support slots below python 3.10, which added the slots
parameter to the dataclass decorator.
@ItsDrike thanks for posting though, I did a quick check myself and come to the same conclusion. Perhaps I can make the error messages clearer to make it clear that import errors are generally due to the code itself, not slotscheck
.