altdesktop / i3ipc-python

🐍 An improved Python library to control i3wm and sway.
http://i3ipc-python.readthedocs.io
BSD 3-Clause "New" or "Revised" License
851 stars 109 forks source link

Add decorator syntax for event handlers #188

Closed pjeanjean closed 2 years ago

pjeanjean commented 3 years ago

This PR provides an alternative syntax to define event handlers, using function decorators.

The syntax without this PR looks like this:

    sway = await Connection().connect()

    async def on_window_focus(sway, e):
        pass

    sway.on(Event.WINDOW_FOCUS, on_window_focus)

This is still supported with the changes introduced in this PR.

The only difference is that this new syntax is now also available:

    sway = await Connection().connect()

    @sway.on(Event.WINDOW_FOCUS)
    async def on_window_focus(sway, e):
        pass

It is also possible to stack multiple decorators on the same event handler:

    sway = await Connection().connect()

    @sway.on(Event.WINDOW_FOCUS)
    @sway.on(Event.WINDOW_CLOSE)
    @sway.on(Event.WINDOW_TITLE)
    async def on_window_event(sway, e):
        pass
acrisci commented 3 years ago

Great, would you please add a test for this?

pjeanjean commented 3 years ago

Are these enough?

acrisci commented 2 years ago

:+1: