Skip to content

executing queries with method chaining #22

@ariebovenberg

Description

@ariebovenberg

It is possible to implement a method chaining API, with:

class Explorer:

    def __init__(self, obj, *, executor=execute):
        self.__wrapped__ = obj
        self._executor = executor

    def execute(self, **kwargs):
        """execute the wrapped object as a query

        Parameters
        ----------
        **kwargs
            arguments passed to the executor
        """
        return self._executor(self.__wrapped__, **kwargs)

    def __getattr__(self, name):
        return Explorer(getattr(self.__wrapped__, name),
                        executor=self._executor)

    def __repr__(self):
        return f'Explorer({self.__wrapped__!r})'

    def __call__(self, *args, **kwargs):
        return Explorer(self.__wrapped__(*args, **kwargs),
                        executor=self._executor)

Usable like

module = Explorer(my_module)
module.my_query(bla=4).related_query().execute()

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions