Reputation: 1570
I'd like to add a condition to a while loop, only if a variable value is not None.
This the approach I'm using right now:
from queue import Queue
max_limit = None # could be None or an integer (user provided value)
q = Queue()
q = get_values()
counter = 0
while not q.empty() and \
(not max_limit or counter <= max_limit):
# If max_limit is None , counter <= max_limit never gets evaluated thanks to lazy OR
# do stuff...
counter += 1
The problem is right now it's very hard to figure out what is doing just by looking at it. Is there a more pythonic way to do that other than adding an if statement before or within the while loop?
Upvotes: 0
Views: 179
Reputation: 18148
max_limit = None or sys.maxint # use sys.maxsize for python 3
counter = 0
while not q.empty():
if counter > max_limit:
break # exit the loop
# do stuff...
counter += 1
Upvotes: 0
Reputation: 881523
Despite your statement:
other than adding an if statement before or within the while loop
I believe that is actually the best solution.
It's likely to become a very ugly while
condition if you ever end up with more than one of these constraints, so I would leave the while
loop to handle the normal case and just add "exit loop early" code to handle the special cases, something like:
counter = 0
while not q.empty():
counter += 1
if max_limit is not None and counter > max_limit: break # User count limit.
if GetElapsedTime() > timeLimit: break # Took too long.
# Other checks as necessary.
# do stuff...
With one exit reason per line (and documented), it still maintains the readabilty of the original loop.
You should keep in mind that Pythonic code isn't always the best code, sometimes it's used just for showing how clever people think they are :-)
My first inclination is to always optimise for readability.
Upvotes: 4
Reputation: 70277
Despite what your math teacher may tell you, there actually is a biggest number.
max_limit = # do something magic
if max_limit is None:
max_limit = float('inf')
# ...
while not q.empty() and counter <= max_limit:
pass
float('inf')
, as the name implies, is the floating-point constant infinity, which is larger than any finite value. So it will effectively disable your condition, as counter
will always be smaller. And the while
loop code doesn't get kludged up with a bunch of conditionals either.
Upvotes: 3
Reputation: 1482
from queue import Queue
max_limit = None # could be None or an integer (user provided value)
q = Queue()
q = get_values()
counter = 0
while q is not None and counter <= max_limit:
counter += 1
Upvotes: -1