Skip to content

Commit

Permalink
Merge pull request #30 from Zuehlke/feature/async-decorator
Browse files Browse the repository at this point in the history
Feature/async decorator
  • Loading branch information
silvanmelchior authored Nov 30, 2021
2 parents 21c1687 + 9fd1a00 commit 76dcc61
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 53 deletions.
14 changes: 11 additions & 3 deletions confz/change.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,17 @@ def __init__(self, fn: Callable[[], Any], config_classes: List[Type['ConfZ']]):
self._backup_instances = {}

def __call__(self):
if self._instance is None:
self._instance = self._fn()
return self._instance
if inspect.iscoroutinefunction(self._fn):
async def inner():
if self._instance is None:
self._instance = await self._fn()
return self._instance
else:
def inner():
if self._instance is None:
self._instance = self._fn()
return self._instance
return inner()

def change_enter(self, context):
self._backup_instances[context] = self._instance
Expand Down
15 changes: 15 additions & 0 deletions docs/source/usage/listeners.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ changed because we are in a config change context manager and the function gets
allowing the new config to take effect. As soon as the context is left again, the original instance of the function
singleton will be active again.

This decorator also works for asynchronous functions::

from confz import depends_on

@depends_on(DBConfig)
async def get_engine():
engine = create_async_engine(f'sqlite:///{DBConfig().path}', echo=True)

async with engine.begin() as conn:
await conn.run_sync(meta.drop_all)
await conn.run_sync(meta.create_all)

return engine


Early Loading
-------------

Expand Down
Loading

0 comments on commit 76dcc61

Please sign in to comment.