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?

2
  • Good question; perhaps this post is relevant? stackoverflow.com/questions/4828080/… Commented May 28, 2012 at 2: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? Commented Apr 21, 2015 at 5:44

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

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
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.