How can I refactor this code to generalize the argument parsing? I feel like this code can be better but I can't find a way. The usage syntax of the index operator is similar to the NumPy indexing syntax.
def __getitem__(self, arg):
"""
[] operator to index elements in the matrix
Usage:
>> mat[0] returns first row
>> mat[3, :] return the 4th row
>> mat[:, 7] return the 8th column
>> mat[0, 0] returns first element
"""
if isinstance(arg, int):
return self.matrix[arg]
elif isinstance(arg, tuple):
if isinstance(arg[0], int) and isinstance(arg[1], int):
y, x = arg
return self.matrix[x][y]
elif isinstance(arg[0], slice) and isinstance(arg[1], int):
return self.get_column(arg[1])
elif isinstance(arg[0], int) and isinstance(arg[1], slice):
return self.get_column(arg[1])
else :
raise TypeError('Invalid indexing arguments type', arg)
Also, how can I make a setitem function that uses the [] operator to set columns without rewriting the getitem function inside it? Here is my current implementation without the possibility of setting a column.
def __setitem__(self, arg, value):
if isinstance(value, Fraction):
self[arg] = value
elif isinstance(value, list) and all(isinstance(elem, Fraction) for elem in value):
self[arg] = value
else:
raise TypeError('Invalid value type', value)