[Python-ideas] Control Flow - Never Executed Loop Body

Steven D'Aprano steve at pearwood.info
Tue Mar 22 09:10:18 EDT 2016


On Tue, Mar 22, 2016 at 11:16:55PM +1100, Chris Angelico wrote:
> On Tue, Mar 22, 2016 at 11:07 PM, Sven R. Kunze <srkunze at mail.de> wrote:
> > However, I assume that when I do "object()" I got something unique among all
> > other objects. So,
> >
> > item = sentinel = object()
> > for item in collection:
> >     main_suite(item)
> > if item is sentinel:
> >     empty_suite()
> >
> > Is still quite correct, right?
> 
> Sure it is. Perfectly correct.

Are you being sarcastic?


> >>> def nope():
> ...     item = sentinel = object()
> ...     for item in locals().values():
> ...         print("We have:", item)
> ...     if item is sentinel:
> ...         print("We have no items.")
> ...
> >>> nope()
> We have: <object object at 0x7f17b1c6b0a0>
> We have: <object object at 0x7f17b1c6b0a0>
> We have no items.


I think that this is a completely artificial edge case that's never 
going to come up in practice, and is easy to work around: Just Don't Do 
That.

It's perfectly safe if somebody passes you locals() from *another* 
scope, because it cannot have access to *your* local sentinel. So you 
only need worry about one case: when *you* pass *your own* locals as the 
iterable. Hence, *just don't do it*.

"But what if I want to iterate over locals() and handle the case where 
it is empty?"

if not locals():
    handle_empty
else:
    for value in locals().values():
        ...


Don't get me wrong, I think it was very clever that you thought of this 
case. But I don't think this is ever going to come up in practice.


-- 
Steve


More information about the Python-ideas mailing list