Home > Mobile >  AssertionError raised even when requirements are met in a class attribute?
AssertionError raised even when requirements are met in a class attribute?

Time:10-28

I have a class Interval with a class attribute compare_mode set to None. The compare_mode is used for relational operators, comparing the values based on the different "modes".

When compare_mode is 'liberal' or 'conservative' it should go to their respective if-else statements in __lt__ and do the comparison, but even if I've set compare_mode to 'liberal' or 'conservative', the AssertionError is raised in __lt__ as if the value is still None?

I'm not sure what's going on here. Any explanation would be appreciated.

class Interval:
    compare_mode = None
    def __init__(self, mini, maxi):
        self.mini = mini
        self.maxi = maxi
        
    @staticmethod
    def min_max(mini, maxi = None):
        assert isinstance(mini, (int,float)), "Minimum value must be an int or float"
        if maxi != None:
            assert isinstance(maxi, (int,float)), "Maximum value must be an int, float, or None"
        if maxi != None and mini > maxi:
            raise AssertionError('Minimum value is greater than the maximum value')
        elif maxi == None and isinstance(mini, (int, float)):
            maxi = mini
        return Interval(mini, maxi)

    def __lt__(self, other):
        if Interval.compare_mode != 'liberal' or Interval.compare_mode != 'conservative':
            raise AssertionError
        if not isinstance(other, (int, float, Interval)):
            return NotImplemented
        if Interval.compare_mode == 'liberal':
            if isinstance(other, (int,float)):
                return ((self.mini   self.maxi) / 2) < other
            else:
                return ((self.mini   self.maxi) / 2) < ((other.mini   other.maxi) / 2)
        elif Interval.compare_mode == 'conservative':
            if isinstance(other, (int,float)):
                return self.maxi < other
            else:
                return self.maxi < other.mini

if __name__ == '__main__':
    l = Interval.min_max(1.0,5.0)
    r = Interval.min_max(4.0,6.0)
    e = Interval.min_max(4.0,4.0)
    
    Interval.compare_mode = 'liberal'
    print(l<l)

>>> AssertionError:

CodePudding user response:

Change your condition to

Interval.compare_mode != 'liberal' and Interval.compare_mode != 'conservative'
  • Related