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

frozen dataclass in def __init__ and iteration on it

I want to use a frozen class as a structure as I don’t want to use any mutable objects in my code. But also I need to iterate on my_data. How can I make this work?

SideNote: dict is not an option

from dataclasses import dataclass

data = {'demo1': "description for demo 1", "demo2": 'description for demo 2'}


@dataclass(frozen=True)
class SomeDataclass:
    name: str
    description: str


class ParserClass:
    def __init__(self, some_data_class: SomeDataclass) -> None:
        self.my_data = some_data_class

    def parsing_method(self, demo_data) -> None:
        for data, description in demo_data.items():
            self.my_data(name=data, description=description)

test = ParserClass(SomeDataclass)
test.parsing_method(data)
for my_date in test.my_data:
    print(my_date.name, my_date.description)

of course, i’m getting an error

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

for my_date in test.my_data:
TypeError: 'type' object is not iterable

>Solution :

Did you mean to make a collection of instances?

from attrs import frozen

data = {'demo1': "description for demo 1", "demo2": 'description for demo 2'}

@frozen(kw_only=True)
class SomeDataclass:
    name: str
    description: str

class ParserClass:
    def __init__(self) -> None:
        self.my_data = []

    def parsing_method(self, demo_data) -> None:
        for data, description in demo_data.items():
            self.my_data.append(SomeDataclass(name=data, description=description))

test = ParserClass()
test.parsing_method(data)
for my_date in test.my_data:
    print(my_date.name, my_date.description)

Here ParserClass has a list at self.my_data and parsing_method() appends new instances of SomeDataclass to it.

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