[Python] Check validity of interdependent arguments at init

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    I would like some input on what the most efficient way is to check the validity of interdependent arguments in a class using native Python. I know of Pydantic, which could be a good tool for us, but our current code doesn't use it and it is not an option for now.

    Our current implementation looks like the following example where validity checks are done at multiple places (at init and at each setter). But in many cases we have 5 arguments with complex relations that all need to be checked before initiation and when changes are applied. The reason is that we want to prevent erroneous data from entering our database which is updated when new objects are initiated.

    So my question is: Are there more efficient ways to do this?

    class Foo()

    def __init__(self, a, b)

    self._check_validity(a, b)

    self._a = a
    self._b = b

    @staticmethod
    def _check_a_larger_b(a, b):
    if a =< b:
    raise ValueError("a must be larger than b")

    @staticmethod
    def _check_total(a, b):
    if a + b > 100:
    raise ValueError("The sum of a and b can't be larger than 100")

    @staticmethod
    def _check_validity(a, b):
    self._check_a_larger_b(a, b)
    self._check_total(a, b)

    @property
    def a(self):
    return self._a

    @a.setter
    def a(self, new_value)
    if not new_value > 0:
    raise ValueError("Must be larger than 0")
    self._check_validity(new_value, self._b)
    self._a = new_value

    @property
    def b(self):
    return self._b

    @a.setter
    def b(self, new_value)
    if not new_value > 0:
    raise ValueError("Must be larger than 0")
    self._check_validity(self._a, new_value)
    self._b = new_value

    Continue reading...

Compartilhe esta Página