Denis
Denis

Reputation: 3707

Circular dependency in the class constructor

I have the following class:

class CustomDictionary(dict):
    def __init__(self, val, *args, **kwargs):
        self.wk = val
        super(dict, self).__init__()

    def __setattr__(self, key, value):
        if key in self.wk:
            raise Exception("Wrong key", "")

        key = key.replace(" ", "_")
        self.__dict__[key] = value


def main():
    wrong_keys = ("r23", "fwfew", "s43t")

    dictionary = CustomDictionary(wrong_keys)

    dictionary["a1"] = 1

As you can see, I create the attribute wk in the constructor. But I have __setattr__ function, in which I work with attribute wk. However, CustomDictionary object has no attribute wk.

Upvotes: 1

Views: 100

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69041

__setattr__ is a pain that way, because it is called for every assignment to an instance member. Probably the easiest fix for your situation is to define an empty wk before __init__:

class CustomDictionary(dict):

    wk = []

    def __init__(self, val, *args, **kwargs):
        self.wk = val
        ...

Upvotes: 1

Related Questions