I am trying to create a decorator that creates an association between a function and associated text it will execute in response to. Here is some working code that illustrates what I mean:
# WORKING CODE
mapping = {}
def saying(text):
def decorator(function):
mapping[text] = function
return function
return decorator
@saying("hi")
def hi():
print "hello there"
@saying("thanks")
@saying("gracias")
def thanks():
print "you're welcome"
mapping["hi"]() #running this line will print "hello there"
mapping["thanks"]() #running this line will print "you're welcome"
The issue occurs when I attempt to add these methods to a class. Something like this:
#NON-WORKING CODE:
class politeModule(object):
def __init__(self):
self.mapping = {}
@saying("hi")
def hi(self):
print "hello there"
@saying("thanks")
@saying("gracias")
def thanks(self):
print "you're welcome"
module = politeModule()
module.mapping["hi"]()
module.mapping["thanks"]()
The issue is, I don't know where to put the decorator so it can access mapping
and also work. I understand there are a lot of StackOverflow questions and articles about this. I tried to implement some of the solutions described in this blog post, but repeatedly got stuck on scoping issues and accessing the mapping dictionary from inside the decorator