Executing python class code located in folders
Question: I currently have a folder structure like this:

    
    
    .
    ├── main.py
    └── parent.py
    └── classes
        └── subclass1.py
        └── subclass2.py
        └── subclass3.py
    

Each of the `subclass`es are a subclass of `parent`, and parent is an abstract
class. The subclasses need to execute some functions like `mix()` and
`meld()`, and each of these subclasses must implement `mix()` and `meld()`.

I would like to write `main.py` such that the functions in each of the
subclasses are executed, without me having to `import` their files into my
program. That is, I'd like something akin to the following to happen:

    
    
    def main():
        # Note that I don't care about the order of which these
        for each subclass in the sources folder:
            execute `mix()` and `meld()`
            # Note that I don't mind which order the order 
            # of which the subclasses' functions are invoked.
    

Is there any way I could get this to happen?

Essentially, what I want to do is drop a bunch of classes into the `classes`
folder, with only `mix()` and `meld()` defined, and let this program run wild.


Answer: I've never tried this, but I _think_ it does what you're asking for:

    
    
    import os
    import imp
    import runpy
    
    package = 'classes'
    
    _, path, _ = imp.find_module(package)
    for m in os.listdir(path):
        if m.endswith('.py'):
            runpy.run_module(
                package + '.' + os.path.splitext(m)[0], 
                run_name="Mix_Meld"
            )
    

Then, inside of your subclasses, you can write:

    
    
    if __name__ == 'Mix_Meld':
        ClassName.mix()
        ClassName.meld()
    

This may result in additional code, granted, but if you ever need to stop the
execution in one of the files, doing so is just a matter of commenting out
that part of the code.

Another advantage is extensibility and polymorphism; if you need to run the
code a bit differently for each one of these modules in the future, you only
have to change the behaviour in the specific modules. The callee (`main.py`)
will remain oblivious to those changes and continue calling the modules the
usual way.

