initializing "parameters" class in Python only once?

Steven D'Aprano steve at pearwood.info
Tue Jul 15 07:28:19 CEST 2014


On Mon, 14 Jul 2014 15:24:26 -0700, Catherine M Moroney wrote:

> The problem:  I'm writing a large Python program and I have a bunch of
> parameters (whose values are static) that I want to make available to
> the rest of the code with minimum overhead and duplicate processing.
> 
> I think that the simplest way would be to create a file called
> "Params.py" and then simply have statements like a = 1, b = 2, etc. in
> there (no classes, no methods, just a bunch of declarations).

That sounds exactly right to me.


> But, some
> of these static parameters have to be calculated rather than simply
> hard-coded.

I don't think that should be a problem. You can include calculations:

a = 1
b = 2
c = a**2 + b**2 - a + 1


The only difficulty is if you want those values to be calculated on 
demand, rather than at program startup. If that's the case, I think the 
best solution is to turn them into functions:

def c():
    return a**2 + b**2 - a + 1


This, sadly, requires you to tell the difference between params that 
should be constants and those which should be function calls. If that is 
a serious problem, you should consider a singleton class with properties, 
but if the simpler solution works for you, stick to the simpler solution!


> I thought of creating a class called Params and having a bunch of
> methods (decorated with @classmethod) that set/calculate the value of
> all the parameters.  Easy enough, but then I have to create a Params
> object in every source file that uses these parameters, and that seems
> wasteful.

I don't think that Params with class methods is the best solution. I 
would do something like this:

# === module params.py ===
class Params(object):
    a = 1
    b = 2

    @property
    def c(self):
        return self.a**2 + self.b**2 - self.a + 1


params = Params()
del Params  # hide the class



Then callers just say:

from params import params
print params.c


All modules now see the same params instance, so it is (almost) a 
singleton.


-- 
Steven



More information about the Python-list mailing list