Decorator question (how to test if decorated function is in a class)
Martin P. Hellwig
martin.hellwig at dcuktec.org
Fri Jun 19 15:04:12 CEST 2009
I have been trying out to wrap my mind around the advantages of
decorators and thought I found a use in one of my experiments. (see code
after my sig).
Although it works, I think it should be able to do it better.
My particular problem is that I want to remove an argument (say always
the first one) when the decorated function is called.
However if the function is defined in a class the first argument is self
and thus the second argument should be removed.
Since I like to have a more general DRY approach I want to test if the
decorated function is defined in a class or not thus knowing that the
first argument is self and must be preserved.
I tried different approaches but all didn't work and looked very
unpythonic (looking at the attributes, descriptors namespaces, id() of
the function, the first argument and the decorator itself).
So is there a way to find out if the first argument is 'self' without
making a false positive if the first argument is a class instance passed
to a function?
'If consumed, best digested with added seasoning to own preference.'
"When used as Decorator(argument) returns a decorator"
def __init__(self, key):
self.key = key
def __call__(self, function):
"Return a decorator"
def decorator(*arg_tuple, **arg_dict):
"The decorator test if the arguments contain a valid key"
if arg_tuple == self.key:
# This means it is a simple function, so check and strip it
arg_list = arg_tuple[1::]
elif arg_tuple == self.key:
# This means it is a class method, check it,
# strip (but retain self)
arg_list = arg_tuple
arg_list = arg_list[0:1] + arg_list[2::]
# The key was invalid
def test(self, data):
def function_2(self, data):
def function_3(self, data):
# Test starts here
test_c = Test()
More information about the Python-list