Home > database >  Accessing dictionary inside a dictionary as attribute in python
Accessing dictionary inside a dictionary as attribute in python

Time:10-09

I am making a simple Entity Component System in python using dictionaries (I heard they have better performance somehow), but I didn't wanted access the data like foo['bar']['x'], and wanted to access it more like foo.bar.x (just personal preference)

So I made this code

class Entity(dict):
    def __init__(self, dictionary={}):
        super().__init__(dictionary)

    def __getattr__(self, attribute):
        return self[attribute]

foo = Entity([('PositionComponent', {'x': 0, 'y': 0})])

So, I can access the PositionComponent as foo.PositionComponent but I cant access the x value as foo.PositionComponent.x

How could I make it work? And is there a better way to make what I've already made?

CodePudding user response:

You can't access the x value because it belongs to a dict instance, not a Entity one. A possible workaround would be to only use Entity.

Also, since you're inheriting from dict you can use **kwargs for building your objects.

class Entity(dict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def __getattr__(self, attribute):
        return self[attribute]

foo = Entity(PositionComponent=Entity(x=0, y=1))
print(foo.PositionComponent.x)
>>> 0
  • Related