Python 3.x - Run a function before adding an item to a list

In Python 3.x, is it possible to run a function before adding an item to the list?

I have a class that inherits from a list, with some additional custom functions. I would like a series of checks to be performed on the data of any element that is added to this list. If the added item does not meet certain criteria, the list causes an error.

class ListWithExtraFunctions(list):

   def __beforeappend__(self):

      ... run some code ...
      ... perform checks ...
      ... raise error if checks fail ...
+4
source share
2 answers

Define ListWithExtraFunctions.appendand call super().append(value)if it valuepasses all the checks:

class ListWithExtraFunctions(list):
    def append(self, value):
        if okay():
            return super().append(value)
        else:
            raise NotOkay()
+3
source

, Vaultah. "try... except", .

class Nw_list(list):


    def val_check(self, value):
        # Accepts only integer
        if type(value) == int:
            return value
        else:
            # Any other input type will raise exception 
            raise ValueError

    def append(self, value):
        try:
            # Try to append checked value
            super().append(self.val_check(value))                                      
        except ValueError:
            # If value error is raised prints msg
            print("You can append only int values")
0

Source: https://habr.com/ru/post/1626765/


All Articles