Constants and Globals

Pierre Rouleau pieroul at attglobal.net
Sun Dec 15 21:53:31 EST 2002


Sean 'Shaleh' Perry wrote:
> On Saturday 14 December 2002 04:41, Travis Beaty wrote:
> 
>>1.  Is there such an animal as a "constant" in Python?  I've looked
>>through the manual, documentation, and FAQ's, but I haven't been able to
>>find an answer about that.  I'm sure it's there somewhere, and I've just
>>overlooked it.  I noted that the term "constant" was used, but I am
>>unsure whether one can actually lock the value of a variable, or whether
>>such constants are simply "constant by agreement."
>>
> 
> 
> there is no direct support for this in Python.  The idiom is to name the 
> variable in ALL CAPS and never name anything else that way.
> 
> 
You may want to take a look at this recipe: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207

There is also a way to make a class attribute read-only using property:


Given the module protect.py:

class against(object):
    """ Abstract base class to prevent class attribute operations."""

    class AccessError(TypeError): pass

    def readAccess(self) :
       """Prevent the get_attribute operation for the property."""
       raise self.AccessError, "Attribute is not readable"

    def writeAccess(self,value) :
       """Prevent the set_attribute operation."""
       raise self.AccessError, "Can not rebind attribute"

You can protect class attributes:


 >>> import protect
 >>> class A(protect.against):
...   version = property((lambda self: '1.0'),protect.against.writeAccess)
...   value = 1
...
 >>> a = A()
 >>> a.value
1
 >>> a.value = 2
 >>> a.value
2
 >>> A.value = 9
 >>> A.value
9
 >>> a.value
2
 >>> a.version
'1.0'
 >>> a.version = 0
Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    File "protect.py", line 107, in writeAccess
       raise self.AccessError, "Can not rebind attribute"
AccessError: Can not rebind attribute
 >>>



-- 
         Pierre





More information about the Python-list mailing list