const in Python

Tom Holroyd tomh at po.crl.go.jp
Mon Feb 7 20:11:31 EST 2000


On Mon, 7 Feb 2000, Gordon McMillan wrote:

> Anders M Eriksson writes:
> > 
> > Would someone please explain why there isn't a const 'operator' in
> > Python!
> 
> If you are truly concerned, you could make them attributes of 
> a class that prohibits setattr. But generally naming 
> "constants" in all upper case is enough to tell a Pythonista 
> that it shouldn't be modified.

Right, like this:

class ReadOnly:
    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            raise TypeError, 'value is read only'
        self.__dict__[name] = value

>>> const = ReadOnly()
>>> const.x = 5
>>> const.x = 9
TypeError: value is read only

Dr. Tom Holroyd
"I am, as I said, inspired by the biological phenomena in which
chemical forces are used in repetitious fashion to produce all
kinds of weird effects (one of which is the author)."
	-- Richard Feynman, _There's Plenty of Room at the Bottom_




More information about the Python-list mailing list