Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop python question

The following is a method in a particular class that creates a simple calculator in python. It's intended to wait for a button to be clicked and return the label of that that button:

def getButton(self):
    while True:
        p = self.win.getMouse()
        for b in self.buttons:
            if b.clicked(p):
                return b.getLabel()

The self.buttons variable is a list of all the calculator buttons. Clicked is a method that checks if the button has been clicked. What I don't understand is the "while True" boolean while loop. What is it testing to be true or false? In what case will the it not be true?


1 Answers

This is an example of a busy wait. This program will get stuck in this loop, eternally checking to see if any button b in self.buttons has been clicked. At this point, it will break from the busy wait to return b's label.

So, in essence, it's not testing for anything. It's just waiting until a condition is met.

That being said, the busy wait is considered an anti-pattern. If you have control over this codebase (and this is more than just a trivial toy application), consider looking into whether this condition can be checked as part of a larger application main loop, or if the object provides a way that that event can be waited on (say, with a callback, or in a separate thread).

like image 196
Nate Avatar answered Feb 24 '26 01:02

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!