python-dbus-next icon indicating copy to clipboard operation
python-dbus-next copied to clipboard

Dynamically add property

Open dakhnod opened this issue 1 year ago • 2 comments

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?

dakhnod avatar Jan 17 '24 23:01 dakhnod

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.

elParaguayo avatar Jan 20 '24 16:01 elParaguayo

That is awful...thank you!

dakhnod avatar Jan 27 '24 17:01 dakhnod