initializing "parameters" class in Python only once?

Chris Angelico rosuav at gmail.com
Mon Jul 14 19:41:48 EDT 2014


On Tue, Jul 15, 2014 at 8:32 AM, Catherine M Moroney
<Catherine.M.Moroney at jpl.nasa.gov> wrote:
> The actual scope of the problem is very small, so memory/cpu time is not
> an issue.  I'm just looking for the most pythonic/elegant way of doing this.

Small job? Use the simplest possible technique. Just create
"params.py" with a bunch of assignments in it:

# params.py
a = 1
b = 2
c = a + b

# every other file
import params
print("c is",params.c)
# if you need to change anything:
params.c += 5
# everyone else will see the change, because there can be
# only one instance of the module (Highlander!)

Works nicely for anything even moderately complex. Also serves as a
convenient way to separate configs from code; for instance, I do this
any time I need to have a program with database passwords, or
per-installation setup, or stuff like that. Two examples:

https://github.com/Rosuav/Yosemite/blob/master/config.py
https://github.com/Rosuav/Flask1/blob/master/1.py

In the latter case, config.py doesn't even exist in the repository, as
its main purpose is to store the database connection string - both
private (don't want that published on Github) and per-installation (my
dev and production systems use different connection strings). The
Yosemite config is actually a bit legacy now; I used to have two
distinctly different instances of it, one running on Windows and the
other on Linux, but now I have a large number of identical instances
(all on Linux and all referencing the same disk server - which,
incidentally, is the one that I've weaponized with Alice, Elsa, Anya,
a Vorpal blade, and a Portal turret). Either way, though, config.py
consists generally of simple assignments (and comments), but it's most
welcome to use all the power of Python to calculate values.

ChrisA



More information about the Python-list mailing list