[Python-Dev] Unbound locals in class scopes

Nick Coghlan ncoghlan at gmail.com
Tue Jun 23 05:33:32 CEST 2015


On 22 June 2015 at 17:13, Guido van Rossum <guido at python.org> wrote:
> But what *is* the correct behavior? I suspect people's intuitions differ. If
> you think of this as similar to function scopes you're likely to be wrong.

For me, there's a correct answer for *new* users based on the combination of:

1. For module level class definitions, if you look up a name before
binding it locally, it's looked up the same way it would be if you
never bound it locally at all
2. For function level class definitions, If the name isn't bound
locally in the class body, nonlocals are visible as if the class body
was running in the scope of the function defining the class

If folks never experienced Python as it existed prior to 2.2, the
current behaviour isn't likely to be at all intuitive to them (I
barely make it into that category myself - prior to adopting 2.2.2 for
DSP testing in 2002 or so, my sole experience with Python 1.5.2 was a
single university level networking class*)

> Also, since classes inside functions are commonly used in unit tests (at
> least mine :-), I worry that *any* changes in this behavior might break
> working code (no matter how much that "working" could be considered an
> accident, it's still going to be a bear to debug if this happens to you).

Agreed - I think any change here would need to go through a
deprecation period where we warned about cases where LOAD_NAME would
be changed to LOAD_CLASSDEREF and there was a nonlocal defined with
that name.

Since it's trivial easy to workaround by renaming a local variable to
use a name that differs from the nested class attribute, I'd also be
entirely happy with leaving the current behaviour as an obscure quirk
- I'm only +0 on changing it, and also +0 on declaring it "not worth
the hassle of changing".

Cheers,
Nick.

P.S. *Two fun facts about that class (this was in the late 90's): a)
the lecturer *required* us to use Python as he assumed there'd be very
few people that already knew it, so we'd be starting off on a more
level playing field; and b) I asked if I could use Java instead, since
I already knew that at the time (he said no, and Python really *was*
very easy to pick up for the assignments we needed to do. It made it
up again an easy choice several years later)

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list