Importing a python file as a config file

In some circumstances you might like to have the configuration file for your Python program actually be another Python program, especially if you want your users to be able to write really cool config files. At first glance the eval() statement looks like a nice way to do this, but unfortunatley it won't work because import isn't an expression, it's a statement.

>>> config_file = "config"
>>> eval("import " + config)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'config' is not defined

You can get around this however with the ihooks library. First, create a config file called config.py with the following.

class Config:
      some_config_dictionary = {"option" : "Hello Config"}

Then you can import the config as per the following

import ihooks, os

def import_module(filename):
    loader = ihooks.BasicModuleLoader()
    path, file = os.path.split(filename)
    name, ext  = os.path.splitext(file)
    module = loader.find_module_in_dir(name, path)
    if not module:
        raise ImportError, name
    module = loader.load_module(name, module)
    return module

def config_example():
    config = import_module("config.py").Config
    print config.some_config_dictionary["option"]

if __name__ == "__main__":
        config_example()

All going well, you should print out Hello, Config!