Immutable instances, constant values

George Sakkis gsakkis at rutgers.edu
Mon Nov 21 12:18:02 EST 2005


Steven D'Aprano wrote:

> Yes, that would be how I interpret constants: You want a name which can't
> be re-bound to something else.
>
> One work-around is to use the convention of writing the name in all caps:
>
> CONSTANT = some_value
>
> and then trust that your module user doesn't rebind CONSTANT. I'd like to
> see support for something a little stronger than just "cross your fingers
> and hope", without necessarily going all the way to Pascal's full
> enforcement of constants. "We're all adults here" -- if somebody *really*
> wants to rebind CONSTANT, I'm not going to stop them, but I want them to
> jump through a hoop to do it, as a reminder that the module creator thinks
> they shouldn't be doing it.

Another workaround if you tradeoff strictness with convenience is
define a CONST  metaclass in which contants are accessed as attributes
and which raises an Exception in __setattr__:

class CONST(type):
    def  __new__(cls, name, bases, dict):
        def __setattr__(self,attr,val):
            raise AttributeError('Cannot reassign constant %s.%s'
                                         % (name, attr))
        cls.__setattr__ = __setattr__
        return type.__new__(cls, name, bases, dict)


class PhysicsConstants(object):
    __metaclass__ = CONST
    c = 2.9979246e+08


>>> PhysicsConstants.c = 0
AttributeError: Cannot reassign constant PhysicsConstants.c


George




More information about the Python-list mailing list