Home > Software engineering >  frozen dataclass in def __init__ and iteration on it
frozen dataclass in def __init__ and iteration on it

Time:08-11

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

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

CodePudding user response:

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.

  • Related