Created
June 4, 2018 22:15
-
-
Save probablytom/dd23210838a29c7930e16a6db0551ded to your computer and use it in GitHub Desktop.
A really simple example of the mechanism ASP uses for AOP
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
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 | |
# 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