Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python - Creating a class with all the elements specified in a file using ConfigParser

I have created a .ini-like file with all the values which I need later in my program, see below:

[debugging]
checkForAbort = 10
...

[official]
checkForAbort = 30
...

I would like to read all these items into a single class and make it accessible from other parts of my python project. What I have so far is the code below:

from ConfigParser import SafeConfigParser
import glob

class ConfigurationParameters
    def __init__(self):
        self.checkForAbortDuringIdleTime = None     

    parser = SafeConfigParser()

    # making a list here in case we have multiple files in the future!
    candidatesConfiguration = ['my.cfg']
    foundCandidates = parser.read(candidatesConfiguration)
    missingCandidates = set(candidatesConfiguration) - set(found)
    if foundCandidates:
        print 'Found config files:', sorted(found)
    else
        print 'Missing files     :', sorted(missing)
        print "aborting..."


    # check for mandatory sections below
    for candidateSections in ['official', 'debugging']:
        if not parser.has_section(candidateSections)
            print "the mandatory section", candidateSections " is missing"
            print "aborting..."

    for sectionName in ['official', 'debugging']:
        for name, value in parser.items(section_name):
            self.name = value

I am new to python but I can still see lots of problem with my code:

  • I am forced to add a attribute for each item in my class file. and keep the configuration file and my class in sync all the time.
  • This class is not a singleton, therefore the reading/parsing will be done from wherever it is imported!
  • If a value is added to the config-file with is not defined in my class, it will probably crash!

How should I solve this problem instead? Can class attributes be created dynamically?

My class only need to read from the values, so no writing to the configuration file is needed!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What J.F. Sebastian said.

Also, you could do it like Alex Martelli does in his Bunch class:

file MyConfig.py:

from ConfigParser import SafeConfigParser


section_names = 'official', 'debugging'


class MyConfiguration(object):

    def __init__(self, *file_names):
        parser = SafeConfigParser()
        parser.optionxform = str  # make option names case sensitive
        found = parser.read(file_names)
        if not found:
            raise ValueError('No config file found!')
        for name in section_names:
            self.__dict__.update(parser.items(name))  # <-- here the magic happens


config = MyConfiguration('my.cfg', 'other.cfg')

file foo.py:

from MyConfig import config
# ...

file MyProgram.py:

from MyConfig import config

print config.checkForAbort

import foo

assert config is foo.config

The Python Language Reference states that "Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs)."

What that means is that, when a module gets imported, one or more local names are bound to a module object, and only the first time it is imported during the runtime of a Python program it gets initialized (i.e. read from file and run).

In the code above the name config is just a local name that refers to an attribute of a module object. The module object has been initialized by the Python interpreter when it was referenced (via from MyConfig import config) in MyProgram. When MyProgram imports foo it is already initialized and gets bound to a local name in module foo and in MyProgram we can refer to it as foo.config. But both names refer to the very same object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...