Constants and Globals

Ben Leslie benno at sesgroup.net
Sun Dec 15 22:42:17 EST 2002


On Sun, 15 Dec 2002, Pierre Rouleau wrote:

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

Of course this is still only "protected" by way of protocol.
 
> 
> Given the module protect.py:

<snip>

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

>>> a.__class__.version = 3
>>> a.version
3

There is no way to make a truly read only variable in python.
(Which is a good thing)

Benno




More information about the Python-list mailing list