I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?
EDIT
Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I’ve got and I get an ‘name Y not defined error’
class X(models.Model):
creator = Registry()
creator.register(Y)
class Y(models.Model):
a = models.ForeignKey(X)
b = models.CharField(max_length=200)
Hope this helps clarify. Any suggestions.
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:
When you load the module that contains the code, python will print
hello. Whenever you create anx, python will printhello again.You can think of
def __init__(self): ...as equivalent with__init__ = lambda self: ..., except none of the python lambda restrictions apply. That is,defis an assignment, which might explain why code outside methods but not inside methods is run.When your code says
You refer to
Ywhen the module is loaded, beforeYhas a value. You can think ofclass Xas an assignment (but I can’t remember the syntax for creating anonymous classes off-hand; maybe it’s an invocation oftype?)What you may want to do is this:
That is, create the class attributes of
Xwhich referenceYafterYis created. Or vice versa: createYfirst, thenX, then the attributes ofYwhich depend onX, if that’s easier.Hope this helps 🙂