Note: This question is a modification / extension of Adding functions from other files to a Python class. This is partially because imp
is deprecated.
Context: I have a large class file (+5000 lines), say MainClass.py
. To better compartmentalize my code, I would like to move related functions into separate subfiles e.g. the desired directory structure might resemble:
- my_package
|
| - .__init__.py
| - MainClass.py
|
| - main_class_functions
| | - .__init__.py
| | - function_group_1.py
| | - function_group_2.py
| | ...
I would like to be able to load these functions and add them to the MainClass
Currently I have:
# MainClass.py
import os
import importlib
class MainClass(object):
def __init__(self):
self._compartmentalized_functions_directory = 'main_class_functions'
self._location = os.path.dirname(os.path.abspath(__file__))
def load_functions(self):
# absolute path to directory of where the function files are located
function_files_directory = os.path.join(self.location, self._compartmentalized_functions_directory)
#
[importlib.import_module(file, os.path.join(function_files_directory, file)) for file in os.listdir(function_files_directory)]
# main_class_functions_1.py
def test(self):
print("test")
But this spits an ImportError
, 'main_class_functions_1' is not a package
.
(I have also copy-pasted the code from the linked post and tried to see if that worked, but it did not).