ipython-smart-await 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ipython_smart_await-0.1.0/.github/workflows/release.yml +43 -0
- ipython_smart_await-0.1.0/.github/workflows/test.yml +36 -0
- ipython_smart_await-0.1.0/.gitignore +11 -0
- ipython_smart_await-0.1.0/.pre-commit-config.yaml +9 -0
- ipython_smart_await-0.1.0/LICENSE +21 -0
- ipython_smart_await-0.1.0/PKG-INFO +78 -0
- ipython_smart_await-0.1.0/README.md +51 -0
- ipython_smart_await-0.1.0/pyproject.toml +97 -0
- ipython_smart_await-0.1.0/smart_await/__init__.py +110 -0
- ipython_smart_await-0.1.0/tests/test_smart_await.py +107 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
name: release
|
|
2
|
+
|
|
3
|
+
# Publishes to PyPI via Trusted Publishing (OIDC) when a GitHub Release is published.
|
|
4
|
+
# No API token is used: configure the trusted publisher on PyPI for this project, workflow
|
|
5
|
+
# `release.yml`, and environment `pypi`.
|
|
6
|
+
on:
|
|
7
|
+
release:
|
|
8
|
+
types: [published]
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
build:
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: actions/setup-python@v5
|
|
16
|
+
with:
|
|
17
|
+
python-version: "3.12"
|
|
18
|
+
- name: Build sdist and wheel
|
|
19
|
+
run: |
|
|
20
|
+
python -m pip install --upgrade pip build
|
|
21
|
+
python -m build
|
|
22
|
+
- name: Check metadata
|
|
23
|
+
run: |
|
|
24
|
+
pip install twine
|
|
25
|
+
twine check dist/*
|
|
26
|
+
- uses: actions/upload-artifact@v4
|
|
27
|
+
with:
|
|
28
|
+
name: dist
|
|
29
|
+
path: dist/
|
|
30
|
+
|
|
31
|
+
publish:
|
|
32
|
+
needs: build
|
|
33
|
+
runs-on: ubuntu-latest
|
|
34
|
+
environment: pypi
|
|
35
|
+
permissions:
|
|
36
|
+
id-token: write # required for Trusted Publishing (OIDC)
|
|
37
|
+
steps:
|
|
38
|
+
- uses: actions/download-artifact@v4
|
|
39
|
+
with:
|
|
40
|
+
name: dist
|
|
41
|
+
path: dist/
|
|
42
|
+
- name: Publish to PyPI
|
|
43
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
name: test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main, master]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
lint:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- uses: astral-sh/ruff-action@v3
|
|
14
|
+
with:
|
|
15
|
+
version: 0.14.2
|
|
16
|
+
- name: ruff check
|
|
17
|
+
run: ruff check --no-fix
|
|
18
|
+
- name: ruff format --check
|
|
19
|
+
run: ruff format --check
|
|
20
|
+
|
|
21
|
+
test:
|
|
22
|
+
runs-on: ${{ matrix.os }}
|
|
23
|
+
strategy:
|
|
24
|
+
fail-fast: false
|
|
25
|
+
matrix:
|
|
26
|
+
os: [ubuntu-latest]
|
|
27
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
28
|
+
steps:
|
|
29
|
+
- uses: actions/checkout@v4
|
|
30
|
+
- uses: actions/setup-python@v5
|
|
31
|
+
with:
|
|
32
|
+
python-version: ${{ matrix.python-version }}
|
|
33
|
+
- name: Install
|
|
34
|
+
run: python -m pip install --upgrade pip && pip install -e ".[test]"
|
|
35
|
+
- name: Run tests
|
|
36
|
+
run: pytest -v
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Doron Zarhi, Benjy Wiener
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ipython-smart-await
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Auto-await coroutine results (calls, subscripts, item-assignment) in the IPython REPL.
|
|
5
|
+
Project-URL: Homepage, https://github.com/doronz88/ipython-smart-await
|
|
6
|
+
Project-URL: Repository, https://github.com/doronz88/ipython-smart-await
|
|
7
|
+
Project-URL: Issues, https://github.com/doronz88/ipython-smart-await/issues
|
|
8
|
+
Author-email: Doron Zarhi <doronz@kayhut.com>, Benjy Wiener <benjywiener@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: asyncio,await,extension,ipython,jupyter,repl
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: IPython
|
|
14
|
+
Classifier: Framework :: Jupyter
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: ipython>=8
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: pytest; extra == 'test'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# ipython-smart-await
|
|
29
|
+
|
|
30
|
+
Auto-`await` coroutine results in the IPython REPL — drive a pure-`async` API without typing
|
|
31
|
+
`await` everywhere.
|
|
32
|
+
|
|
33
|
+
When loaded, the extension rewrites each input cell so that expressions which evaluate to a
|
|
34
|
+
coroutine are awaited automatically on IPython's loop runner.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install ipython-smart-await
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
%load_ext smart_await
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Then, given some async API bound to `p`:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
p.get_pid() # -> awaited automatically (no `await` needed)
|
|
52
|
+
a[0] # -> awaited if `a.__getitem__` returns a coroutine
|
|
53
|
+
a[0] = 7 # -> routed to `a.setindex(0, 7)` (awaited) when `a` has an async `setindex`
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Opting out
|
|
57
|
+
|
|
58
|
+
Wrap a call in `...( )` to get the raw, un-awaited value:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
coro = ...(p.get_pid()) # `coro` is the coroutine itself
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Cells that already use `await` / `async` constructs are left untouched.
|
|
65
|
+
|
|
66
|
+
## How it works
|
|
67
|
+
|
|
68
|
+
The extension installs an `ast` transformer (an IPython AST transformer) that wraps:
|
|
69
|
+
|
|
70
|
+
- **calls** (`foo()`) and **subscript reads** (`a[0]`) in a helper that awaits the result only if
|
|
71
|
+
it is a coroutine (non-coroutines pass through unchanged);
|
|
72
|
+
- **single-target subscript assignment** (`a[0] = v`) into a call that routes to an async
|
|
73
|
+
`setindex(key, value)` when the target exposes one, otherwise a normal item assignment — so
|
|
74
|
+
dicts, lists, numpy arrays, etc. are unaffected.
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
|
|
78
|
+
MIT
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# ipython-smart-await
|
|
2
|
+
|
|
3
|
+
Auto-`await` coroutine results in the IPython REPL — drive a pure-`async` API without typing
|
|
4
|
+
`await` everywhere.
|
|
5
|
+
|
|
6
|
+
When loaded, the extension rewrites each input cell so that expressions which evaluate to a
|
|
7
|
+
coroutine are awaited automatically on IPython's loop runner.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install ipython-smart-await
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
%load_ext smart_await
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Then, given some async API bound to `p`:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
p.get_pid() # -> awaited automatically (no `await` needed)
|
|
25
|
+
a[0] # -> awaited if `a.__getitem__` returns a coroutine
|
|
26
|
+
a[0] = 7 # -> routed to `a.setindex(0, 7)` (awaited) when `a` has an async `setindex`
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Opting out
|
|
30
|
+
|
|
31
|
+
Wrap a call in `...( )` to get the raw, un-awaited value:
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
coro = ...(p.get_pid()) # `coro` is the coroutine itself
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Cells that already use `await` / `async` constructs are left untouched.
|
|
38
|
+
|
|
39
|
+
## How it works
|
|
40
|
+
|
|
41
|
+
The extension installs an `ast` transformer (an IPython AST transformer) that wraps:
|
|
42
|
+
|
|
43
|
+
- **calls** (`foo()`) and **subscript reads** (`a[0]`) in a helper that awaits the result only if
|
|
44
|
+
it is a coroutine (non-coroutines pass through unchanged);
|
|
45
|
+
- **single-target subscript assignment** (`a[0] = v`) into a call that routes to an async
|
|
46
|
+
`setindex(key, value)` when the target exposes one, otherwise a normal item assignment — so
|
|
47
|
+
dicts, lists, numpy arrays, etc. are unaffected.
|
|
48
|
+
|
|
49
|
+
## License
|
|
50
|
+
|
|
51
|
+
MIT
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ipython-smart-await"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Auto-await coroutine results (calls, subscripts, item-assignment) in the IPython REPL."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Doron Zarhi", email = "doronz@kayhut.com" },
|
|
15
|
+
{ name = "Benjy Wiener", email = "benjywiener@gmail.com" },
|
|
16
|
+
]
|
|
17
|
+
keywords = ["ipython", "asyncio", "await", "repl", "extension", "jupyter"]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Framework :: IPython",
|
|
21
|
+
"Framework :: Jupyter",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
29
|
+
]
|
|
30
|
+
dependencies = ["ipython>=8"]
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
test = ["pytest"]
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/doronz88/ipython-smart-await"
|
|
37
|
+
Repository = "https://github.com/doronz88/ipython-smart-await"
|
|
38
|
+
Issues = "https://github.com/doronz88/ipython-smart-await/issues"
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["smart_await"]
|
|
42
|
+
|
|
43
|
+
[tool.ruff]
|
|
44
|
+
target-version = "py310"
|
|
45
|
+
line-length = 120
|
|
46
|
+
fix = true
|
|
47
|
+
|
|
48
|
+
[tool.ruff.lint]
|
|
49
|
+
select = [
|
|
50
|
+
# flake8-2020
|
|
51
|
+
"YTT",
|
|
52
|
+
# flake8-bugbear
|
|
53
|
+
"B",
|
|
54
|
+
# flake8-builtins
|
|
55
|
+
"A",
|
|
56
|
+
# flake8-comprehensions
|
|
57
|
+
"C4",
|
|
58
|
+
# flake8-debugger
|
|
59
|
+
"T10",
|
|
60
|
+
# flake8-simplify
|
|
61
|
+
"SIM",
|
|
62
|
+
# isort
|
|
63
|
+
"I",
|
|
64
|
+
# pycodestyle
|
|
65
|
+
"E",
|
|
66
|
+
"W",
|
|
67
|
+
# pyflakes
|
|
68
|
+
"F",
|
|
69
|
+
# pygrep-hooks
|
|
70
|
+
"PGH",
|
|
71
|
+
# pyupgrade
|
|
72
|
+
"UP",
|
|
73
|
+
# ruff
|
|
74
|
+
"RUF",
|
|
75
|
+
# tryceratops
|
|
76
|
+
"TRY",
|
|
77
|
+
]
|
|
78
|
+
ignore = [
|
|
79
|
+
# LineTooLong
|
|
80
|
+
"E501",
|
|
81
|
+
# Custom error classes
|
|
82
|
+
"TRY003",
|
|
83
|
+
# Abstract `raise` to an inner function
|
|
84
|
+
"TRY301",
|
|
85
|
+
# Use of `functools.lru_cache` or `functools.cache` on methods can lead to memory leaks
|
|
86
|
+
"B019",
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
[tool.ruff.lint.isort]
|
|
90
|
+
lines-after-imports = 2
|
|
91
|
+
extra-standard-library = ["typing_extensions"]
|
|
92
|
+
|
|
93
|
+
[tool.ruff.format]
|
|
94
|
+
preview = true
|
|
95
|
+
|
|
96
|
+
[tool.pytest.ini_options]
|
|
97
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Auto-await coroutine results in the IPython REPL.
|
|
2
|
+
|
|
3
|
+
Loading this extension (``%load_ext smart_await``) rewrites each input cell so that
|
|
4
|
+
expressions which evaluate to a coroutine are awaited automatically:
|
|
5
|
+
|
|
6
|
+
- calls: ``foo()`` -> awaited if ``foo()`` returns a coroutine
|
|
7
|
+
- subscript reads: ``a[0]`` -> awaited if ``a.__getitem__`` returns a coroutine
|
|
8
|
+
- subscript assigns: ``a[0] = 7`` -> routed to ``a.setindex(0, 7)`` (awaited) when ``a``
|
|
9
|
+
exposes an async ``setindex``; otherwise a normal
|
|
10
|
+
``a[0] = 7``
|
|
11
|
+
|
|
12
|
+
Wrap any call in ``...( )`` to opt out and get the raw (un-awaited) value, e.g. ``...(foo())``.
|
|
13
|
+
|
|
14
|
+
The cell is left untouched when it already uses ``await``/``async`` constructs.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import ast
|
|
18
|
+
import asyncio
|
|
19
|
+
import builtins
|
|
20
|
+
import warnings
|
|
21
|
+
from functools import partial
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from IPython.core.interactiveshell import InteractiveShell
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
__all__ = ["load_ipython_extension"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _maybe_await(ip: InteractiveShell, obj: object) -> object:
|
|
32
|
+
"""Await ``obj`` on the shell's loop runner if it is a coroutine, else return it unchanged."""
|
|
33
|
+
if asyncio.iscoroutine(obj):
|
|
34
|
+
return ip.loop_runner(obj)
|
|
35
|
+
return obj
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _setitem(ip: InteractiveShell, target: Any, key: object, value: object) -> None:
|
|
39
|
+
"""Backing for rewritten ``target[key] = value``.
|
|
40
|
+
|
|
41
|
+
Objects whose ``__setitem__`` can't be awaited may instead expose an async ``setindex``.
|
|
42
|
+
Route through it (awaited) when present; otherwise fall back to normal item assignment so
|
|
43
|
+
dicts/lists/etc. are unaffected.
|
|
44
|
+
"""
|
|
45
|
+
setindex = getattr(target, "setindex", None)
|
|
46
|
+
if setindex is None:
|
|
47
|
+
target[key] = value
|
|
48
|
+
return
|
|
49
|
+
_maybe_await(ip, setindex(key, value))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _SmartAwaitTransformer(ast.NodeTransformer):
|
|
53
|
+
def __init__(self, ip: InteractiveShell) -> None:
|
|
54
|
+
super().__init__()
|
|
55
|
+
self.ip: InteractiveShell = ip
|
|
56
|
+
|
|
57
|
+
def visit_Module(self, node: ast.Module) -> ast.Module:
|
|
58
|
+
# Only transform cells that don't already use async constructs (await / async for / ...).
|
|
59
|
+
unparsed = ast.unparse(node)
|
|
60
|
+
if not self.ip.should_run_async(unparsed, transformed_cell=unparsed):
|
|
61
|
+
self.generic_visit(node)
|
|
62
|
+
ast.fix_missing_locations(node)
|
|
63
|
+
return node
|
|
64
|
+
|
|
65
|
+
def visit_Call(self, node: ast.Call) -> ast.AST:
|
|
66
|
+
match node:
|
|
67
|
+
# Skip anything inside `...(<expr>)` (explicit opt-out).
|
|
68
|
+
case ast.Call(ast.Constant(value=builtins.Ellipsis), args=[inner]):
|
|
69
|
+
return inner
|
|
70
|
+
|
|
71
|
+
visited_node = self.generic_visit(node)
|
|
72
|
+
assert isinstance(visited_node, ast.expr)
|
|
73
|
+
return ast.Call(func=ast.Name(_maybe_await.__name__, ctx=ast.Load()), args=[visited_node], keywords=[])
|
|
74
|
+
|
|
75
|
+
def visit_Subscript(self, node: ast.Subscript) -> ast.AST:
|
|
76
|
+
visited_node = self.generic_visit(node)
|
|
77
|
+
assert isinstance(visited_node, ast.expr)
|
|
78
|
+
# Only reads yield a (possibly awaitable) value; never wrap an assignment/deletion target.
|
|
79
|
+
if not isinstance(node.ctx, ast.Load):
|
|
80
|
+
return visited_node
|
|
81
|
+
return ast.Call(func=ast.Name(_maybe_await.__name__, ctx=ast.Load()), args=[visited_node], keywords=[])
|
|
82
|
+
|
|
83
|
+
def visit_Assign(self, node: ast.Assign) -> ast.AST:
|
|
84
|
+
visited_node = self.generic_visit(node)
|
|
85
|
+
assert isinstance(visited_node, ast.Assign)
|
|
86
|
+
# Rewrite `target[key] = value` into `_setitem(target, key, value)` so subscript assignment
|
|
87
|
+
# can be awaited. Only the simple single-target, non-slice form is rewritten; everything
|
|
88
|
+
# else (plain names, tuples, slices) is left as-is.
|
|
89
|
+
match visited_node.targets:
|
|
90
|
+
case [ast.Subscript(value=target, slice=key, ctx=ast.Store())] if not isinstance(key, ast.Slice):
|
|
91
|
+
return ast.Expr(
|
|
92
|
+
value=ast.Call(
|
|
93
|
+
func=ast.Name(_setitem.__name__, ctx=ast.Load()),
|
|
94
|
+
args=[target, key, visited_node.value],
|
|
95
|
+
keywords=[],
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
return visited_node
|
|
99
|
+
|
|
100
|
+
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> ast.AsyncFunctionDef:
|
|
101
|
+
# Don't descend into `async def`s; they manage their own awaiting.
|
|
102
|
+
return node
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_ipython_extension(ip: InteractiveShell) -> None:
|
|
106
|
+
"""Load the extension: register the helpers and the AST transformer."""
|
|
107
|
+
ip.user_ns_hidden[_maybe_await.__name__] = ip.user_ns[_maybe_await.__name__] = partial(_maybe_await, ip)
|
|
108
|
+
ip.user_ns_hidden[_setitem.__name__] = ip.user_ns[_setitem.__name__] = partial(_setitem, ip)
|
|
109
|
+
ip.ast_transformers.append(_SmartAwaitTransformer(ip))
|
|
110
|
+
warnings.filterwarnings("ignore", message=r"'ellipsis' object is not callable", category=SyntaxWarning)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import asyncio
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from IPython.core.interactiveshell import InteractiveShell
|
|
6
|
+
|
|
7
|
+
import smart_await
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture
|
|
11
|
+
def ip() -> InteractiveShell:
|
|
12
|
+
shell = InteractiveShell.instance()
|
|
13
|
+
# Drive top-level awaits synchronously to completion for the tests.
|
|
14
|
+
shell.loop_runner = lambda coro: asyncio.new_event_loop().run_until_complete(coro)
|
|
15
|
+
# Reset any transformers/namespace left by a previous test.
|
|
16
|
+
shell.ast_transformers = [t for t in shell.ast_transformers if type(t).__name__ != "_SmartAwaitTransformer"]
|
|
17
|
+
smart_await.load_ipython_extension(shell)
|
|
18
|
+
return shell
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _rewrite(ip: InteractiveShell, src: str) -> str:
|
|
22
|
+
tree = ast.parse(src)
|
|
23
|
+
for transformer in ip.ast_transformers:
|
|
24
|
+
tree = transformer.visit(tree)
|
|
25
|
+
ast.fix_missing_locations(tree)
|
|
26
|
+
return ast.unparse(tree)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class FakeSym:
|
|
30
|
+
"""Minimal async-symbol stand-in: coroutine __getitem__, async setindex, un-awaitable __setitem__."""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self.store: dict = {}
|
|
34
|
+
|
|
35
|
+
def __getitem__(self, index):
|
|
36
|
+
async def _get():
|
|
37
|
+
return self.store.get(index)
|
|
38
|
+
|
|
39
|
+
return _get()
|
|
40
|
+
|
|
41
|
+
async def setindex(self, index, value) -> None:
|
|
42
|
+
self.store[index] = value
|
|
43
|
+
|
|
44
|
+
def __setitem__(self, index, value) -> None:
|
|
45
|
+
raise TypeError("use setindex")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_call_is_wrapped(ip: InteractiveShell) -> None:
|
|
49
|
+
assert _rewrite(ip, "foo()") == "_maybe_await(foo())"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_subscript_read_is_wrapped(ip: InteractiveShell) -> None:
|
|
53
|
+
assert _rewrite(ip, "a[0]") == "_maybe_await(a[0])"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_subscript_assign_is_rewritten(ip: InteractiveShell) -> None:
|
|
57
|
+
assert _rewrite(ip, "a[0] = 7") == "_setitem(a, 0, 7)"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_plain_assign_untouched(ip: InteractiveShell) -> None:
|
|
61
|
+
assert _rewrite(ip, "x = 9") == "x = 9"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_slice_assign_untouched(ip: InteractiveShell) -> None:
|
|
65
|
+
assert _rewrite(ip, "a[1:2] = 3") == "a[1:2] = 3"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_ellipsis_opt_out(ip: InteractiveShell) -> None:
|
|
69
|
+
assert _rewrite(ip, "...(foo())") == "foo()"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_call_auto_awaited(ip: InteractiveShell) -> None:
|
|
73
|
+
async def foo():
|
|
74
|
+
return 42
|
|
75
|
+
|
|
76
|
+
ip.user_ns["foo"] = foo
|
|
77
|
+
assert ip.run_cell("foo()").result == 42
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_subscript_read_auto_awaited(ip: InteractiveShell) -> None:
|
|
81
|
+
a = FakeSym()
|
|
82
|
+
a.store[0] = "hello"
|
|
83
|
+
ip.user_ns["a"] = a
|
|
84
|
+
assert ip.run_cell("a[0]").result == "hello"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_subscript_assign_routes_to_setindex(ip: InteractiveShell) -> None:
|
|
88
|
+
a = FakeSym()
|
|
89
|
+
ip.user_ns["a"] = a
|
|
90
|
+
assert ip.run_cell("a[0] = 7").success
|
|
91
|
+
assert a.store == {0: 7}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_dict_assign_unaffected(ip: InteractiveShell) -> None:
|
|
95
|
+
ip.user_ns["d"] = {}
|
|
96
|
+
assert ip.run_cell("d['k'] = 5").success
|
|
97
|
+
assert ip.user_ns["d"] == {"k": 5}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_ellipsis_returns_raw_coroutine(ip: InteractiveShell) -> None:
|
|
101
|
+
async def foo():
|
|
102
|
+
return 1
|
|
103
|
+
|
|
104
|
+
ip.user_ns["foo"] = foo
|
|
105
|
+
result = ip.run_cell("...(foo())").result
|
|
106
|
+
assert asyncio.iscoroutine(result)
|
|
107
|
+
result.close()
|