Skip to main content
3 of 7
Add example of fix
Nihathrael
  • 641
  • 4
  • 12

Using exec() is generally regarded as bad practice (http://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided). Since you are trying to import a module, you can do the same by using the importlib package.

Python 2: https://docs.python.org/2/library/importlib.html

Python 3: https://docs.python.org/3/library/importlib.html#module-importlib

Using it should clean up the rest of the code as well.

You might also be interested in this discussion for more possibilities regarding imports: http://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python

Edit 1:

So I gave this a shot and came up with this:

import os
import sys
import pkgutil
from importlib import import_module
import inspect

import base
# I don't want to import foo, bar, or whatever other file is in pkg/

all_my_base_classes = {}
pkg_dir = os.path.dirname(__file__)
for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):
    module = import_module("." + name, __package__)
    for name, classObject in inspect.getmembers(module, inspect.isclass):
        if name.startswith('_'):
            continue
        if issubclass(classObject, base._MyBase):
            all_my_base_classes[name] = classObject

I'm still not sure if it isn't easier to use the __all__ method mentioned in the SO article, but that might depend on how you are planning to use that all_my_base_classes variable.

Nihathrael
  • 641
  • 4
  • 12