python classes that refer to each other python classes that refer to each other django django

python classes that refer to each other


In python, the code in a class is run when the class is loaded.

Now, what the hell does that mean? ;-)

Consider the following code:

class x:    print "hello"    def __init__(self): print "hello again"

When you load the module that contains the code, python will print hello. Whenever you create an x, python will print hello again.

You can think of def __init__(self): ... as equivalent with __init__ = lambda self: ..., except none of the python lambda restrictions apply. That is, def is an assignment, which might explain why code outside methods but not inside methods is run.

When your code says

class X(models.Model):    creator = Registry()    creator.register(Y)

You refer to Y when the module is loaded, before Y has a value. You can think of class X as an assignment (but I can't remember the syntax for creating anonymous classes off-hand; maybe it's an invocation of type?)

What you may want to do is this:

class X(models.Model):    passclass Y(models.Model):    foo = something_that_uses_(X)X.bar = something_which_uses(Y)

That is, create the class attributes of X which reference Y after Y is created. Or vice versa: create Y first, then X, then the attributes of Y which depend on X, if that's easier.

Hope this helps :)


The error is that execution of creator.register(Y) is attempted during the (executable) definition of class X, and at that stage, class Y is not defined. Understand this: class and def are statements that are executed (typically at import time); they are not "declarations".

Suggestion: tell us what you are trying to achieve -- perhaps as a new question.


UPDATE: He changed the question after my answer. The currently accepted solution is better in light of the new question.

What are you saying is the problem?

class A(object):    def __init__(self):        super(A, self).__init__()    def b(self):        return B()class B(object):    def __init__(self):        super(B, self).__init__()    def a(self):        return A()

This compiles and runs just fine.