Python is extremely elegant language. Well, except... except imports. I still can't get it work the way it seems natural to me.
I have a class MyObjectA
which is in file mypackage/myobjecta.py
. This object uses some utility functions which are in mypackage/utils.py
. So in my first lines in myobjecta.py
I write:
from mypackage.utils import util_func1, util_func2
But some of the utility functions create and return new instances of MyObjectA
. So I need to write in utils.py
:
from mypackage.myobjecta import MyObjectA
Well, no I can't. This is a circular import and Python will refuse to do that.
There are many question here regarding this issue, but none seems to give satisfactory answer. From what I can read in all the answers:
- Reorganize your modules, you are doing it wrong! But I do not know how better to organize my modules even in such a simple case as I presented.
- Try just
import ...
rather thanfrom ... import ...
(personally I hate to write and potentially refactor all the full name qualifiers; I love to see what exactly I am importing into module from the outside world). Would that help? I am not sure, still there are circular imports. - Do hacks like import something in the inner scope of a function body just one line before you use something from other module.
I am still hoping there is solution number 4) which would be Pythonic in the sense of being functional and elegant and simple and working. Or is there not?
Note: I am primarily a C++ programmer, the example above is so much easily solved by including corresponding headers that I can't believe it is not possible in Python.
mypackage/__init__.py
? If so, removing that import may make the circular imports inside the package work fine. – Coparcenary