Search code examples
pythonpython-dataclasses

python dataclass asdict ignores attributes without type annotation


Python documentation explains how to use dataclass asdict but it does not tell that attributes without type annotations are ignored:

from dataclasses import dataclass, asdict

@dataclass
class C:
  a : int
  b : int = 3
  c : str = "yes"
  d = "nope"

c = C(5)
asdict(c)
# this returns
# {'a': 5, 'b': 3, 'c': 'yes'}
# note that d is ignored

How can I make d attribute appear in the returned dict without implementing the function myself?


Solution

  • You can use Any as type annotation. For example:

    from typing import Any
    from dataclasses import dataclass, asdict
    
    @dataclass
    class C:
      a : int
      b : int = 3
      c : str = "yes"
      d : Any = "nope"
    
    c = C(5)
    asdict(c)
    # this returns
    # {'a': 5, 'b': 3, 'c': 'yes', 'd': 'nope'}
    # Now, d is included as well!