Skip to content

Instantly share code, notes, and snippets.

@hubertgrzeskowiak
Created December 22, 2012 02:33
Show Gist options
  • Save hubertgrzeskowiak/4357159 to your computer and use it in GitHub Desktop.
Save hubertgrzeskowiak/4357159 to your computer and use it in GitHub Desktop.
With this method decorator you can make a method a method container or -composition. See the included example to see how it works.
class composition(object):
"""This is a composition decorator, which allows a function to be used as a container for functions.
On call, all the functions contained will be called.
Keep in mind, though, that the decorated function itself won't be included/called.
"""
class NoSuchElementError(Exception):
def __init__(self):
Exception.__init__(self, "You tried to remove an element from a composition that was not existent.")
class ElementNotCallableError(Exception):
def __init__(self):
Exception.__init__(self, "You can only add callables to the composition")
def __init__(self, func=None):
self.functions = []
def __call__(self):
return_values = []
for f in self.functions:
return_values.append(f())
return return_values
def __add__(self, value):
if not callable(value):
raise ElementNotCallableError()
self.functions.append(value)
return self
def __sub__(self, value):
try:
self.functions.remove(value)
except ValueError:
raise composition.NoSuchElementError()
return self
def removeLast(self):
return self.functions.pop()
def clear(self):
self.functions = []
# Usage
class ExampleClass(object):
@composition
def onFocus(self):
pass
# Test
def p(to_print="random string"):
print to_print
def r(to_return=42):
return to_return
c = ExampleClass()
c.onFocus += p
c.onFocus += lambda: p("second function call")
c.onFocus += r
return_values = c.onFocus()
print "---"
print "return values: "+str(return_values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment