Skip to content Skip to sidebar Skip to footer

Are There Any 'gotchas' With This Python Pattern?

Here's the pattern I'm thinking of using: class Dicty(dict): def __init__(self): self.__dict__ = self d = Dicty() d.foo = 'bar' print d['foo'] >>> bar

Solution 1:

Here's a less "hacky" way to achieve the same effect:

class Dicty(dict):
    def __getattr__(self, key):
        return self[key]

    def __setattr__(self, key, value):
        self[key] = value

I think that your way may work fine as well, but setting the __dict__ attribute like that seems a bit iffy style-wise, and is bound to raise some questions if anyone else ends up reading your code.


Solution 2:

Don't set self.__dict__. Call __init__(self, *args, **kwargs) on the superclass. Also, dict inherits from object so you don't need to specify it.


Solution 3:

A couple of things. One is if you try and use a dictionary method, such as keys, you won't be able to get it now. There were some other issues I ran into, such as being pickle-able and copy-able.

But I have implemented something that does this without those problems. You can see it here, it's the AttrDict class in the dictlib.py module. That module also contains a class that can wrap another mapping style object, in cases where it can't be subclassed.


Post a Comment for "Are There Any 'gotchas' With This Python Pattern?"