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