jeudi 7 octobre 2021

Using If not function(): to control flow in Python

I have an object class with an update method: this method simply makes a few checks and updates the object's properties, nothing is returned.

Some of these checks outcomes preclude others execution:

def updateObject(self):
    self.checkOne()

    if not self.checkTwo():
        self.checkThree():

def checkTwo(self):
    if self.x == condition:
        self.y = different value
        return True
    return False

As you can see, the outcome of checkTwo determines whether checkThree occurs by returning a Bool.

This felt really uncomfortable to write, but it's the most clear and concise way I can think of to get the behaviour I want.

Is this bad practice? I feel like it breaks the "one tool; one job" rule. I also think that it might make the behaviour unclear due to excessive logical inversions...

Aucun commentaire:

Enregistrer un commentaire