ipython-smart-await 0.1.0__py3-none-any.whl

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.
@@ -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,5 @@
1
+ smart_await/__init__.py,sha256=6GXF9GQ-ZVJ85GB_LuGWXkCEoZwUTgtBmng2In9pXGs,4855
2
+ ipython_smart_await-0.1.0.dist-info/METADATA,sha256=XYYMHrKrHax_sAFq3dRPH2KUSwgBFl6Drc4ECrYoIfA,2625
3
+ ipython_smart_await-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
4
+ ipython_smart_await-0.1.0.dist-info/licenses/LICENSE,sha256=ie6PhMw578kaNgE6OBe92yIftXs_aWLGppprmIYsYzI,1082
5
+ ipython_smart_await-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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,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)