[Python-ideas] Control Flow - Never Executed Loop Body
Chris Angelico
rosuav at gmail.com
Tue Mar 22 09:21:34 EDT 2016
On Wed, Mar 23, 2016 at 12:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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():
I was, hence the function name.
> 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*.
And make sure the function you call doesn't use sys._getframe to get
them for you.
> 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.
Maybe. But it's an edge case of a form that could come up in other
ways - I don't know of a way to enumerate all objects in CPython, but
it's a perfectly reasonable way to debug a garbage collector. Point is
that iteration can return literally *any* object. The object()
sentinel is better than the None sentinel is better than the "if not
item" falsiness check, but the only perfect solution is an extremely
ugly one (and I'm not guaranteeing that even that is perfect - only
that *I* haven't found a flaw in it yet). At some point, the solution
is good enough for your code.
ChrisA
More information about the Python-ideas
mailing list