The second thing is that the config file can be anywhere and I do not want force people to make any Python modules (with those strange __init__.py files). They will simply forget to create.
On the other hand I want to keep those attributes in the class object because then I can use that object in other part of the program. First idea was to simply use execfile()
Here is how I overcome the problem, I create a BaseSettings class with the constructor that takes an path to the settings file:
class BaseSettings(object):
def __init__(self, settings_file):
"""Constructor of the settings class.
Args:
settings_file: The full path to the settings file.
"""
_required_sections = set([
'ANGLES',
'DIHEDRALS',
'PAIRS',
'ATOM_PAIRS',
'BOND_CONFIG',
'TOTAL_NUMBER_OF_CROSSLINKS'
])
settings_variables = {}
copy_globals = globals().copy()
try:
execfile(settings_file, copy_globals, settings_variables)
except SyntaxError as ex:
print 'There is an error in your config file %s in line %s' % (
ex.filename, ex.lineno)
print '%d: %s' % (ex.lineno, ex.text)
print ex.msg
sys.exit(2)
# Checks if some attributes are missing in the settings file.
missing_sections = _required_sections - set(settings_variables)
if missing_sections:
Exception(
'Invalid settings file, those sections are missing: %s' % (
','.join(missing_sections))
# Loads the variables as it they would be and attributes of the class.
self.__dict__.update(settings_variables)
and then I use execfile() with the copied globals() and the empty dict settings_variables that works as the container for the locals(). I had to copy globals dict because otherwise I had those attributes in the globals.Afterwards the variables from the settings file can be found in the settings_variables dictionary. So the only things was to update the __dict__ of the class with those variables.
No comments:
Post a Comment