Search code examples
pythonclassattributesimmutability

Can I create an immutable class attribute in Python 3?


I am writing a class with custom __eq__ and __hash__ methods, and __hash__ basically returns one of class' attributes (which is an integer). Therefore, I need to make this attribute as immutable as possible. Is there a way to make an attribute immutable in Python?

I can, of course, make it __private, but that's not quite the same thing. Also at this point of time I am not sure if I should make my class a dataclass.

More context if this is somehow relevant: the class Simplex represents a combinatorial simplex, and stores a set of vertices (in the form of a binary number) and an integer coefficient. The class has a method boundary() that should return an object of the type Complex, which is a collection of Simplex instances. The __eq__ method thinks A == B if their sets of vertices coincide (coefficients are not relevant). The method __hash__ returns the binary storing vertices. I want __hash__ to work in this specific way, because I think it would simplify adding up equal simplices in Complex.


Solution

  • Try to use a customized class_property decorator.

    Something like (copy from this post https://stackoverflow.com/a/5191224/24285005):

    
    class ClassPropertyDescriptor(object):
    
        def __init__(self, fget, fset=None):
            self.fget = fget
            self.fset = fset
    
        def __get__(self, obj, klass=None):
            if klass is None:
                klass = type(obj)
            return self.fget.__get__(obj, klass)()
    
    def classproperty(func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
    
        return ClassPropertyDescriptor(func)
    
    
    class Bar(object):
        @classproperty
        def bar(cls):
            return 1