Created
February 7, 2013 01:24
-
-
Save olliebun/4727589 to your computer and use it in GitHub Desktop.
decorator with closure
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
def will_break(f): | |
broken = False | |
def on_call(self, *args, **kwargs): | |
if broken: | |
raise ValueError("Already broken!") | |
else: | |
broken = True | |
f(self, *args, **kwargs) | |
return on_call | |
class AnEgg(object): | |
@will_break | |
def __call__(self): | |
print("I am a tasty egggg.") | |
egg = AnEgg() | |
egg() | |
egg() # should throw a ValueError |
(same behaviour in 2.7 and 3.3)
Fixed with this:
def will_break(f):
def on_call(self, *args, **kwargs):
if on_call.broken:
raise ValueError("Already broken!")
else:
on_call.broken = True
f(self, *args, **kwargs)
on_call.broken = False
return on_call
class AnEgg(object):
def __init__(self):
self.num = 1
@will_break
def __call__(self):
print("I am a tasty egggg.")
print(str(self.num))
egg = AnEgg()
egg()
egg()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the line:
Throws an exception: