How do you create constants?

Christian Tismer tismer at tismer.com
Sat Oct 28 09:46:41 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.

There are no true constants in Python.
But if you really need something similar, you can write
a little class with read-only attributes, in order to track
assignments to your constants.

Here a little implementation: A class that doesn't allow assignment
twice.

ciao - chris

--------------------------------------------------------
"""
    constants.py

    A small class to implement constant like behavior.
    Christian Tismer, 00-10-28

"""

class constant:
    """ this class allows assignment only once for every member """
    def __setattr__(self, key, value):
        if self.__dict__.has_key(key):
            raise AttributeError, "can't assign to constant " + key
        self.__dict__[key] = value

# now you can use it like so:

import math
c = constant()
c.pi = math.pi
c.one = 1
# and it will not work twice!
--------------------------------------------------------

-- 
Christian Tismer             :^)   <mailto:tismer at tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com




More information about the Python-list mailing list