简体   繁体   中英

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM