1

I know the init method is built automatically when creating a dataclass, but when I try this definition:

@dataclass
class LayoutCollection:
    root_folder_idx: dict = field(repr=False)
    folder_idx: dict = field(repr=False)
    layouts: List[Layout] = field(default_factory=list)

    def __post_init__(self):
        if len(self.folder_idx) == 0:
            self._populate_folder_index()
            self._populate_root_folder_index()
    
    def __repr__(self):
        return json.dumps(self.__dict__)

Anytime I run this code I get:

TypeError: __init__() missing 2 required positional arguments: 'root_folder_idx' and 'folder_idx'

If I re-order the arguments such that the layouts: attribute is first, I get:

TypeError: non-default argument 'root_folder_idx' follows default argument

I'm just trying to make it so that layouts initializes as a list of Layout objects, while the other two initialize as dict() but aren't represented during repr

1 Answer 1

2

Of course, right when I ask I figure it out.

On both of the attributes I wanted to initialize as dictionaries I needed to add default_factory defs, like this:

root_folder_idx: dict = field(default_factory=dict, repr=False)
Sign up to request clarification or add additional context in comments.

1 Comment

It's good that you figured it out. However, it is always suggested to ask such questions with the code that can be reproduced so that others can try that out and answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.