2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

dataclasses-json:データクラスのフィールドの型に`list`などを使うと、`TypeError: 'type' object is not subscriptable`エラーが発生する

Last updated at Posted at 2022-01-26

実行環境

  • Python3.8.6
  • dataclasses-json 0.4.5

やりたいこと

dataclasses-jsonを使って、dictからデータクラスに変換したいです。

エラー発生

以下のコードを実行すると、TypeError: 'type' object is not subscriptableが発生しました。

foo.py
from __future__ import annotations
from dataclasses import dataclass
from dataclasses_json import dataclass_json


@dataclass_json
@dataclass
class Person:
    name: str
    club: list[str]


d = {"name": "Alice", "club": ["tennis", "soccer"]}
person = Person.from_dict(d)
print(person)
$ python foo.py
Traceback (most recent call last):
  File "foo2.py", line 14, in <module>
    person = Person.from_dict(d)
  File "/home/vagrant/.pyenv/versions/3.8.6/lib/python3.8/site-packages/dataclasses_json/api.py", line 83, in from_dict
    return _decode_dataclass(cls, kvs, infer_missing)
  File "/home/vagrant/.pyenv/versions/3.8.6/lib/python3.8/site-packages/dataclasses_json/core.py", line 152, in _decode_dataclass
    types = get_type_hints(cls)
  File "/home/vagrant/.pyenv/versions/3.8.6/lib/python3.8/typing.py", line 1232, in get_type_hints
    value = _eval_type(value, base_globals, localns)
  File "/home/vagrant/.pyenv/versions/3.8.6/lib/python3.8/typing.py", line 270, in _eval_type
    return t._evaluate(globalns, localns)
  File "/home/vagrant/.pyenv/versions/3.8.6/lib/python3.8/typing.py", line 518, in _evaluate
    eval(self.__forward_code__, globalns, localns),
  File "<string>", line 1, in <module>
TypeError: 'type' object is not subscriptable

原因

フィールドclubの型list[str]が原因のようです。
型がtyping.Listならば、エラーは発生しませんでした。

import typing
@dataclass_json
@dataclass
class Person:
    name: str
    club: typing.List[str]

またPython3.9.7ならエラーは発生しませんでした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?