[Python] throw ad un generatore: perché non riparte dall'inizio?

Marco Giusti marco.giusti a posteo.de
Gio 28 Lug 2022 09:48:02 CEST


On 28.07.2022 09:40, Marco Beri wrote:
> On Thu, 28 Jul 2022 at 08:57, Marco De Paoli <depaolim a gmail.com>
> wrote:
> 
>> =
>> ---><--- begin test_gen.py ---><---def gen():
>> while True:
>> try:
>> yield "A"
>> yield "B"
>> yield "C"
>> except Exception as ex:
>> print("catched exception", ex)
>> 
>> g = gen()
>> you_can_specify_any_number_of_steps = 3
>> for idx in range(you_can_specify_any_number_of_steps):
>> print("result:", g.send(None))
>> print("throw...")
>> g.throw(Exception("BOOM"))
>> print("result:", g.send(None), "*** I was expecting A and I get B,
>> why?!? ***")
>> print("result:", g.send(None))
> 
> Se invece di g.throw(Exception("BOOM")) scrivi
> print(g.throw(Exception("BOOM")))
> 
> Ritroverai il tuo "A" :-)

Grazie Marco,
   Mi ero perso questo punto. I generator non vengono usati come 
coroutine tutti i giorni.

https://docs.python.org/3/reference/expressions.html#generator.throw

Ciao
Marco


Maggiori informazioni sulla lista Python