[Python-ideas] Control Flow - Never Executed Loop Body
Steven D'Aprano
steve at pearwood.info
Tue Mar 22 09:48:26 EDT 2016
On Wed, Mar 23, 2016 at 12:21:34AM +1100, Chris Angelico wrote:
> > 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.
Are you saying that I might have code like this:
def test():
x = sentinel = object()
iterable = some_function()
for x in iterable:
# you know the rest
and some_function() might use _getframe to steal sentinel and return it
back to me as iterable = [sentinel]?
I'll take my chances with that, thanks very much. I am as concerned by
that as I am that some_function might use ctypes to hack the value of
integers so that 1 + 1 returns 4. Yes, it could happen. No, I don't care
to take any special precautions to avoid it happening.
I think a far more likely possibility is that somebody or something has
monkey-patched object() to always return the same instance, regardless
of who calls it from where, and now my sentinel is the same as everyone
else's sentinel. Am I bothered by this? Not in the least.
I mean, seriously, we write code all time relying on the behaviour of
builtin functions, knowing full well that any piece of code anywhere
might monkey-patch them to do something weird. Should we insist on
special syntax that returns the len() of sequences because of an
edge-case "what if len has been monkey-patched?". No. We just say "well
don't monkey-patch len."
In case it's not obvious by now, I don't think there's any need for
syntax to handle the empty iterable case. -1 on the proposal.
--
Steve
More information about the Python-ideas
mailing list