snug icon indicating copy to clipboard operation
snug copied to clipboard

executing queries with method chaining

Open ariebovenberg opened this issue 6 years ago • 3 comments

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()

ariebovenberg avatar Mar 04 '18 21:03 ariebovenberg

"flowing" might be confusing, it's "Method chaining"

Kub-AT avatar Mar 13 '18 09:03 Kub-AT

@Kub-AT thanks, I have updated the issue title accordingly.

ariebovenberg avatar Mar 13 '18 12:03 ariebovenberg

added a recipe in release 1.2, see http://snug.readthedocs.io/en/latest/recipes.html#method-chaining

ariebovenberg avatar Mar 21 '18 20:03 ariebovenberg