0

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).

Community
  • 1
  • 1
SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • Not directly answering your question, but thinking out of the box: Instead of monkey-patch-assembling your class it might be a cleaner solution to create smaller classes (mixins) in multiple files and compose them to the ultimate huge class using multiple inheritance. – MB-F Feb 14 '17 at 10:05
  • @kazemakase could you make a small example? – SumNeuron Feb 14 '17 at 10:27
  • I don't have the time, sorry. See if [this](https://www.programiz.com/python-programming/multiple-inheritance) and [this](http://stackoverflow.com/questions/301134/dynamic-module-import-in-python) can get you started. – MB-F Feb 14 '17 at 10:33

0 Answers0