Skip to main content

Ralsina.Me — Roberto Alsina's website

Python Trick: Save anything in config files

The Python con­fig ob­jects are con­ve­nient and sim­ple, but they have a prob­lem: you can on­ly save strings. That means you need to store num­bers as strings and re­mem­ber to use the get­int()/get­float() meth­ods (or co­erce by hand!), which is er­ror prone and an­ti-python­ic. Stor­ing a list is even ugli­er.

You could store ascii pick­les, but those are pret­ty un­pleas­ant to read in some cas­es.

Here's my so­lu­tion: En­code it us­ing a JSON en­coder first! (I am us­ing demj­son)

Sil­ly ob­vi­ous code frag­men­t:

def getValue(section,key,default=None):
    try:
        return JSON().decode(conf.get (section,key))
    except:
        return default

def setValue(section,key,value):
    value=JSON().encode(value)
    try:
        r=conf.set(section,key,value)
    except ConfigParser.NoSectionError:
        conf.add_section(section)
        r=conf.set(section,key,value)
    f=open(os.path.expanduser('~/.bartleblog/config'),'w')
    conf.write(f)
    return r

With just a lit­tle ef­fort you can have a read­able ascii typed python con­fig file.

Comments

Comments powered by Disqus