Skip to content

Instantly share code, notes, and snippets.

@olliebun
Created February 7, 2013 01:24
Show Gist options
  • Save olliebun/4727589 to your computer and use it in GitHub Desktop.
Save olliebun/4727589 to your computer and use it in GitHub Desktop.
decorator with closure
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
@olliebun
Copy link
Author

olliebun commented Feb 7, 2013

(same behaviour in 2.7 and 3.3)

@olliebun
Copy link
Author

olliebun commented Feb 7, 2013

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