[Python-ideas] Fixing class scope brainstorm

Paul Moore p.f.moore at gmail.com
Thu Mar 29 12:53:13 EDT 2018


On 29 March 2018 at 16:27, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 28 March 2018 at 04:47, Paul Moore <p.f.moore at gmail.com> wrote:
>> To me, that would be the ideal. I assume there are significant
>> technical challenges, though, as otherwise I'd have thought that would
>> have been the approach taken when Python 3 fixed the name leaking
>> issue from Python 2.
>
> It isn't avoiding the names leaking that's particularly challenging
> (there are several viable ways to do that), it's making sure that
> inner scopes can still see them. For example:
>
>     lazy_and_eager = [((lambda: i), (lambda i=i: i)) for i in range(3)]
>     for lazy, eager in lazy_and_eager:
>         print(lazy(), eager())
>
>     # prints:
>     2 0
>     2 1
>     2 2

I'm really not sure what point you're trying to make here - are you
saying that this is good or bad? Correct or incorrect? I don't really
have any intuition about what's going on here, so I'd just have to
work it out in terms of the defined scoping rules. And I'd then tell
whoever wrote it to rewrite it more clearly ;-)

Maybe a real-life case where this was important would clarify what
counts as intuitive here - but as it stands,I don't really care. I
don't even care that much about compatibility. Unless someone were to
come along and demonstrate a serious breakage in their code, I think
it's perfectly OK to change the behaviour in this situation, if that's
what you're suggesting (with suitable deprecation, of course).

> While it's *technically* feasible to hide "i" from the outer scope
> without hiding it from inner scopes with a variable renaming based
> approach, you end up having to design and document a separate lexical
> scoping mechanism that's distinct from the one that functions already
> use. I really didn't want to do that, so I proposed just using the
> existing scoping mechanism instead, and while that has definitely had
> its quirks, I'm still happy enough with it a decade later to call it a
> successful approach.

I do think the current implementation is a pretty good compromise. I'd
be reasonably OK with not changing anything in this area. But this
discussion was prompted by some of the debates around statement local
variables, so "not changing anything" includes, in my mind, "not
trying to make statement local variables work" as they interact badly
with the current scoping behaviour in this area.

Paul


More information about the Python-ideas mailing list