Search code examples
pythonlistnonetypebuilt-in

Python: How can I set the default behaviour of NoneType objects?


I have created my own class that inherits from python's default list class. A simplified version is the following, that contains the __abs__ method so I can use python's abs function.

class DataSet(list):

    def __abs__(self):
        result = []
        for i in self:
            result.append(abs(i))
        return result

Suppose have a DataSet that sometimes contains a NoneType value, for example

>>> dataset = DataSet([1, 2, 3, None, -1, -2, -3])

If I want to know the absolute value of this DataSet, I use the function

>>> abs_dataset = abs(dataset)

The result that I want to get is

[1, 2, 3, None, 1, 2, 3]

but because there is a value of type NoneType in the dataset, I get the error

TypeError: bad operand type for abs(): 'NoneType'

For this one case it can be fixed by modifying the DataSet's __abs__ function and to check for None in the individual elements of the DataSet, but in my case I have more cases where a None value can occur and I also want to implement more builtin functions than only abs. Is there a method to set this default behaviour of default python functions like abs to None values?


Solution

  • You can do something like this.

    class DataSet(list):
    
        def __abs__(self):
            # Here if i is 0 then it'll be 0. 
            # No need to check for `None`.
            return [abs(i) if i else i for i in self]
    
    dataset = DataSet([1, 2, 3, None, -1, -2, -3])
    print(abs(dataset))
    # [1, 2, 3, None, 1, 2, 3]
    

    Edits:
    As mentioned by @juanpa.arrivillaga, if you want to filter the None type elements then you can do something like [abs(i) for i in self if i is not None] inside list comprehension.