Python overrides dictionary access methods

Python overrides dictionary access methods … here is a solution to the problem.

Python overrides dictionary access methods

I have a class devices that inherits from the dict class. A device is a dictionary of dictionaries. I want to access its keys and values by using method call syntax as well as using normal syntax. Namely

class Devices(dict):
    def __init__(self):
        self['device'] = {'name':'device_name'}
    def __getattr__(self, name):
        value = self[name]
        return value
...

mydevices = Devices()
mydevice = mydevices.device #works and mydevices['device'] also works

#But what code do I need for the following?
name = mydevices.device.name 
mydevices.device.name = 'another_name'

I

know I can implement this if I override the __getattr__ and __setattr__ methods, but as you can see from my code, I’m not sure how to access the nested dictionary.
Does anyone know how to achieve this?

Thanks, lab rubbish

Solution

So your answer is already complete. You can define the type of structure you want:

class Devices(dict):
    def __init__(self,inpt={}):
        super(Devices,self).__init__(inpt)

def __getattr__(self, name):
        return self.__getitem__(name)

def __setattr__(self,name,value):
        self.__setitem__(name,value)

Then a use case is:

In [6]: x = Devices()

In [7]: x.devices = Devices({"name":"thom"})

In [8]: x.devices.name
Out[8]: 'thom'

Basically just nesting your property lookup dictionary.

Related Problems and Solutions