Python is an extremely elegant language. Well, except ... except for imports. I still cannot get it to work as it seems natural to me.
I have a class MyObjectA , which is located in the file mypackage/myobjecta.py . This object uses some utility functions that are located in mypackage/utils.py . Therefore, in my first lines in myobjecta.py I write:
from mypackage.utils import util_func1, util_func2
But some utility functions create and return new instances of MyObjectA . So I need to write in utils.py :
from mypackage.myobjecta import MyObjectA
Well, I canβt. This is circular import, and Python will refuse to do so.
There are many questions regarding this problem, but no one gives a satisfactory answer. From what I can read in all the answers:
- Reorganize your modules, you are doing it wrong! But I donβt know how to better organize my modules even in such a simple case as I presented.
- Try just
import ... rather than from ... import ... (I personally hate writing and potentially reorganizing all classifiers of names; I like to see what exactly I enter into the module from the outside world). Will this help? I am not sure there is still circular imports. - To do hacks as importing something in the inner area of ββthe function body with only one line before using something from another module.
I still hope that there is a solution number 4) that would be Pythonic in terms of functionality, elegance and simplicity and work. Or not?
Note. I am primarily a C ++ programmer, the above example is so easily solved by including the appropriate headers, which I cannot believe that this is not possible in Python.
source share