Search code examples
pythonattributesoperator-overloadingvariable-assignmentmagic-methods

Bracket assignment in Python


I would like to create a class that is able to do the following

class Test:
    # code here

test = Test()
test["test"] = 1
test.test  # returns 1

Is this possible in Python using magic methods (e.g. not inheriting from dict)?


Solution

  • You could override __getitem__ and __setitem__ using getattr and setattr:

    class Test:
        def __getitem__(self, key):
            return getattr(self, key)
    
        def __setitem__(self, key, value):
            setattr(self, key, value)
    
    
    test = Test()
    test["test1"] = 1
    print(test.test1)
    

    Using this method, you can also set from the attribute and get from the square bracket operator:

    test = Test()
    test.test2 = 2
    print(test["test2"])
    

    If you wanted to use this among many classes then you could turn this into a base class:

    class ItemAttributes:
        def __getitem__(self, key):
            return getattr(self, key)
    
        def __setitem__(self, key, value):
            setattr(self, key, value)
    
    
    class Test(ItemAttributes):
        pass