0

In my project I have a generic class named Interface and many subclasses which inherit from Interface:

  • /interface_folder/
    • interface.py
    • interface_a.py
    • interface_b.py
    • interface_c.py
    • ...
  • /test/
    • test.py

The Interface class has a method which lists all the available methods of all its subclasses : their names, docstring, input and output arguments. I did this using the inspect module on Interface.__subclasses__().

In test.py, if I want the Interface method using __subclasses__() to work, I need to import interface_a.py, interface_b.py, interface_c.py, etc.

I would like to automate these imports, so that I can add as many interface_x.py as I want in the folder without having to think of adding every time "from interface_folder.interface_d import Interface_d" at the beginning of test.py.

Is this possible? If not, is there a solution to force python to build the __subclasses__()?

  • This scenario sounds a bit strange. Why do you need so many subclasses in the first place? – Jussi Nurminen May 05 '22 at 15:21
  • The reason is specific to my project : we allow the users to add their own subclasses to the "interface_folder" (one subclass per file) and the rest of the code is made to handle as many subclasses as needed. But right now only the import issue cannot be automatized – JackOfHearts May 05 '22 at 15:43
  • Well, I guess you could scan the folder for the relevant filenames, and then use `importlib.import_module()`? – Jussi Nurminen May 05 '22 at 15:55
  • 1
    Thanks, it worked like a charm with importlib.import_module() ! – JackOfHearts May 06 '22 at 13:18

1 Answers1

0

Here is an idea:

  • Create a new subfolder, say /interface_folder/child_interfrace_folder/.
  • Move all interface_x.py in the new subfolder.
  • Import all files of the new subdirectory in interface.py. To do this:
    1. Create an __init__.py file in the new subdirectory and open it in your editor.
    2. In the new __init__.py file, list all interface_x.py files and put them in a variable named __all__. Example:

From here:

#  __init__.py
from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

You can now use from child_interfrace_folder import * in your interface.py file.

Xenial
  • 11
  • 4