tools-python
tools-python copied to clipboard
typing: fix dataclass_with_properties for static type checkers
Purpose of this PR:
Currently, all model in the codebase are implemented as dataclass with additional functionality provided by dataclass_with_properties. However, this approach causes static type checkers to fail in recognizing the dataclass structure.
To resolve this, I've introduced typing.dataclass_transform, which allows static type checkers to properly recognize and work with the enhanced dataclasses. This should improve type safety and make the code more robust from a type-checking perspective.
Demonstration:
Content of test.py:
import datetime
from spdx_tools.spdx.model import CreationInfo
def demo() -> CreationInfo:
return CreationInfo(
spdx_version="SPDX-2.3",
spdx_id="SPDXRef-DOCUMENT",
name="name",
document_namespace="https://testdomain.com",
creators=[],
created=datetime.datetime.now()
)
if __name__ == "__main__":
demo()
Without this fix:
tools-python ❯ .venv/bin/pyright test.py
tools-python/test.py
tools-python/test.py:6:15 - error: Expected class but received "(type[_T@dataclass]) -> type[_T@dataclass]" (reportGeneralTypeIssues)
tools-python/test.py:8:22 - error: Expected 1 more positional argument (reportCallIssue)
2 errors, 0 warnings, 0 informations
With this fix:
tools-python ❯ .venv/bin/pyright test.py
0 errors, 0 warnings, 0 informations
Ahhh, I’ve just realized that the typing.dataclass_transform was introduced in python 3.11, while this project supports and tests with python>=3.7.
I guess, close this PR then? Unless there's a plan to upgrade the minimum python version in the near future, or we can make it only run if python version is at least 3.11