altdesktop / python-dbus-next

🚌 The next great DBus library for Python with asyncio support
https://python-dbus-next.readthedocs.io/en/latest/
MIT License
187 stars 58 forks source link

Dynamically add property #159

Open dakhnod opened 5 months ago

dakhnod commented 5 months ago

I have a dynamic list of properties as a variable, and I need to declare a property for each of the values. In other words: how can I create and register a Property without declaring a function in my class?

elParaguayo commented 5 months ago

This is very, very hacky but you could do something like this:

from dbus_next.constants import PropertyAccess
from dbus_next.service import ServiceInterface, dbus_property

class DynamicProps(ServiceInterface):
    def __init__(self, *args, **kwargs):
        ServiceInterface.__init__(self, *args, **kwargs)

        self._trueprop = True
        self._falseprop = False

        props = ["_trueprop", "_falseprop"]

        def bool_prop(name):
            def _wrapper(self) -> "b":
                return getattr(self, name)
            return _wrapper

        for prop in props:
            name = prop[1:].capitalize()
            func = bool_prop(prop)
            func.__name__ = name
            member = dbus_property(access=PropertyAccess.READ)(func)
            setattr(DynamicProps, name, member)
            self._ServiceInterface__properties.append(member)

I've no idea if there's an easier way or not.

dakhnod commented 5 months ago

That is awful...thank you!