How do you feel about multiple Python classes in the same module depending on each other?

I use the ODM library and I define documents as classes in one module when they are linked. I ran into the problem of cyclic dependencies and because I had not seen this in Python before, I don’t know how to tell classes about each other's existence. 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, Python will throw a NameError , because Bar not detected when the interpreter gets a reference to it in a file, in the Foo class. How can I tell Python not to worry and what the class definition will be in the near future?

+4
source share
1 answer

ReferenceField also accepts a class name.

 another_field = ReferenceField('Bar') 
+5
source

Source: https://habr.com/ru/post/1384095/


All Articles