mercredi 31 mars 2021

How do I work with double references and consequent import errors

I'm running into a problem with imports and references. I'm gonna use a made-up example to explain (the example uses mongoengine)

Let's say I have the following two classes in two different files

# File 1 
# Titled houses.py

import persons
import mongoengine as me

class House(me.Document):
    residents: me.ListField(me.ReferenceField(persons.Person)) #This will be a list populated with Person objects
# File 2
# Titled persons.py

import houses
import mongoengine as me

class Person(me.Document):
    house: me.ReferenceField(houses.House) #This is a House object

I have two concerns in a scenario like the above

  1. I'm getting a circular import error (b/c they require each other) - I can't get rid of the imports b/c mongo asks that you input the class of the object that will be assigned to the variable
  2. This seems less than ideal - is there a design pattern that betters this situation?

Thanks!

Aucun commentaire:

Enregistrer un commentaire