Right now, I have the following class methods:
def check_capacity(self, at_index)
def update_capacity(self, at_index)
The former returns a Boolean, while the latter changes an instance variable. The problem is both methods do very similar things. I feel like I’m violating DRY?
I’d like to have one method:
def update_capacity(self, at_index)
which I can use as:
if update_capacity(at_index):
that would create the intended side-effects if the side-effects are desirable, and return False otherwise.
My attempt was to copy the instance variable, check to see if the copy was desirably changed, and then set the instance variable to the copy if correct and return True, or don’t and return False otherwise. However, this doesn’t work with mutable data structures (like lists)!
Should I just be doing this with a “deep copy”? Or is there a better way to go about doing this? I’d like to be as Pythonic as possible.
EDIT
The check_capacity iterates through the instance variable and checks if making the change would violate a condition.
The update_capacity iterates through the instance variable and makes the change, knowing the condition won’t be violated.
Both have very similar code.
I have a hunch that those two functions together manage to straddle your problem without exactly hitting it on the head. If I have this right, you want to have
update_capacityeither change something or returnFalseif changing something is not desired.It seems to me that you will be able to achieve this functionality by adding the checking mechanism from
check_capacityintoupdate_capacity, performing the condition check before executing the body ofupdate_capacity:Of course, this code will return
Noneif the condition is true, so if you want to keep your function signatures tidy, you could returnTrueor something depending on what fits the rest of your code.