The concept is fine, but there's a couple bugs. See comments below.
+class EditConfig(object):
Kind of a weird class name. Maybe ShellConfig, or maybe we should just replace SimpleConfig?
- def read(self):
""" Read the config file and store the key/value pairs"""with open(self.filename) as f:for line in f:if len(line)>0 and line[0] in '#";':continue
Bug. len(line) will never be 0, because empty lines will come out as "\n". readline() is tricky like that.
Also, this line won't be considered a comment: ' #blah=funk\n'
Add a 'line = line.strip()' first?
(key, sep, var) = [x.strip() for x in line.partition("=")]
(With the strip happening above, you wouldn't need it here.)
if key and sep == "=":
For clarity, can you change this so the test on 'key' is more explicit? That line looks like it means: if (key == '=') and (sep == '='). Maybe: if key != '' and sep == '=': Or: if sep == '=' and key:
Either way would be clearer, I think.
self.values[key] = var
This is going to leave any quoting that's in var, so if quotes are used the value will be something like: '"fun"'. Conversely, in write(), we're not adding quotes if the value has spaces, so if you change a value to 'something with spaces in it', it's not gonna be quoted in the resulting file, which will cause problems if the parser expects that.
Do we care about that stuff?
- def write(self):
""" Rewrite the file with the new key/value pairspass-thru comments and lines without ="""tmpf = tempfile.NamedTemporaryFile(mode="w", delete=False)with open(self.filename) as f:
We're reopening the file here? What if the file has been changed/removed since it was read, or we want to read the config from a string?
It might be a good idea to save the lines in an array on read(), and just iterate over the saved lines in write().
I actually wrote a ConfigParser-style thingy for this out of curiosity - I'll send it along for discussion.
-w