Skip to content

Instantly share code, notes, and snippets.

@probablytom
Created June 4, 2018 22:15
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 probablytom/dd23210838a29c7930e16a6db0551ded to your computer and use it in GitHub Desktop.
Save probablytom/dd23210838a29c7930e16a6db0551ded to your computer and use it in GitHub Desktop.
A really simple example of the mechanism ASP uses for AOP
from functools import partial
def weave(target_class, advice):
original_getattribute = target_class.__getattribute__
# Hack around bound / unbound methods
for target, adv in advice.items():
advice[target.im_func] = adv
def __new_getattribute__(self, item):
item = object.__getattribute__(self, item)
if not callable(item) or item.im_func not in advice.keys():
return original_getattribute(self, item)
advised_item = partial(advice[item.im_func], item)
advised_item.func_name = item.func_name # More Python magic
return advised_item
target_class.__getattribute__ = __new_getattribute__
def example_advice(target_function, *args, **kwargs):
print "we're running some advice!"
target_function(*args, **kwargs)
print "now the advice is finishing, after the original function ran."
class T(object):
def some_method(self, message):
print message
# Without weaving
t = T()
t.some_method("chunky bacon!") # Just this message
print
# Let's weave!
weave(T, {T.some_method: example_advice})
t = T()
t.some_method("chunky bacon!") # Three lines, two of which are from our AOP!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment