Daniel Daniel - 1 year ago 129
Python Question

python classes that refer to each other

I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?


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()

class Y(models.Model):
a = models.ForeignKey(X)
b = models.CharField(max_length=200)

Hope this helps clarify. Any suggestions.

Answer Source

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()

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):
class 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 :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download