Check if a given value is out of certain range

Marko Rauhamaa marko at pacujo.net
Mon Oct 5 07:42:41 EDT 2015


Jussi Piitulainen <harvesting at makes.email.invalid>:

> Michiel Overtoom writes:
>
>> Why not use a function?
>>
>>
>>     if outside(x, 0, 10):
>>         print("x has wrong value")
>>     else:
>>         print("x has good value")
>>
>>
>> where 'outside' is defined as:
>>
>>     def outside(value, lowerbound, upperbound):
>>         return value < lowerbound or value > upperbound  
>
> Wouldn't that be more readable as:?
>
>      def outside(value, lowerbound, upperbound):
>          return not (lowerbound <= value <= upperbound)

Why not use a fricking class framework:

    class Endpoint:
        def __init__(self, value):
            self.value = value

    class IncludedEndpoint(Endpoint):
        def above(self, x):
            return x > self.value

        def below(self, x):
            return x < self.value

    class ExcludedEndpoint(Endpoint):
        def above(self, x):
            return x >= self.value

        def below(self, x):
            return x <= self.value

    class Range:
        def __init__(self, lower_bound, upper_bound):
            self.lower_bound = lower_bound
            self.upper_bound = upper_bound

        def outside(self, x):
            return self.lower_bound.below(x) or self.upper_bound.above(x)

        def inside(self, x):
            return not self.outside(x)

Then, we could simply have:

    if Range(IncludedEndpoint(0), IncludedEndpoint(10)).outside(x):
        print("x has wrong value")
    else:
        print("x has good value")

Just for the sake of readability, I mean...


Marko



More information about the Python-list mailing list