The basic idea
Generators can receive values from the yield <value>
statement by using generator.send(value)
. I think this would be a decent QoL feature to make it easier to pass values to generators by using pass
or continue
Cons of using the continue <value>
syntax
continue <value
, in order to make sense, would just need to be a logical extension of the already existing continue
statement. That means that it must also work like the regular continue
statement and skip to the next iteration.
Cons of using the pass <value>
syntax
pass
normally does absolutely nothing. Adding functionality to pass
could be seen as weird, but the word pass
makes sense logically if you are “passing” a value back to the generator. Since the pass statement also does nothing normally, there is no functionality to compare the new pass <value>
syntax to.
Pros of both
This is simply a QoL feature that would allow you to send send data to a generator without first storing that generator somewhere.
Examples
previous way
import random
def my_gen():
'''A generator that receives values'''
pass
gen = my_gen()
for x in gen:
gen.send(random.randint(0, 100))
New way
import random
def my_gen():
'''A generator that receives values'''
pass
for x in my_gen():
pass random.randint(0, 100) # alternatively, `continue random.randint(0, 100)`
edit:
clarification
what about nested loops?
In that case, the pass <value>
statement will assume you want to send the the value to the generator in the current loop. This means it makes the same assumption as the break
statement. If you want to use the old syntax to add specificity, go ahead, it isn’t being removed by my idea.
for x in my_gen(): # loop 1
# ...
for y in my_gen(): # loop 2
pass 8 # value passed to loop 2
# ...
pass 8 # value passed to loop 1
what about nested generators?
example of what I mean when I say “nested generators”
for tup in zip(spamgen, eggsgen, cheesegen):
pass value
In this case, the value is passed to the top-level generator and not its children (if that makes any sense). For example, in the code above, the value would be passed to the zip()
generator, not the children spamgen, eggsgen, and cheesegen
.