Welcome, guest | Sign In | My Account | Store | Cart

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, 36 lines
 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 ---

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 ...

4 comments

Simon Brunning 18 years, 1 month ago  # | flag

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

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

Cristian Echeverria 18 years, 1 month ago  # | flag

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

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

Gregor Rayman 18 years, 1 month ago  # | flag

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

Miki Tebeka 10 years, 8 months ago  # | flag

Note that in Python3 execfile is gone, you need to do

with open(filename) as fo:
    exec(fo.read(), globals(), h)
Created by Miki Tebeka on Wed, 5 Nov 2003 (PSF)
Python recipes (4591)
Miki Tebeka's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks