I have a series of python modules written which are held in the same directory and I am having trouble with an ImportError.
The three modules I am using are draw_menu.py, errors.py and file_operations.py.
In errors.py I requires a list of error codes, I am using a custom method defined in file_operations.py to open a file containing the codes therefore I am using import file_operations just below the she-bang (above the class definition).
In file_operations.py I use a method defined in error.py to print error messages upon errors (e.g. file not found etc.). I therefore import errors in the same way here.
The above has been working fine but when I come to using draw_menu.py which uses a file to define the options in an ascii menu (therefore I am using import file_operations) an ImportError is encountered.
ImportError: cannot import name file_operations
I understand that this is because the ‘import tree’ if you like flows as follows:
draw_menu <- file_operations <- errors <- file_operations
It is important that each module can be used individually, why is this an issue and how can I overcome this without removing import file_operations from errors.py?
Thankyou
Tom
Circular imports can cause issues in Python (as you might expect). It’s probably worth checking if:
A) errors.py and file_operation.py should be single module (if they both rely so heavily on each other, do they need to be separate?)
B) you can delay the
importin one or the other module. An import statement in a function will not run until the function is called, and while it’s normally good practice to import at the beginning of a module there is no requirement to in Python. In situations like this it can avoid the circular reference during import.