0

I'm trying to import files based on their name, for example:

project /
    __init__.py
    log.py
    conf /
        __init__.py
        logger_settings.py
        other_settings.py

In my conf/__init__.py file I want to have something similar to this:

 # -*- coding: utf-8 -*-                                                         
 # vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab                           

 import os                                                                       
 import sys                                                                         
 import json                                                                        

 def get_settings(identity):                                                             
     """Settings."""                                                                

     try:                                                                       
         from i import *                                                        
     except ImportError as exc:                                                 
         raise Exception('Eror importing config %s' % exc) 

So than in log.py file I would be able to do something like this:

 #!/usr/bin/env python -u                                                        
 # -*- coding: utf-8 -*-                                                         
 # vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab                           

 import os                                                                       
 import logging                                                                  

 from project import conf                                                     

 CONF = conf.get_settings('logger_settings')                                              

 def getLogger(identity ,log_file=CONF.log_file):  
     # Then access CONF to return settings
     # For example:
     # host = CONF.host  would return something like 'localhost'

And I want to have logger_settings.py like this:

log_file = '/mnt/logs/'
host = 'localhost'

How do I need to modify conf/__init__.py in order to achieve this?

1

1 Answer 1

1

See the __import__ built-in (low level), as well as importlib (high level).

These provide a means of importing modules dynamically (i.e. whose names are given by runtime values).

import importlib
settings = importlib.import_module('conf.%s' % i)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.