Created
October 27, 2009 13:38
-
-
Save whilefalse/219565 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class toggler(object): | |
def __init__(self, getter, setter): | |
self.getter = getter | |
self.setter = setter | |
def __enter__(self, *args, **kwargs): | |
self.setter(not self.getter()) | |
__exit__ = __enter__ | |
#use like: | |
class MyClass(object): | |
x = True | |
def getx(self): | |
return self.x | |
def setx(self, x): | |
self.x = x | |
def some_awesome_fn(self): | |
with toggler(self.getx, self.setx): | |
print self.x # -> False | |
print self.x # -> True | |
#Or even better | |
class WebClient(object): | |
def javascriptToggled(self): | |
return toggler(self.client.isJavascriptEnabled, self.client.setJavascriptEnabled) | |
def really_awesome_fn(self): | |
with self.javascritToggled(): | |
#Do some stuff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment