Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load parameters from a file in Python

I am writing a Python class to model a process and I want to initialized the parameters from a file, say 'input.dat'. The format of the input file looks like this.

'input.dat' file:

Z0: 0 0
k: 0.1
g: 1
Delta: 20
t_end: 300

The code I wrote is the following. It works but appears redundant and inflexible. Is there a better way to do the job? Such as a loop to do readline() and then match the keyword?

def load(self,filename="input.dat"):
    FILE = open(filename)
    s = FILE.readline().split()
    if len(s) is 3:
        self.z0 = [float(s[1]),float(s[2])] # initial state
    s = FILE.readline().split()
    if len(s) is 2:
        self.k = float(s[1])    # kappa
    s = FILE.readline().split()
    if len(s) is 2:
        self.g = float(s[1])
    s = FILE.readline().split()
    if len(s) is 2:
        self.D = float(s[1])    #  Delta
    s = FILE.readline().split()
    if len(s) is 2:
        self.T = float(s[1])    # end time
like image 528
nos Avatar asked Dec 15 '11 19:12

nos


1 Answers

Assuming the params are coming from a safe place (made by you or users, not the internet), just make the parameters file a Python file, params.py:

Z0 = (0, 0)
k = 0.1
g = 1
Delta = 20
t_end = 300

Then in your code all you need is:

import params
fancy_calculation(10, k=params.k, delta=params.Delta)

The beauty of this is two-fold: 1) simplicity, and 2) you can use the power of Python in your parameter descriptions -- particularly useful here, for example:

k = 0.1
Delta = 20
g = 3 * k + Delta

Alternatively, you could use Python's built-in JSON or ConfigParser .INI parser modules.

like image 90
Ben Hoyt Avatar answered Oct 12 '22 22:10

Ben Hoyt