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

dataclassでdictの初期値を設定する方法

Posted at

Pythonのdataclassでdictに {}で初期化すると default_factory エラーが発生します。

@dataclass
class Record:
    """
    結果クラス
    """
    name: str = ''
    result_dict: dict[str, float] = {}

実行結果

ValueError: mutable default <class 'dict'> for field result_dict is not allowed: use default_factory

エラーメッセージの通り、filedをimportとしてdefault_factoryで設定します。

import pandas as pd
import numpy as np
from dataclasses import dataclass, field

@dataclass
class Record:
    """
    結果クラス
    """
    name: str = ''
    result_dict: dict[str, float] = field(default_factory=dict)

def main():
    record = Record()
    record.name = 'test'
    record.result_dict['test'] = 1.0
    print(record)

    record2 = Record()
    record2.name = 'test'
    print(record2)

if __name__ == '__main__':
    main()

実行結果

Record(name='test', result_dict={'test': 1.0})
Record(name='test', result_dict={})
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?