On Thu, Dec 5, 2019 at 22:08 Jonathan Goble <[email protected]> wrote:
> On Fri, Dec 6, 2019, 12:47 AM Steven D'Aprano <[email protected]> wrote: > >> On Thu, Dec 05, 2019 at 05:40:05PM -0400, Juancarlo Añez wrote: >> > I just found this code: >> > >> > def get_product_item(jsonld_items): >> > for item in jsonld_items: >> > if item['@type'] == 'Product': >> > return item >> > else: >> > return {} >> >> I'm sorry, I can't tell what that is supposed to do. Is the "return {}" >> supposed to be inside the loop? If so, it has been accidentally >> dedented. Is it meant to be outside the loop? The "for-else" is >> redundent, since there is no break. >> > > "return", like "break", causes the "else" suite to be skipped. > > https://docs.python.org/3/reference/compound_stmts.html#the-for-statement > does not clearly specify this; it only says that the else suite is executed > when the iterator is exhausted or empty, and that "break" skips it. Perhaps > a sentence should be added to clearly and unambiguously state that "return" > skips it also? > No, that follows from the semantics of return. (Same for raise.) Break is mentioned specifically because it transfers control to the code after the loop, just like exhausting the iterable. The difference between exhaustion and break is the reason the else clause (on loops) exists -- so we can do something only when no break is taken. (Only a finally clause can intercept return.) > -- --Guido (mobile)
_______________________________________________ Python-ideas mailing list -- [email protected] To unsubscribe send an email to [email protected] https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/[email protected]/message/MEAUG55DPM5FOZCYLIX3EWUJX6YYWYYV/ Code of Conduct: http://python.org/psf/codeofconduct/
