#define equivalents and config files

Jeff Shannon jeff at ccvcorp.com
Thu Mar 21 15:45:35 EST 2002


Dave Swegen wrote:

> > Rich Salz wrote:
> > >
> > > > Is there a pythonic way of doing something similiar to Cs #define?
> > >  >... are globals the only way to go?
> > >
> > > You can at least make them class attributes
> > >         class constants:
> > >                 pi = 3.14159
> > >                 e = 2.71828
> > > adding your own setattr can serve to make them read-only.
>
> I'm basically after a single file where such values can be stored, and
> then used in various parts of the program without having to pass extra
> configuation variables around.

One option that I have used, is to create a separate module called
constants.py, and defined my constants/configuration variables there.  Then,
every module in my project can simply do something like:

import constants
area = constants.pi * (radius ** 2)

You can use some interesting hacks to make the constants module read-only,
if necessary (see the ASPN Python Cookbook), but since I'm typically the
only person using my code I've decided to simply trust myself.  ;)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list