0
0

More than 1 year has passed since last update.

dataclasses-json:`from __future__ import annotations`が有効な状態で`schema().load()`を実行するとwarningが発生する

Last updated at Posted at 2023-05-31

環境

  • Python 3.11.2
  • dataclasses-json 0.5.7
  • marshmallow 3.19.0

何が起きたのか?

以下のコードを実行したら、Task.schema().load()で、Unknown type int at Task.countというwarningが発生しました。

sample.py
from __future__ import annotations
from dataclasses_json import DataClassJsonMixin
from dataclasses import dataclass


@dataclass
class Task(DataClassJsonMixin):
    count: int


print("Use `Task.from_dict()`")
print(Task.from_dict({"count": 1}))
print("Use `Task.schema().load()`")
print(Task.schema().load({"count": 1}))
$ python sample.py
Use `Task.from_dict()`
Task(count=1)
Use `Task.schema().load()`
/home/vagrant/.pyenv/versions/3.11.2/lib/python3.11/site-packages/dataclasses_json/mm.py:271: UserWarning: Unknown type int at Task.count: int It's advised to pass the correct marshmallow type to `mm_field`.
  warnings.warn(
Task(count=1)

しかし、1行目のfrom __future__ import annotationsを取り除いたら警告は発生しませんでした。

原因

不明です。

対策

上記のコードはPython3.8でも動くようにしたいです。list,dictなども型ヒントに使いたいので、できればfrom __future__ import annotationsは残しておきたいです。
なので、Task.schema().load()を使わないようにしました。

Task.schema().load()は、dictのlistをDataClassのlistに1回で変換できるので重宝していたのですが、使用するのを諦めます。Task.from_dictとループで素直に実装します。

Task.schema().load([{"count": 1}, {"count":2}, ...])

補足

以下のissueに関係しているかもしれません。

0
0
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
0
0