Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python workaround for circular import

Ok so it is like this.

I'd rather not give away my code but if you really need it I will. I have two modules that need a bit from each other. the modules are called webhandler and datahandler.

In webhandler I have a line:

import datahandler 

and in datahandler I have another line:

import webhandler

Now I know this is terrible code and a circular import like this causes the code to run twice (which is what im trying to avoid).

However the datahandler module needs to access several functions from the webhandler module, and the webhandler module needs access to several variables that are generated in the datahandler module. I dont see any workaround other than moving functions to different modules but that would ruin the organisation of my program and make no logical sense with the module naming.

Any help?

like image 492
Adam Griffiths Avatar asked Dec 06 '22 21:12

Adam Griffiths


1 Answers

Circular dependencies are a form of code smell. If you have two modules that depend on each other, then that’s a very bad sign, and you should restructure your code.

There are a few different ways to do this; which one is best depends on what you are doing, and what parts of each module are actually used by another.

  • A very simple solution would be to just merge both modules, so you only have a single module that only depends on itself, or rather on its own contents. This is simple, but since you had separated modules before, it’s likely that you are introducing new problems that way because you no longer have a separation of concerns.
  • Another solution would be to make sure that the dependencies are actually required. If there are only a few parts of a module that depend on the other, maybe you could move those bits around in a way that the circular dependency is no longer required, or utilize the way imports work to make the circular dependencies no longer a problem.
  • The better solution would probably be to move the dependencies into a separate new module. If naming is really the hardest problem about that, then you’re probably doing it right. It might “ruin the organisation of [your] program” but since you have circular dependencies, there is something inherently wrong with your setup anyway.
like image 176
poke Avatar answered Dec 26 '22 03:12

poke