I have a use case where I need to repeat some block of code:
- Sometimes I need to repeat the code block a finite number of times
- Sometimes I need to repeat the code block indefinitely.
I am wondering, is there some Python built-in way to:
- No limit supplied --> code block is repeated via something like a
while
loop - Limit supplied --> code block is repeated via something like a
for
loop
Note: I know I can use an if
statement (depending on if upper limit is present), and switch between a for
or while
loop. I am trying to not have the code block repeated twice, or it broken out into another function.
Current Implementation
I wrote the below flawed (see below) for_while_hybrid.py
using Python 3.8.2.
from typing import Iterator
def iter_for_while(num_yield: int = None) -> Iterator[int]:
"""Generate an incrementing counter.
This enables one to make a for loop or a while loop, depending on args.
Args:
num_yield: Number of times to yield.
If left as None, the generator makes a while loop
If an integer, the generator makes a for loop
"""
counter = 0
condition = True if num_yield is None else counter < num_yield
while condition:
yield counter
counter += 1
if num_yield is not None:
condition = counter < num_yield
upper_limit = 5
for _ in iter_for_while(upper_limit):
print("Some code block") # Run 5 times
for _ in iter_for_while():
print("Some code block") # Run infinitely
This implementation works.
The downside is, if run for a very long time, I am worried the counter
will take up lots of memory, or will eventually max out. My computer is 64-bit, so sys.maxsize = 2 ** 63 - 1 = 9,223,372,036,854,775,807
.