Page 1 of 1

Is it possible to check if a function has been decorated with a listener?

Posted: Wed Oct 05, 2016 10:46 am
by Mahi
For example, is it possible to know from my_listener that it has been decorated here:

Syntax: Select all

@OnLevelChange
def my_listener(...):
pass

I'm using a class decorator and I need to loop through all of the class's methods, and if they have been decorated with a listener, I need to wrap them. Basically this:

Syntax: Select all

for attr in dir(cls):
func = getattr(cls, attr)
if is_decorated(func):
setattr(cls, attr, wrapped(func))
But I need a proper check for the is_decorated

Edit: Nvm, I can just use isinstance() check for ListenerManagerDecorator

Re: Is it possible to check if a function has been decorated with a listener?

Posted: Wed Oct 05, 2016 12:37 pm
by iPlayer
I say it depends on the decorator. If it returns original callback, there's no way to tell then.

In your case the decorator (OnLevelChange doesn't exist, but whatever, let's assume it's a regular listener) is basically a constructor of an object, and calling it returns the object. So yeah, isinstance will work in that case.

But as for some PreHook decrorators, the decorator is the __call__ method of the object. And it will return original callback. Take a look: https://github.com/Source-Python-Dev-Team/Source.Python/blob/master/addons/source-python/packages/source-python/entities/hooks.py#L97