Home > Software design >  Is it valid Python to use a __slots__ dictionary for initialization purposes?
Is it valid Python to use a __slots__ dictionary for initialization purposes?

Time:10-08

While searching for a convenient method to initialize slots, I had the stupid? idea of wrongly? using __slots__ dictionaries as shown below.

Note: There is a related question on SO where I've previously posted my idea as answer, but I though it might be more useful to create a new question from it as I'd really like to get more feedback.

So I'd appreciate any notes/advice/issues for the following "trick":

class Slotted:

    __slots__ = {}

    def __new__(cls, *args, **kwargs):
        inst = super().__new__(cls)
        for key, value in inst.__slots__.items():
            setattr(inst, key, value)
        return inst

class Magic(Slotted):

    __slots__ = {
        "foo": True,
        "bar": 17
    }
magic = Magic()

print(f"magic.foo = {magic.foo}")
print(f"magic.bar = {magic.bar}")
magic.foo = True
magic.bar = 17

Is it ok/safe to do this? Are there any drawbacks or possible probelms, etc.?

CodePudding user response:

The docs say that any iterable containing strings is allowed for __slots__, but it has a specific warning about mappings:

Any non-string iterable may be assigned to __slots__. Mappings may also be used; however, in the future, special meaning may be assigned to the values corresponding to each key.

I'm not aware of any active proposals to add such special meaning to a mapping used for __slots__, but that doesn't mean one might not be created in the future. I would keep an eye out for deprecation warnings as you use this code in future releases!

  • Related