I am defining two classes in the same module and want to use the second one in the first one (as a global variable):
class Class1(object):
global_c2 = Class2()
def foo(self):
local_c2 = Class2()
class Class2(object):
pass
global_c2 gets an error but local_c2 doesn’t. This makes sense because when the compiler looks through this file it won’t know that Class2 is going to exist. Also if I switch the class around so that Class2 is defined first it works.
However I was wondering if there is another way to get around this. Maybe I can somehow tell python that Class2 is going to exist so don’t worry about it, or do I just have to put them in the right order?
The compiler doesn’t do anything here. In both cases, exactly the same bytecode sequence is generated to look up the class at runtime and instanciate it.
What makes the difference is when the statements are run. All code in a Python module is executed top from bottom — there is no such thing as a declaration, everything’s a definition and every binding is dynamic. Code in a class definition is run when the class definition is encountered (and therefore before the second class is brought into existence and bound to the name
Class2). Code in a function runs when the function is called, and because you don’t call the function before the definition of the second class, it’s available by the time you call that function.That’s basically what every solution boils down to: Delay binding until whatever you’re binding to exists.