Newbie Alert: Help me store constants pythonically

Brendan spam4bsimons at yahoo.ca
Tue Nov 8 02:16:23 CET 2005


> How many is LOOONG? Ten? Twenty? One hundred?

About 50 per Model

> If it is closer to 100 than to 10, I would suggest
> putting your constants into something like an INI file:
>
> [MODEL1]  # or something more meaningful
> numBumps: 1
> sizeOfBumps: 99
>
> [MODEL2]
> numBumps: 57
> sizeOfBumps: 245
>
>
> etc.
>
> Then sub-class the ConfigParser to create struct-like
> objects from an ini file. Something vaguely like:
>
> # warning: pseudo-code, seriously not tested!!!
> class Config2Consts(ConfigParser):
>      """Reads an INI file, and creates a struct-like
>      object from each section, storing that object
>      in the local scope with the name of the section.
>      """
>
>      class Struct:
>          def __init__(self):
>              pass
>
>      def make_single_constant_object(self, sectionname):
>          obj = Struct()
>          for field in INI_FILE[sectionname]:
>               obj.__dict__[field.name] = field.value
>          locals().update({sectionname: obj})
>
>
>
> If you are likely to be changing the constants (either
> names, field names, or values) an hour or three
> developing this code will save you a lot of heart-ache
> later.

Thanks for your reply Steve.  I like this suggestion because it
separates my config data from the code, which could mean less headaches
editing the values later.  It also lets me keep my constants
language-neutral, which is good because I haven't convinced my boss yet
that Python's the way to go.

The only downside is that it doesn't do any 'name checking', so any
mistakes in my config file won't show up until the middle of the
analysis.  Maybe this is a 'static language' mode of thinking, but it
seems risky.  Also my config files have (a tiny bit of) nested
structure, such as:

Model1(
   numBumps = 1
   sizeOfBumps = 2
   transversePlanes = [
        Plane(type=3, z=4),
        Plane(type=5, z=6),
        Plane(type=3, z=8)
    ]
)

which I'm not sure the .ini format can easily support.  I could use
(key buzzword voice) XML, but  I fear that might send me down the
'overcomplicating things' path.  Your suggestion has given me some new
places to search Google (configparser, python config files), so I'll
look around for better ideas.

   Brendan




More information about the Python-list mailing list