11

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?

jamylak
  • 128,818
  • 30
  • 231
  • 230
Igor Gatis
  • 4,648
  • 10
  • 43
  • 66
  • Good question; perhaps this post is relevant? http://stackoverflow.com/questions/4828080/how-to-make-an-immutable-object-in-python – Steve Tjoa May 28 '12 at 02:46
  • Your question is incoherent. Look: `t = [2,3]; foo.bar = t; lock(foo); t.append(4)` - should it work, or should it raise exception? – Veky Apr 21 '15 at 05:44

1 Answers1

13

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()
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Can you offer some tips as to how one could generalize this to a method to make generic classes lockable? Specifically multiple inheritance vs mixing vs metaclass – drxzcl May 28 '12 at 07:56
  • @Ranieri I only offered this way since the OP didn't specify what he is using this for so I can't be sure of the best way to implement the solution. If there were more information I would go to the effort of generalizing it, this is probably why no other solutions have been submitted at this point of time. If you have an answer then submit it of course but I'm just gonna leave this as the basic solution. If you would like to add info to this, that would be fine with me as well. – jamylak May 28 '12 at 08:08