Search code examples
pythonnestedpython-dataclasses

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.

{
  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.