Why has Python decided against constant references? Why has Python decided against constant references? python python

Why has Python decided against constant references?


It's the same as with private methods: as consenting adults authors of code should agree on an interface without need of force. Because really really enforcing the contract is hard, and doing it the half-assed way leads to hackish code in abundance.

Use get-only descriptors, and state clearly in your documentation that these data is meant to be read only. After all, a determined coder could probably find a way to use your code in different ways you thought of anyways.


In PEP 351, Barry Warsaw proposed a protocol for "freezing" any mutable data structure, analogous to the way that frozenset makes an immutable set. Frozen data structures would be hashable and so capable being used as keys in dictionaries.

The proposal was discussed on python-dev, with Raymond Hettinger's criticism the most detailed.

It's not quite what you're after, but it's the closest I can find, and should give you some idea of the thinking of the Python developers on this subject.


There are many design questions about any language, the answer to most of which is "just because". It's pretty clear that constants like this would go against the ideology of Python.


You can make a read-only class attribute, though, using descriptors. It's not trivial, but it's not very hard. The way it works is that you can make properties (things that look like attributes but call a method on access) using the property decorator; if you make a getter but not a setter property then you will get a read-only attribute. The reason for the metaclass programming is that since __init__ receives a fully-formed instance of the class, you actually can't set the attributes to what you want at this stage! Instead, you have to set them on creation of the class, which means you need a metaclass.

Code from this recipe:

# simple read only attributes with meta-class programming# method factory for an attribute get methoddef getmethod(attrname):    def _getmethod(self):        return self.__readonly__[attrname]    return _getmethodclass metaClass(type):    def __new__(cls,classname,bases,classdict):        readonly = classdict.get('__readonly__',{})        for name,default in readonly.items():            classdict[name] = property(getmethod(name))        return type.__new__(cls,classname,bases,classdict)class ROClass(object):    __metaclass__ = metaClass    __readonly__ = {'a':1,'b':'text'}if __name__ == '__main__':    def test1():        t = ROClass()        print t.a        print t.b    def test2():        t = ROClass()        t.a = 2    test1()