Newbie Alert: Help me store constants pythonically

Steven D'Aprano steve at REMOVEMEcyber.com.au
Tue Nov 8 03:56:10 CET 2005


Brendan wrote:

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

Cool :-)

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

That's easy: in your ConfigParser subclass, create a 
method:

def validate_name(self, name):
     if not name in self.__class__.ALLOWED_NAME_LIST:
         raise ValueError("Name '%s' not recognised." \
         % name)

then call that method before adding the attribute to 
the object __dict__. ALLOWED_NAME_LIST should be a 
class attribute, or perhaps use a global instead.


> 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)
>     ]
> )

That's a little trickier, but not much. You effectively 
are just creating a struct where some attributes are 
themselves structs.


> which I'm not sure the .ini format can easily support.

Perhaps not easily, but maybe you can modify the code 
or subclass it.


Good luck!


-- 
Steven.




More information about the Python-list mailing list