0

How would you write this code elegantly?

for i in get_generator():
    # ...

# if loop executed then call the function
some_function()
Kanony
  • 509
  • 2
  • 12

2 Answers2

2

If your problem is to detect if there were any items returned by the generator (did the body of the loop execute at least once):

loop_executed = False
for i in get_generator():
    loop_executed = True
    # ...

if loop_executed:
    some_function()
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0
loop_executed = False
for i in get_generator():
  loop_executed = True
  # ...
    
# if loop executed, then call the function
if loop_executed:
  some_function()

Alternatively, if this get_generator call is not dynamic and does not change its state you can also just do something like

for i in get_generator():
    # ...

# if loop executed, then call the function
if get_generator() is not None: # or empty or whatever
    some_function()
Berkay Berabi
  • 1,933
  • 1
  • 10
  • 26