Welcome, guest | Sign In | My Account | Store | Cart

Useful class and decorator for create immutable objects. Decorator mutablemethod used for define mutable methods.

Python, 48 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Immutable(object):
     """An immutable class.
     """
     _mutable = False
     def __setattr__(self, name,value):
        if self._mutable or name == '_mutable':
             super(Immutable,self).__setattr__(name,value)
        else:
             raise TypeError("Can't modify immutable instance")
    
     def __delattr__(self,name):
         if self._mutable:
             super(Immutable,self).__delattr__(name)
         else:
             raise TypeError("Can't modify immutable instance")
    
    
def mutablemethod(f):
    def func(self,*args, **kwargs):
        if isinstance(self,Immutable):
            old_mutable = self._mutable
            self._mutable = True
            res = f(self,*args, **kwargs)
            self._mutable = old_mutable
        else:
            res = f(self,*args, **kwargs)
        return res
    return func
         


if __name__ == '__main__':
    
    class A(Immutable):
        '''
           Define __init__ can set attributes for instance
        '''
        @mutablemethod
        def __init__(self,value):
            super(A,self).__init__(self)
            self.value = value
    
        def try_change(self,value):
            self.value = value
        
    a = A("test")
    a.try_change("TEST")
    a.value = "TEST"
Created by Dmitry on Thu, 22 Apr 2010 (MIT)
Python recipes (4591)
Dmitry's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks