Javascript-Style Dictionary Access

Date: 2013-09-17

In Javascript objects and associative arrays are almost exchangeable as you can access an object attribute either with the []-operator or the .-operator, which is really useful for make your code much more readable (personal opinion!):

var foo = object();
foo["name"] = 23;
foo.name = 23;

I really like this idiom in javascript, because when using the dot notation you have to put the key literally into the code and you cannot use a variable as accessor key. And i really started to miss this feature in Python, so i dug into the Python documentation and found the __getattr__ mechanism. And so i implemented a Javascript style dictionary (dictionary is the python notation for an hashed associative array):

class JSdict(dict):
    def __getattr__(self, name):
        return self[name]
    def __setattr__(self, name, value):
        self[name] = value
    def __delattr__(self, name):
        del self[name]

The JSdict class inherits from the standard dict-type to get all the normal dict methods (like the []-operator). Addionally to that __getattr__ is implemented to provide read access to the dictionary's content via the dot-notation. __getattr__ is only called, when the key is not provided by the class type (e.g. .keys() is not overriden). Similar to this __setattr__ and __delattr__ are also implemented. Now to a short example how this JSdict may be used:

d = JSdict()
d["foo"] = 23
d.bar    = 42
print d # {'foo': 23, 'bar': 42}

del d.bar
print d # {'foo': 23}

Additional: If you want to override every attribute lookup within an object (e.g. to override .keys() in this case) you may use __getattribute__, but there you have to handle every attribute lookup, except that for __getattribute__ itself. Of course implementing this inefficient, makes your attribute access very inefficient, because it is called very often.