pythondecoratoraiortc

Is it possible to use methods on decorators?


I was looking around the aiortc examples when I notice a decorator that has a method on it:

@pc.on("datachannel")
    def on_datachannel(channel):
    ...

I don't really understand how this work or what does this code do. I've been searching about decorators and I know it's possible to have class decorators but none about using methods. Can anyone elaborate on this?


Solution

  • @foo
    def bar(): ...
    

    This syntax is merely sugar for this:

    def bar(): ...
    bar = foo(bar)
    

    So, this:

    @pc.on('datachannel')
    def on_datachannel(channel): ...
    

    is the same as:

    def on_datachannel(channel): ...
    on_datachannel = pc.on('datachannel')(on_datachannel)
    

    pc is some object, pc.on is a method on it, pc.on('datachannel') calls it and it returns a function, pc.on('datachannel')(on_datachannel) calls that returned function passing it the on_datachannel function.

    The implementation of pc.on is something like this:

    class PC:
        def on(self, event):
            ...
            def wrapper(fn):
                ...
                def inner_wrapper(*args, **kwargs):
                    ...
                    fn(*args, **kwargs)
    
                return inner_wrapper
    
            return wrapper
    
    pc = PC()
    

    All that inner part is entirely a regular decorator accepting arguments. That it's defined on a class makes no difference to it.