-1

I am currently working with dataclasses which a class is a composite of another. The code below should have resulted in an error and it did not.

@dataclass
class kk:
    p: int
    tr: int

@dataclass
class xx:
    x: int
    y: int 
    kq: kk


somkq = kk(p=1, tr=3)
somxx = xx(x=1, y=2, kq=somkq)
print(somkq)
print(somxx)

x_dict = {"x":1, "y":2, "kq":{"pk":1, "tr":3}}
print(xx(**x_dict), asdict(xx(**x_dict)))

My thoughts on why an error should occur: Per default, xx(**dict_obj) should have raised a TypeError: __init__() ... since it was not defined "pk" in kq.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Dataclasses do not do *any* sort of validation, nor do they care about instantiating attributes as classes. – deceze Aug 26 '22 at 05:25

1 Answers1

0

Regular dicts have no validation like you are looking for. In fact I can do:

class KK:
    p = 1

k = KK()
k.q = 2

Now k has 2 attributes p and q.

What you might want to do is use pydantic.

from pydantic import BaseModel


class KK(BaseModel):
    p: int
    tr: int


class XX(BaseModel):
    x: int
    y: int
    kq: kk

Now

x_dict = {"x":1, "y":2, "kq":{"pk":1, "tr":3}}
print(xx(**x_dict))

will throw a pydantic ValidationError.

Finally, I don't think this line: somkq = kk(p=1, tr=3) in your example works. The class kk cannot be instantiated unless you add a def __init__().

OlafdeL
  • 81
  • 1
  • 5