0

I have got 2 modules which tend to import each other because they will be using each other in classes. I found in this link which tells to use try/except statement along with imports to deal with circular imports, but still I am getting KeyError instead.

The name of module is brand.py which contains the following code:

try:
    from erp.common.models.productwithspecs import ProductWithSpec, ProductWithSpecSchema
except ImportError:
    import sys
    ProductWithSpec = sys.modules[__package__ + '.productwithspecs.ProductWithSpec']

but I get the below error:

File "/home/arsalan/python_practise/MY_WORK_FILES/React_works/React_Container_Mount/backend/erp/common/models/brand.py", line 13, in <module>
    ProductWithSpec = sys.modules[__package__ + '.productwithspecs.ProductWithSpec']
KeyError: 'erp.common.models.productwithspecs.ProductWithSpec'` Can anybody point out the mistake
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

2

I have got 2 modules which tend to import each other because they will be using each other in classes

Then you have a design issue, and the proper solution is not hack around it but to solve this design issue. Having circular dependencies between modules is a big no no whatever the language, even when it's technically possible.

You have three possible solutions here, depending on the concrete case: extracting common deps to a third module, regrouping both modules in one, and using dependency injection. But by all means avoid the temptation to resort to ugly hacks that will cause various issues later on (been here, done that :-/, now I know better).

martineau
  • 119,623
  • 25
  • 170
  • 301
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Well the way you are referring to as 'ugly hack' seemed to be told in Pycon talk, are you sure this is not the right thing to do ? – Arsalan Ahmad Ishaq Apr 07 '20 at 08:51
  • 1
    @ArsalanAhmadIshaq the fact it's "told in a Pycon talk" doesn't make it less of a dirty hack - and FWIW even the first "solution" mentionned in your link (deporting the import within the function itself) IS a dirty hack that should only be considered a quick'n'dirty gaffer-tape temporary fix until you properly solve the issue by using the refactorings I mentionned above. But if you really want to make your life (or the life of whoever poor soul will have to maintain this mess) miserable for the years to come, please ignore what I learned the hard way and go ahead. – bruno desthuilliers Apr 07 '20 at 09:01
  • 1
    @martineau thanks for fixing my spelling mistakes BTW ;-) – bruno desthuilliers Apr 07 '20 at 09:01