Skip to content

Dynamically add property #159

Description

@dakhnod

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?

Activity

  1. elParaguayo commented on Jan 20, 2024

    @elParaguayo
    Contributor

    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.

  2. dakhnod commented on Jan 27, 2024

    @dakhnod
    Author

    That is awful...thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions