Skip to content

Commit

Permalink
.register(fn, name=) option plus documentation, closes #14
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jan 20, 2023
1 parent fd5ef10 commit ddb71fd
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,24 @@ The HTTP requests to `www.example.com` and `simonwillison.net` will be performed

The library notices that `both()` takes two arguments which are the names of other registered `async def` functions, and will construct an execution plan that executes those two functions in parallel, then passes their results to the `both()` method.

### Registering additional functions

In addition to registering functions by passing them to the constructor, you can also add them to a registry using the `.register()` method:

```python
async def another():
return "another"

registry.register(another)
```
To register them with a name other than the name of the function, pass the `name=` argument:
```python
async def another():
return "another 2"

registry.register(another, name="another_2")
```

### Resolving an unregistered function

You don't need to register the final function that you pass to `.resolve()` - if you pass an unregistered function, the library will introspect the function's parameters and resolve them directly.
Expand Down
4 changes: 2 additions & 2 deletions asyncinject/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ def __init__(self, *fns, parallel=True, timer=None):
for fn in fns:
self.register(fn)

def register(self, fn):
self._registry[fn.__name__] = fn
def register(self, fn, *, name=None):
self._registry[name or fn.__name__] = fn
# Clear caches:
self._graph = None
self._reversed = None
Expand Down
26 changes: 26 additions & 0 deletions tests/test_asyncinject.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,29 @@ def three_not_async(one, two):
# Test that passing parameters works too
result2 = await registry.resolve(fn, one=2)
assert result2 == 4


@pytest.mark.asyncio
async def test_register():
registry = Registry()

async def one():
return "one"

async def two_():
return "two"

async def three(one, two):
return one + two

registry.register(one)

# Should raise an error if you don't use name=
with pytest.raises(TypeError):
registry.register(two_, "two")

registry.register(two_, name="two")

result = await registry.resolve(three)

assert result == "onetwo"

0 comments on commit ddb71fd

Please sign in to comment.