How to assign the return value from __setitem__() function

Question:

I have a custom __setitem__() function.

class Myclass:
    array = [[[1]*3]]
    def __setitem__(self, idcs, other):       
        # do something
        array[idcs] = other
        return 2

I would like to do something like this:

x = Myclass()
other = [1, 2, 3]
z = x.__setitem__([0:1, 0:1, 0:], other) # change the given range of x and assign the return value to 

But it doesn’t work and returns Invalid Syntax error. I expect the result to be this:

z == 2
x.array == [[[1, 2, 3]]]

What should I do?

Asked By: AES

||

Answers:

I’ve compiled some usage as I understood your question, but please take in consideration the following points :

  • your array is very convoluted / complex, do you really need it ?

  • the __setitem__ shouldn’t return value, only set it

  • the __getitem__ takes care for the returning a value

  • the provided example is a very rudimental example of eventual usage of the tandem __setitem__ / __getitem__ and the slice, also the data structure is a simple list

  • some subtleties arises if you change your data structure like that, shown with .multiple_assing()

from typing import Iterable
class CustomContainer:

    def __init__(self):
        # dummy data
        self._data = [1,2,3,4,5,6,7,8,9]

    def __setitem__(self, key, value):
        # valid for iterables only !
        self._data[key] = value

    def __getitem__(self, key):
        return self._data[key]

    def multiple_assing(self, slices: list[tuple], value:Iterable):
        for sl in slices:
           self[slice(*sl)] = value

    def __str__(self):
        return str(self._data)


if __name__ == "__main__":
    cc = CustomContainer()
    print(cc)
    # subtlety by the usage of such change
    # start         --> [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # first change  -->  x  x  x  x
    # changed to    --> [10, 4, 5, 6, 7, 8, 9]
    # second change -->            x  x  x  x
    # changed to    --> [10, 4, 5, 10]
    cc.multiple_assing([(0,3), (3,None,None)], [10])
    print(cc)
    # final         --> [10, 4, 5, 10]

Answered By: baskettaz
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.