I would like to add an attribute called tag to the BoundFunctionWrapper of a wrapt decorated method in order to be able to inspect my instances for methods that have a certain tag value. As I use this decorator on multiple classes, this will allow me to find and execute all methods with a certain tag.
import wrapt
import inspect
def tag_method(tag_message:str):
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
# do some other wrapper stuff besides just tagging
return wrapped(*args, **kwargs)
setattr(wrapper, 'tag', tag_message)
return wrapper
# Test Code
if __name__ == '__main__':
class MyClass:
def __init__(self) -> None:
pass
@tag_method('value_method')
def return_value(self, value:int) -> int:
return value
instance = MyClass()
print(instance.return_value(5))
print(inspect.getmembers(instance, predicate=inspect.ismethod))
print(inspect.getmembers(instance, predicate=inspect.ismethod)[1])
print(inspect.getmembers(instance, predicate=inspect.ismethod)[1][1]) # why does this suddenly evaluate to the bound method instead of the BoundFunctionWrapper?
print(inspect.getmembers(instance, predicate=inspect.ismethod)[1][1].tag) # want to print the assigned tag 'value_method'
Is this possible? If so what am I missing in my decorator implementation?
Or is there a better way to implement this functionality dynamically? I prefer dynamically because statically labeling things in a dict or something could lead to user error.