snug
snug copied to clipboard
executing queries with method chaining
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()
"flowing" might be confusing, it's "Method chaining"
@Kub-AT thanks, I have updated the issue title accordingly.
added a recipe in release 1.2, see http://snug.readthedocs.io/en/latest/recipes.html#method-chaining