ActiveState Code

Recipe 231516: Using Python in Configuration Files


Traditional configuration files are static in their nature. Using Python as configuration language will give the application user a dynaimc environment to configure the application.

Using Python's build in "execfile" this is very easy to implement.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# start --- config.ini ---
# --*-- python --*--

enemy = "Dr. No"
salary = 100

def tax(salary):
   return salary * 0.2


bond = employee(id = "007", salary=salary * 2, tax=tax(salary * 2))

# end --- config.ini ---

# start --- readconf.py ---
class employee:
    def __init__(self, id, salary, tax):
        self.id = id
        self.salary = salary
        self.tax = tax

#FIXME: No error checking is done (to simplify code)
def read_conf(filename, optnames):
    '''Read configuration file return elements hash'''
    # Load file & eval
    h = {}
    execfile(filename, globals(), h)
    # Get only what we want 
    options = {}
    for item in h:
        if isinstance(h[item], employee) or (item in optnames):
            options[item] = h[item]

    return options

# end --- readconf.py ---

Discussion

As we can see it is very easy to add new types of options. Option is selected is it is a known option or a subclass of an option class. You can change read_conf to get a list of known option classes and check of h[item].__class__ is one of them.

Known limitation: o Config file must be in Python syntax o Options names must be valid python variables o In unix if config file in in DOS format, compile will fail o Security, the user can place shutil.rmtree("/") somewhere ...

Comments

  1. 1. At 4:48 a.m. on 5 nov 2003, Simon Brunning said:

    Calling a spade a spade. Good tip, but...

    If it's not really an INI file, don't use the 'ini' extension.

  2. 2. At 6:18 a.m. on 6 nov 2003, Cristian Echeverria said:

    What is the diference if I use execfile? I use something similar

    mydict = {} execfile(filename,globals(),mydict)

  3. 3. At 11:52 a.m. on 6 nov 2003, Gregor Rayman said:

    Nice idea, BUT. try to write dialog driven software with check-boxes, drop-down-lists etc. to edit those ini-files.

Sign in to comment