Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Default value for nested dataclasses

I got the following dataclasses in Python:

@dataclass
class B(baseClass):

  d: float
  e: int


@dataclass
class A(baseClass):

  b: B
  c: str

I have this configured so that the baseClass allows to get the variables of each class from a config.json file. This file contains the following nested dictionary.

{
  a: {
    b: {
       "d": a_float_value
       "e": a_int_value
    }
    c: a_string_value
}

But the key "b" can be an empty dict.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  a: {
    b: {}
    c: a_string_value
}

But how do I integrate this into my dataclasses?
I tried

@dataclass
class B(baseClass):

  d: float
  e: int


@dataclass
class A(baseClass):

  b: Optional[B] = {}
  c: str

and

@dataclass
class B(baseClass):

  d: float
  e: int


@dataclass
class A(baseClass):

  b: B = field(default_factory=dict)
  c: str

But this doesn’t seem to work.

>Solution :

Could you try something like this by explicitly using the field class from dataclasses:

from typing import Dict, Optional
from dataclasses import dataclass, field

@dataclass
class B:

  d: float
  e: int

@dataclass
class A:
  c: str
  b: Optional[B] = field(default_factory=dict)


obj = A(c='sds')
print(obj.b)

Output was an empty dictionary for b variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading