How do you create constants?

Alex Martelli aleaxit at yahoo.com
Sat Oct 28 12:21:59 EDT 2000


"marc cheatham" <marcc at yieldworks.com> wrote in message
news:39FAE133.9070001 at yieldworks.com...
    [snip]
> I am not sure if Python has user defined constants, but a possible

It doesn't.

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

If you're willing to use something like const.foo, it's not
hard to ensure its value won't be changeable:

-- in const.py:

class Const:
    foo = 'Foobar!'
    bar = 23
    pi = 3.1415926
    baz = "Whacka-doo"
    def __setattr__(self,name,value):
        if Const.__dict__.has_key(name):
            raise AttributeError, "cannot change const.%s" % name
        Const.__dict__[name] = value

const = Const()

-- anywhere else:

from const import const

# may now use const.foo, const.bar, ..., and also add new
# const.whatever values by assignment, but NOT change
# any existing one


Alex






More information about the Python-list mailing list