tools-python icon indicating copy to clipboard operation
tools-python copied to clipboard

typing: fix dataclass_with_properties for static type checkers

Open kukovecz opened this issue 5 months ago • 1 comments

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 

kukovecz avatar Sep 16 '24 08:09 kukovecz