環境
- Python 3.11.2
- dataclasses-json 0.5.7
- mypy 1.3.0
本題
@dataclass_json
でデータクラスを定義して、dataclass_json
が用意したfrom_dict
関数などを呼び出すと、「そんな属性はない」とmypyに怒られます。
from dataclasses_json import dataclass_json, DataClassJsonMixin
from dataclasses import dataclass
@dataclass_json
@dataclass
class Task:
value: int
Task.from_dict({"value": 1})
$ mypy sample.py
sample.py:11: error: "Type[Task]" has no attribute "from_dict" [attr-defined]
mypyなどのlinterを使う場合は、DataClassJsonMixin
を継承してデータクラスを定義しましょう。
@dataclass
class Task(DataClassJsonMixin):
value: int
Task.from_dict({"value": 1})
$ mypy sample.py
Success: no issues found in 1 source file
Pick whichever approach suits your taste. Note that there is better support for the mixin approach when using static analysis tools (e.g. linting, typing), but the differences in implementation will be invisible in runtime usage. 1