-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Docs] Add description for async callable
- Loading branch information
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# 异步可调用 | ||
|
||
在正式开始我们的教程之前,需要简单讲一讲关于“异步可调用”的概念。 | ||
|
||
首先关于“可调用”或“可调用对象”,大家在过去的 Python 开发中,应该有所接触。可调用对象代指任何能被调用的东西,像是一种接口,都能使用 `()` 来触发调用行为: | ||
|
||
```python | ||
class Foo: | ||
def __call__(self, *args, **kwargs): | ||
... | ||
foo = Foo() | ||
|
||
bar1 = lambda *_, **__: ... | ||
|
||
def bar2(*args, **kwargs): | ||
... | ||
|
||
from functools import partial | ||
bar3 = partial(bar2, 1, arg1=2) | ||
|
||
# 它们都是可调用对象,因此可以: | ||
foo() | ||
bar1() | ||
bar2() | ||
bar3() | ||
``` | ||
|
||
可调用对象一般使用 {external:class}`~collections.abc.Callable` 注解: | ||
|
||
```python | ||
f: Callable = ... | ||
``` | ||
|
||
同样的思路,melobot 中提出了 {class}`.AsyncCallable` 类型。它用于许多接口的类型注解,有以下特性: | ||
|
||
{class}`.AsyncCallable`\[{data}`.P`, {data}`.T`\] {math}`\iff` {external:class}`~collections.abc.Callable`\[{data}`.P`, {external:class}`~collections.abc.Awaitable`\[{data}`.T`\]\] | ||
|
||
其中 P 为 {external:class}`~typing.ParamSpec` 泛型,T 为普通的无约束泛型。 | ||
|
||
典型的异步可调用对象包括: | ||
|
||
```python | ||
class Foo: | ||
async def __await__(self): | ||
... | ||
|
||
async def _any_coro_f(*args, **kwargs): ... | ||
bar1 = lambda *_, **__: _any_coro_f(*_, **__) | ||
|
||
async def bar2(*args, **kwargs): | ||
... | ||
|
||
from functools import partial | ||
bar3 = partial(bar2, 1, arg1=2) | ||
|
||
# 它们都是异步可调用对象,因此可以: | ||
await Foo() | ||
await bar1() | ||
await bar2() | ||
await bar3() | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
:maxdepth: 2 | ||
:hidden: | ||
async-callable | ||
create-bot | ||
event-process | ||
msg-action | ||
|