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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With