Andrea Mancini
Andrea Mancini

Reputation: 11

A variable updating every time it is changed

i'm trying to create a variable that, everytimes it is changed, checks if the value is a certain amount and updates itself. I have something like this

max = 10
min = 0
var = 1

And then some code updating it. Is it any way to keep it updating? It is in a class if it can in some way help.

I tried to put something like

if var < min:
 var = min
elif var > max:
 var = max

After every block that could change the var, but it is very slow like this.

Upvotes: 1

Views: 175

Answers (1)

BrownieInMotion
BrownieInMotion

Reputation: 1182

Here's how you might approach doing something like this. Although you cannot mess with assignment directly, you can change how properties are set and accessed:

class LimitedValue:
    def __init__(self, min, max):
        self.min = min
        self.max = max
        self._value = None

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = min(max(value, self.min), self.max)

This could be used as follows:

lv = LimitedValue(0, 100)
lv.value = 50
print(lv.value) # 50
lv.value = 200
print(lv.value) # 100
lv.value = -100
print(lv.value) # 0

Depending on the context, this might not be very idiomatic. You could instead just shorten the code you use to constrain var to a range min, max.

First, I would rename min and max to something that does not collide with the globals of the same name. Maybe min_var and max_var. Then, you can simply use

var = min(max_var, max(min_var, var))

to constrain var to the range you want.

Upvotes: 1

Related Questions