faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

14 of 21 people (67%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

const in Python

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 368, Tom Holroyd


"""
Packages: core_python
"""
"""
> > 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
# example usage
const = ReadOnly()
const.x = 5
const.x = 9
# TypeError: value is read only