Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically add property #159

Open
dakhnod opened this issue Jan 17, 2024 · 2 comments
Open

Dynamically add property #159

dakhnod opened this issue Jan 17, 2024 · 2 comments

Comments

@dakhnod
Copy link

dakhnod commented Jan 17, 2024

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
Copy link
Contributor

elParaguayo commented Jan 20, 2024

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
Copy link
Author

dakhnod commented Jan 27, 2024

That is awful...thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants