How do you create constants?
Dale Strickland-Clark
dale at out-think.NOSPAMco.uk
Sat Oct 28 13:22:25 EDT 2000
"Tom wright" <thomas.wright1 at ntlworld.REMOVETHIS.com> 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
>
AFAIK, Python doesn't do constants, as such.
If you want to use 'set once' values, you could write a simple class
for that. Something like this:
class SetOnce:
def __setattr__(self, key, value):
if key in dir(self):
raise ValueError(key)
self.__dict__[key] = value
If you want sequential flag bits, I have found this handy:
# This class allocates flag bits sequentially.
class Flagbit:
def __init__(self):
self.bit = 1
def flag(self):
if self.bit == 0:
raise Hell(12, 'FlagBit: Too many flag bits')
rv = self.bit
self.bit = self.bit << 1
return rv
Hope that helps.
--
Dale Strickland-Clark
Out-Think Ltd
Business Technology Consultants
More information about the Python-list
mailing list