Skip to content

Instantly share code, notes, and snippets.

@jpf
Created March 1, 2014 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpf/9297761 to your computer and use it in GitHub Desktop.
Save jpf/9297761 to your computer and use it in GitHub Desktop.
A class with a method that can only be assigned a specific number of times
class StateLatch(object):
def __init__(self, changes_until_latched=2):
self._state = None
self.latch_count = changes_until_latched
@property
def state(self):
return self._state
@state.setter
def state(self, value):
if self.latch_count > 0 and self._state != value:
self._state = value
self.latch_count -= 1
if __name__ == '__main__':
# Here is how to use a StateLatch:
# Instantiate the class:
x = StateLatch()
# Show the state
print(x.state)
# Assign the state property three times
# By default, the StateLatch will freeze ("latch") after 2 assignments
x.state = 'One'
x.state = 'Two'
x.state = 'Three'
# This will print "Two"
print(x.state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment