Reputation: 1999
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?
Upvotes: 0
Views: 942
Reputation: 11662
A cheesy and somewhat unprofessional way is to annotate it with any random string value.
So, for example:
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d: 'help,, i dunno how [a]ny of this w@rks!!' = "nope"
c = C(5)
print(asdict(c))
# this returns
# {'a': 5, 'b': 3, 'c': 'yes', 'd': 'nope'}
With some thought, this can actually be simplified down to:
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d: ... = "nope"
Upvotes: 0
Reputation: 79
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!
Upvotes: 1