Francesco Bochicchio wrote:
On Wed, 14 Jan 2009 08:13:30 +0000, Steven D'Aprano wrote:
Absolutely. It's rather sad that I can do this:
import math
math.pi = 3.0
I like the ability to shoot myself in the foot, thank you very much, but
I should at least get a warning when I'm about to do so:
math.PI = 3.0 # use God-like powers to change a constant
Constants would be a nice addition in python, sure enough.
But I'm not sure that this can be done without a run-time check every time
the constant is used, and python is already slow enough. Maybe a check
that is disabled when running with optimizing flags ?
But I'm sure this discussion has been already made and the FINAL WORD has
been already spoken.
>>> class Constants(object):
def __setattr__(self, key, value):
if key in self.__dict__:
raise ValueError("Can't change constant")
self.__dict__[key] = value
>>> c = Constants()
>>> c.PI = 3.0
>>> c.PI
3.0
>>> c.PI = 4.0
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
c.PI = 4.0
File "<pyshell#19>", line 4, in __setattr__
raise ValueError("Can't change constant")
ValueError: Can't change constant
--
http://mail.python.org/mailman/listinfo/python-list