Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock mutable objects as immutable in python

How do I "lock" an object in Python?

Say I have:

class Foo:
  def __init__(self):
    self.bar = []
    self.qnx = 10

I'd modify foo as much as I want:

foo = Foo()
foo.bar.append('blah')
foo.qnx = 20

But then I'd like to be able to "lock" it such that when I try

lock(foo)
foo.bar.append('blah')  # raises some exception.
foo.qnx = 20            # raises some exception.

Is that possible in Python?

like image 465
Igor Gatis Avatar asked May 28 '12 02:05

Igor Gatis


1 Answers

Here is a simple way of doing this.

class Foo(object):
    def __init__(self):
        self._bar = []
        self._qnx = 10
        self._locked= False

    @property
    def locked(self):
        return self._locked

    def lock(self):
        self._locked = True

    @property
    def bar(self):
        if self.locked:
            return tuple(self._bar)
        return self._bar

    @property
    def qnx(self):
        return self._qnx
    @qnx.setter
    def qnx(self,val):
        if self.locked:
            raise AttributeError
        self._qnx = val

def lock(obj):
    obj.lock()
like image 170
jamylak Avatar answered Oct 04 '22 12:10

jamylak