4

I'm using an ODM library and I'm defining documents as classes within the same module, when they are related. I've hit a circular dependency problem and because I haven't come across this before in Python, I don't know how to inform the classes of the existence of each other. Example:

''' docs.py '''
from mongoengine import Document
from mongoengine.fields import StringField, ReferenceField, ListField


class Base(Document):
    some_field      = StringField()


class Foo(Base):
    other_field     = StringField()
    another_field   = ReferenceField(Bar)


class Bar(Base):
    other_field     = StringField()
    another_field   = ListField(ReferenceField(Foo))

As it stands the Python will throw a NameError because Bar is not defined when the interpreter gets to a reference to it in the file, within the class Foo. How do I tell Python not to worry and that the class definition will be along shortly?

Edwardr
  • 2,906
  • 3
  • 27
  • 30
  • possible duplicate of [Python mutually dependent classes (circular dependencies)](http://stackoverflow.com/questions/6402522/python-mutually-dependent-classes-circular-dependencies) – Shawn Chin Dec 01 '11 at 11:45
  • @ShawnChin: I don't think the solution in the linked question applies here, so it's not a real duplicate. – Sven Marnach Dec 01 '11 at 11:58

1 Answers1

5

ReferenceField accepts class name as well.

another_field   = ReferenceField('Bar')
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
  • 1
    I didn't know that (doesn't mention it in the API docs), the approach of referencing `A.field = ReferenceField(B)` is probably more applicable to Python generally, but I think this approach is preferable here because it maintains readability in the module (all document fields grouped together) – Edwardr 9 secs ago edit – Edwardr Dec 01 '11 at 12:03