Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69677

Re: Scoping rules for class definitions

References <lhmu69$1nu$1@dont-email.me>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-04-04 12:55 -0600
Subject Re: Scoping rules for class definitions
Newsgroups comp.lang.python
Message-ID <mailman.8898.1396637751.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Apr 4, 2014 at 12:37 PM, Rotwang <sg552@hotmail.co.uk> wrote:
> Hi all. I thought I had a pretty good grasp of Python's scoping rules, but
> today I noticed something that I don't understand. Can anyone explain to me
> why this happens?
>
>>>> x = 'global'
>>>> def f1():
>     x = 'local'
>     class C:
>         y = x
>     return C.y
>
>>>> def f2():
>     x = 'local'
>     class C:
>         x = x
>     return C.x
>
>>>> f1()
> 'local'
>>>> f2()
> 'global'

Start by comparing the disassembly of the two class bodies:

>>> dis.dis(f1.__code__.co_consts[2])
  3           0 LOAD_NAME                0 (__name__)
              3 STORE_NAME               1 (__module__)
              6 LOAD_CONST               0 ('f1.<locals>.C')
              9 STORE_NAME               2 (__qualname__)

  4          12 LOAD_CLASSDEREF          0 (x)
             15 STORE_NAME               3 (y)
             18 LOAD_CONST               1 (None)
             21 RETURN_VALUE
>>> dis.dis(f2.__code__.co_consts[2])
  3           0 LOAD_NAME                0 (__name__)
              3 STORE_NAME               1 (__module__)
              6 LOAD_CONST               0 ('f2.<locals>.C')
              9 STORE_NAME               2 (__qualname__)

  4          12 LOAD_NAME                3 (x)
             15 STORE_NAME               3 (x)
             18 LOAD_CONST               1 (None)
             21 RETURN_VALUE

The only significant difference is that the first uses
LOAD_CLASSDEREF, which I guess is the class version of LOAD_DEREF for
loading values from closures, at line 4 whereas the second uses
LOAD_NAME.  So the first one knows about the x in the nonlocal scope,
whereas the second does not and just loads the global (since x doesn't
yet exist in the locals dict).

Now why doesn't the second version also use LOAD_CLASSDEREF?  My guess
is because it's the name of a local; if it were referenced a second
time in the class then the second LOAD_CLASSDEREF would again get the
x from the nonlocal scope, which would be incorrect.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Scoping rules for class definitions Rotwang <sg552@hotmail.co.uk> - 2014-04-04 19:37 +0100
  Re: Scoping rules for class definitions Ian Kelly <ian.g.kelly@gmail.com> - 2014-04-04 12:55 -0600
    Re: Scoping rules for class definitions Rotwang <sg552@hotmail.co.uk> - 2014-04-08 23:09 +0100

csiph-web