How to initialize a class with data from a python file

I would like to initialize a class from the data stored in a simple python file specified when the script was called. Configuration file named myconfig.py :

str='home'
val=2
flt=7.0

I would call it during class initialization like this. One of the goals is to determine the types of variables as well as in the file. I know the configurator, but this method is less verbose if it can be made to work.

class ClassInit(object):
    def __init__(self, configFile):
        fp, path, des = imp.find_module('',configFile)
        imp.load_module(configFile, fp, path, des)
        self.__dict__ = configFile.__dict__
        fp.close()

    def printVal(self):
        print '%s %0.2f'%(self.str, self.val)

if __name__ == '__main__':
    srcDir = 'src/'
    config = osp.join(srcDir, argv[0]) # config for current run 
    ci = ClassInit(config)
    ci.printVal()

Is this possible?

+3
source share
2 answers

, . - eval() exec . , -, . , . __builtins__ , , eval/exec . :

class ClassInit(object):
    def __init__(self, configFile):
        f = open(configFile)
        config = f.read()
        f.close()
        config_dic = { '__builtins__': None}
        exec 'a = 4' in config_dic
        for key, value in config_dic.iteritems():
            if key != '__builtins__':
                setattr(self, key, value)

', . , , . , .py.

, , , - .

, eval(): Python: eval

, config.py, , python , JSON , Python 2.6 simplejson, . - Javascript, Python, .

+1
source

Can you try self.__dict__.update(configFile.__dict__)? I do not understand why this will not work.

0
source

All Articles