0

I ran into this old blog post : https://blog.kevmod.com/2014/06/

X = 0
Y = 0
def wrapper():
    X = 1
    Y = 1
    class C(object):
        print X, Y # <- what happens at this line?
        X = 2
wrapper()

Apparently this prints "0,1"!!!!

While there was a pretty thorough explanation as to why it prints it:

"The technical details are that there are a number of different opcodes that Python can use to look up names; in a function scope locals are looked up with LOAD_FAST, but in a classdef they are looked up with LOAD_NAME, which does not check any parent scopes and just skips to the global scope. Non-locals in classdefs are looked up with either LOAD_NAME or LOAD_DEREF, the latter of which will check enclosing scopes."

What I didn't understand is why it prints at all? How is printing inside a declaration even valid?

das-g
  • 9,718
  • 4
  • 38
  • 80
Rohi
  • 814
  • 1
  • 9
  • 26
  • 1
    You could try and hoist `class C` outside of the function and it will still `print`. – quamrana Jan 27 '21 at 14:29
  • 1
    I think you are confused because you have experience with compiled languages like C, C++, or Java. Python is a dynamic interpreted language. So when you define a class, it literally interprets every line in its definition and executes it. You can run your entire program inside a class definition and it would still be valid python because thats just it works. – Niteya Shah Jan 27 '21 at 14:30
  • Python,being an interpreted language, does not distinguish between declaration and execution. Everything happens at runtime and code is interpreted as encountered. – sureshvv Jan 27 '21 at 14:31
  • Thanks all, I have been developing compiled code so much I forgot the basics :( – Rohi Jan 27 '21 at 14:33
  • @sureshvv That makes it sound like *every* interpreted language works that way, which is not the case. That class bodies are just regular imperative code is a peculiarity of Python. – deceze Jan 27 '21 at 14:33

0 Answers0