I have been tasked with researching improvements to a Python tool. However, the current tool is a mess. Just a collection of several hundred functions and imports spread across 10 files all in the same level of directory, all cross referencing each other, with each file importing some subset of the others, sometimes recursively.
There is an underlying hierarchy there, and so I intend to convert it all into a module, with sub-modules, and then to further refactor it into a class rather than a set of nested functions.
I am having some issue with imports though. I am self taught with python, and I am trying to remain PEP8 compliant, with little knowledge of how to. An additional complication is the system I am using is secure, and is unable to have an IDE installed on it, so I am battling with a glorified text editor with a terminal built in.
I thought I could import the sub-modules together in the highest level of the module, and they would then be available to all sub-modules, but this seems to produce name errors. My file structure and code is as follows:
Directory
dir
|
+-- run_module.py
|
+--top_module
|
+--__init__.py
|
+--module.py
|
+--sub_module
|
+--__init__.py
|
+--sub_module_one.py
|
+--sub_module_two.py
Content of run_module.py
from top_module import module
module.run_the_thing()
Content of init.py
Currently, both __init__
files are empty, though this issue persists if top_mod.__init__
has the imports instead of module
, as well as importing module
and being imported by run_module
Content of module.py
from .sub_module import sub_module_one, sub_module_two
def run_the_thing():
sub_module_one.hello()
sub_module_two.greeting()
Content of sub_module_one.py
def hello():
print('I am sub-module 1.')
Content of sub_module_two.py
def hello():
print('I am sub-module 2.')
def callout():
print('And this is my friend:')
sub_module_one.hello()
def greeting():
hello()
callout()
When run, it prints the output from sub_module_one
as expected, and prints everything in sub_module_two
up until the call to sub_module_one
.
I cant say I am surprised by this behaviour, but is there a solution that will allow me to import all the sub-modules in the top level script, leaving them available for all the others, or will I have to have imports in each and every sub-module?
Clearly this isnt too messy for my MWE, but the real code will be horrible spaghetti.