How do you create constants?

marc cheatham marcc at yieldworks.com
Sat Oct 28 10:27:39 EDT 2000


Tom wright wrote:

> Hi All,
> 
> I am a newbie to python, and I have the following question,
> 
> in c++ I can create a constant through something like an enum, or a const
> variable or a static.  How do I go about doing something similar to this in
> python, e.g.
> 
> I want to create a python file/class which contains all my constants for
> ease of use/maintenance.  I then wish to use these from various other
> files/classes.  Now I understand that due to the scoping of python
> variables, I can not simply reference variables in a separate module, but
> how can I achieve something similar to my global defines file as in c++, by
> the way, the defines would be constant strings and integers.
> 
> I am sure there is an easy way to do this, but I havnt found it yet !!
> 
> TIA for pointers
> 
> Regards
> 
> Tom
> 
> PS I have RTFM, but if its there I have missed it

I am not sure if Python has user defined constants, but a possible 
solution to the scoping problem could be creating a module called 
consts.py. Inside consts.py initialize varibles in with their "constant" 
value. Import that module into your other modules and use 
consts.<variable_name> to reference the pre-initialized variable.

The drawback, of course, is anyone can change the value.

Hope this helps.
Marc




More information about the Python-list mailing list