views:

113

answers:

2

Hi all

I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.

The following won't work!

class SomeClass(db.Model):
  item = db.ReferenceProperty(AnotherClass)

class AnotherClass(db.Model):
  otherItem = db.ReferenceProperty(SomeClass)

As far as I am aware, there seems to be no way of getting this to work. Sorry if this is a stupid question. Hopefully if that is the case, I will get a quick answer.

Thanks in advance.

+1  A: 

If you mean it won't work because each class want to reference the other, try this:

class SomeClass(db.Model):
  item = None

class AnotherClass(db.Model):
  otherItem = db.ReferenceProperty(SomeClass)

SomeClass.item = db.ReferenceProperty(AnotherClass)

It conflicts with some metaclass magic if there is any in place ... worth a try though.

THC4k
Thanks - I think that did the trick.
Tom R
+5  A: 

One way to view the "class" keyword in Python is as simply creating a new named scope during the initial execution of your script. So your code throws a NameError: name 'AnotherClass' is not defined exception because Python hasn't executed the class AnotherClass(db.Model): line yet when it executes the self.item = db.ReferenceProperty(AnotherClass) line.

The most straightforward way to fix this: move the initializations of those values into the class's __init__ method (the Python name for a constructor).

class SomeClass(db.Model):
  def __init__(self):
    self.item = db.ReferenceProperty(AnotherClass)

class AnotherClass(db.Model):
  def __init__(self):
    self.otherItem = db.ReferenceProperty(SomeClass)
Larry Hastings