[Solved]-Python/Django: Why does importing a module right before using it prevent a circular import?

8👍

When a module is imported (well, the first time it’s imported in a given process), all the top-level statements are executed (remember that import is an executable statement). So you cannot have module1 with an import module2 statement at the top-level and module2 with an import module1 at the top-level – it cannot obviously work.

Now if in module2 you move the import module1 statement within a function, this statement won’t be executed before the function is actually called, so it won’t prevent module1 from importing module2.

Note that this is still considered bad practice, most of the time a circular dependency means you should refactor your code to avoid the problem (extract the parts both modules depends on into a third module that depends from both but none of the others depends on, or simply merge the modules) – but some cases are complex due to other constraints so having this as a last-resort solution is fine.

Also, you do not need to import a model to reference it in a ForeignKey or Many2Many field – you can pass a "appname.ModelName" string, cf https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey

To refer to models defined in another application, you can explicitly
specify a model with the full application label. For example, if the
Manufacturer model above is defined in another application called
production, you’d need to use:

class Car(models.Model):
    manufacturer = models.ForeignKey('production.Manufacturer')

This sort of reference can be useful when resolving circular import
dependencies between two applications.

Leave a comment