I'd like to use a decorator which accepts an argument, checks if that argument is not None, and if True it lets the decorated function run.
I want to use this decorator inside a class definition, because I have a set of class methods which starts with checking if a specific instance variable is None or not. I think it would look nicer if I used a decorator.
I'd like to do something like this:
# decorator
def variable_tester(arg):
def wrap(f):
def wrapped_f(*args):
if arg is not None:
f(*args)
else:
pass
return wrapped_f
return wrap
# class definition
class my_class(object):
def __init__(self):
self.var = None
@variable_tester(self.var) # This is wrong. How to pass self.var to decorator?
def printout(self):
print self.var
def setvar(self, v):
self.var = v
# testing code
my_instance = my_class()
my_instance.printout() # It should print nothing
my_instance.setvar('foobar')
my_instance.printout() # It should print foobar