Mentre questo è il comportamento predefinito nelle versioni di Python fino al 3,6 incluso, è considerato un errore nella lingua e è programmato per cambiare in Python 3.7 in modo che venga sollevata un'eccezione.
Come PEP 479 dice:
L'interazione di generatori e StopIteration
è attualmente un po 'sorprendente, e possono nascondere insetti oscuri. Un'eccezione imprevista non dovrebbe comportare un comportamento leggermente alterato, ma dovrebbe causare un traceback rumoroso e facilmente debug. Attualmente, StopIteration
generato accidentalmente all'interno di una funzione del generatore verrà interpretato come la fine dell'iterazione dal costrutto del loop che guida il generatore.
Da Python 3.5 in poi, è possibile modificare il comportamento predefinito a quello pianificato per 3.7. Questo codice:
# gs_exc.py
from __future__ import generator_stop
def error():
return next(i for i in range(3) if i==10)
all(error() for i in range(2))
... solleva la seguente eccezione:
Traceback (most recent call last):
File "gs_exc.py", line 8, in <genexpr>
all(error() for i in range(2))
File "gs_exc.py", line 6, in error
return next(i for i in range(3) if i==10)
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "gs_exc.py", line 8, in <module>
all(error() for i in range(2))
RuntimeError: generator raised StopIteration
In Python 3.5 e 3.6 senza il __future__
importazione, un messaggio di avviso viene generato.Per esempio:
# gs_warn.py
def error():
return next(i for i in range(3) if i==10)
all(error() for i in range(2))
$ python3.5 -Wd gs_warn.py
gs_warn.py:6: PendingDeprecationWarning: generator '<genexpr>' raised StopIteration
all(error() for i in range(2))
$ python3.6 -Wd gs_warn.py
gs_warn.py:6: DeprecationWarning: generator '<genexpr>' raised StopIteration
all(error() for i in range(2))
fonte
2015-02-03 00:17:46
La stessa cosa accade in Python 3. – khelwood
@khelwood grazie, io rimuovere il tag py2.7 – amwinter
Certo. [** all ** * (iterable) * Restituisce True se tutti gli elementi di iterable sono true *** (o se iterable è vuoto) ***.] (https://docs.python.org/2/ library/functions.html # all) –