Ahmed Nuaman
Ahmed Nuaman

Reputation: 13211

Multiple imports in python

How do people get around this issue:

A controller (say controller.py) imports two models (say a_model.py and b_model.py):

from app.model import a_model
from app.model import b_model

Now let's say that a_model wants to use a function in b_model (let's say it wants to get something from b_model where an id of the record is from a query in a_model, so I do (in a_model):

from app.model import b_model

Now since our controller has already imported b_model.py and a_model.py is attempting to do the same, we break the application.

Can someone tell me the best way around this? Maybe use a proxy? Or a library loader?

Upvotes: 1

Views: 189

Answers (3)

Drew Sears
Drew Sears

Reputation: 12838

Is this what you're trying to do?

class A(db.Model):
  b = db.ReferenceProperty(B)

class B(db.Model):
  a = db.ReferenceProperty(A)

If so, the easy fix is probably to turn one of them into a weak reference:

class A(db.Model):
  b = db.ReferenceProperty()

class B(db.Model):
  a = db.ReferenceProperty(A)

This is a crappy solution, no question. I'm not sure if there's a better way to do it.

Upvotes: 1

Andrey Tatarinov
Andrey Tatarinov

Reputation: 570

It is fine as long as you don't have cicrcular references, ie.

main --> model.a_model -> model.b_model
     \-> model.b_model

Is ok.

But if you add import a_model from b_model.py things would get complicated as there would be no way to order loading in such way that for each module all prerequisites would be satisfied.

Python handles this situation less nicely as one would expect and instead of reporting about circular imports, raises exception about undefined symbol in one of the modules.

Upvotes: 4

Eli Bendersky
Eli Bendersky

Reputation: 273366

There's no problem with importing a module from two different modules in Python. Maybe your particular design makes it a problem, but it's not something Python imposes.

Anyhow, you could probably solve the problem by moving common stuff from a_model and b_model to some other module, i.e. model_common, and importing that from both a_model and b_model.

Upvotes: 6

Related Questions