wtfpython icon indicating copy to clipboard operation
wtfpython copied to clipboard

About `Name resolution ignoring class scope`

Open imba-tjd opened this issue 5 years ago • 1 comments

Original code:

x = 5
class SomeClass:
    x = 17
    y = [x for i in range(10)]

I find the expression in in is bind to x in the class:

x = 5
class SomeClass:
    x = 3
    y = [x for i in range(x)]

SomeClass.y # [5, 5, 5]

I guess it's the same as Evaluation time discrepancy. But I also don't think y is lazy evaluated. According to my test it is produced when defining the class rather than calling SomeClass. Maybe see the bytecode is a choice? I don't know.

imba-tjd avatar Oct 26 '20 15:10 imba-tjd

Interesting, I didn't think of it this way, here's the disassembled code

In [22]: import dis
    ...:
    ...: def some_func():
    ...:     x = 5
    ...:     class SomeClass:
    ...:         x = 3
    ...:         y = [x for i in range(x)]
    ...:     SomeClass.y # [5, 5, 5]
    ...:
    ...: dis.dis(some_func)
  4           0 LOAD_CONST               1 (5)
              2 STORE_DEREF              0 (x)

  5           4 LOAD_BUILD_CLASS
              6 LOAD_CLOSURE             0 (x)
              8 BUILD_TUPLE              1
             10 LOAD_CONST               2 (<code object SomeClass at 0x10bab2e40, file "<ipython-input-22-6389be0d34ed>", line 5>)
             12 LOAD_CONST               3 ('SomeClass')
             14 MAKE_FUNCTION            8
             16 LOAD_CONST               3 ('SomeClass')
             18 CALL_FUNCTION            2
             20 STORE_FAST               0 (SomeClass)

  8          22 LOAD_FAST                0 (SomeClass)
             24 LOAD_ATTR                0 (y)
             26 POP_TOP
             28 LOAD_CONST               0 (None)
             30 RETURN_VALUE

satwikkansal avatar Oct 27 '20 18:10 satwikkansal