LoginSignup
1
1

dataclasses-json:`DataClassJsonMixin`を継承してデータクラスを定義すれば、mypyに怒られない

Last updated at Posted at 2023-05-31

環境

本題

@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

  1. https://github.com/lidatong/dataclasses-json#approach-2-inherit-from-a-mixin

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1