@node-ctypes/python 0.1.1 → 0.2.1

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.
package/README.md CHANGED
@@ -1,214 +1,230 @@
1
- # node-python (`@node-ctypes/python`)
2
-
3
- Embed CPython in Node.js with a TypeScript API powered by
4
- [node-ctypes](https://www.npmjs.com/package/node-ctypes).
5
- This standalone ESM package ships compiled JavaScript and declarations.
6
- Python runs in-process, not in a subprocess or sandbox.
7
-
8
- ## Requirements and installation
9
-
10
- - Node.js 24+ and an ESM application.
11
- - Python 3.12+ with a shared library matching Node.js architecture and Python ABI.
12
- - Windows, Linux or macOS.
13
-
14
- Windows and macOS installations normally include the shared library. On
15
- Debian/Ubuntu install the matching `libpython3.x` package; with pyenv use
16
- `PYTHON_CONFIGURE_OPTS=--enable-shared`.
17
- Install optional Python dependencies into the selected interpreter's environment.
18
- Neither Python nor its packages are bundled.
19
-
20
- ```sh
21
- npm install @node-ctypes/python
22
- ```
23
-
24
- To build from source, run from this directory:
25
-
26
- ```sh
27
- npm install
28
- npm run build
29
- npm test
30
- npm pack
31
- ```
32
-
33
- Install the resulting tarball into your application with
34
- `npm install /path/to/node-ctypes-python-0.1.0.tgz`.
35
- The runtime dependency is published `node-ctypes` (`^2.10.0`); no custom native
36
- bridge, core patch or JavaScript worker is required.
37
-
38
- ## Quick start
39
-
40
- ```typescript
41
- import { Python, kwargs } from "@node-ctypes/python";
42
-
43
- const python = await Python.initialize({ stdin: false, stdout: "node", stderr: "node" });
44
- try {
45
- const math = await python.import("math");
46
- console.log(await math.sqrt(81)); // 9
47
-
48
- await python.exec("def add(a, b): return a + b");
49
- console.log(await python.main.add(20, 22)); // 42
50
-
51
- const json = await python.import("json");
52
- console.log(await json.dumps({ b: 2, a: 1 }, kwargs({ sort_keys: true })));
53
-
54
- python.module("node", { greet: (name: string) => `Hello ${name}` });
55
- await python.exec("import node\nprint(node.greet('Python'))");
56
- } finally {
57
- await python.finalize();
58
- }
59
- ```
60
-
61
- ### Configuration
62
-
63
- `Python.initialize({ executable, library, stdin, stdout, stderr, synchronousCallbacks, switchInterval })`
64
- returns the runtime singleton. Options apply to the first initialization.
65
-
66
- - `executable`, or `PYTHON`, selects the interpreter; an explicit choice never
67
- falls back. Otherwise discovery tries installed Python commands.
68
- - `library`, or `PYTHON_LIBRARY`, overrides shared-library discovery. The selected
69
- interpreter supplies `sys.path`, including virtualenv paths. Each discovery
70
- probe has a 10-second timeout.
71
- - `stdin: false` leaves standard input to Node.js. `stdout` and `stderr` accept
72
- `"inherit"` (default), `"node"` or a text callback.
73
- - `synchronousCallbacks: true` enables native callback dispatch during
74
- interruptible synchronous Python waits. It requires an available SIGURG wakeup
75
- on POSIX, or Windows Python 3.14+ with its interrupt event available.
76
- Unsupported configurations fail explicitly; the default is `false`.
77
- - `switchInterval` sets the GIL switch interval in milliseconds
78
- (`sys.setswitchinterval`). The default is `5`, as in CPython. Every Python call
79
- acquires the GIL on the Node.js thread, so while Python threads run CPU-bound
80
- code each call can stall the event loop for several intervals: on Windows we
81
- measured stalls of 150–250 ms with the default. `0.5` reduced them to under
82
- 50 ms, but slowed two contending CPU-bound Python threads by 40% or more.
83
- To keep the main thread free without that cost, host Python in a worker
84
- (`examples/worker.ts`).
85
-
86
- Native objects are always enabled; there is no `nativeObjects` mode.
87
- Free-threaded builds require their matching executable and shared library;
88
- an ABI3t compatibility DLL alone does not enable free threading.
89
-
90
- ## API and execution model
91
-
92
- | API | Purpose |
93
- | ------------------------------------------------ | ------------------------------------------------------ |
94
- | `Python.initialize(options)` | Initialize the singleton asynchronously |
95
- | `python.main`, `python.builtins` | Live module proxies |
96
- | `python.version`, `.executable`, `.library` | Selected interpreter information |
97
- | `await python.exec(code)` | Execute statements in `__main__` |
98
- | `await python.eval<T>(expression)` | Evaluate and deeply convert the result |
99
- | `await python.import<T>(name)` | Import a live module, including dotted names |
100
- | `python.module(name, members)` | Register JavaScript members as a Python module |
101
- | `python.toPython<T>(value)` | Create an explicitly disposable Python proxy |
102
- | `python.run(operation, { signal })` | Await a Python operation or awaitable, with abort |
103
- | `await python.with(manager, body)` / `asyncWith` | Run a context manager, including exception suppression |
104
- | `python.stats()` | Inspect shared-reference and scheduler counters |
105
- | `await python.finalize()` | Drain accepted native calls and close the runtime |
106
-
107
- Exports also include `PythonError`, `Tuple`, `kwargs`, `byReference` and
108
- `cancellable`. Types and generics describe the dynamic API; they do not validate
109
- Python types at runtime.
110
-
111
- **Calls are asynchronous; live access is synchronous.** Python functions, methods,
112
- classes and builtins return Promises, including `await new cls(...)`.
113
- Calls, imports, `exec` and `eval` execute on one Python-owned thread without
114
- occupying a waiting libuv worker. Arguments and results are converted on Node.js.
115
- Attributes, indices, assignment, enumeration, ordinary iteration, conversion and
116
- disposal remain synchronous and can block Node.js. Native initialization and
117
- finalization also run synchronously on the hosting Node.js thread.
118
-
119
- Python coroutine results are automatically awaited through a separate asyncio
120
- thread. Async iterators work in both directions. An async JavaScript callback
121
- must be awaited from Python; a synchronous Python callback cannot return a
122
- JavaScript Promise. `cancellable(fn)` adds an `AbortSignal` to callbacks that
123
- cooperate with Python cancellation.
124
-
125
- `python.run(operation, { signal })` accepts the Promise of a call, `exec`,
126
- `eval` or `import`, or a Python awaitable, and rejects with `signal.reason`
127
- on abort (`AbortSignal.timeout(ms)` for time limits). A queued operation is
128
- skipped; running Python code receives one `KeyboardInterrupt`, so `finally`
129
- blocks run and `except Exception` does not swallow it. On CPython 3.12 only,
130
- a one-line loop that starts a `try` block (`try:` followed by `while True: ...`)
131
- skips that `finally` when interrupted; put the loop body on its own line.
132
- Native calls are
133
- interrupted only when they return; asyncio work is cancelled. Synchronous proxy
134
- access and JavaScript work cannot be aborted.
135
-
136
- ### Values, memory and lifetime
137
-
138
- - Scalars convert naturally; Python integers outside JavaScript's safe range
139
- become bigints. Arrays, `Tuple`, objects/Maps and Sets copy to Python containers.
140
- Dates become UTC datetimes; Temporal conversions require runtime support.
141
- - Other Python objects remain live proxies. `eval()` and `proxy.toJS()` perform
142
- deep conversion; ordinary call results use shallow conversion. Circular copies
143
- are rejected; use live proxies or `byReference()` instead.
144
- - Arbitrary JavaScript instances remain shared references. `byReference(value)`
145
- also shares ordinary containers. Python attributes take precedence over dict keys.
146
- - Buffer/Uint8Array values copy to Python bytes; other typed arrays, ArrayBuffers
147
- and DataViews expose shared memoryviews. `byReference(buffer)` shares writable
148
- memory. `proxy.toTypedArray()` requires a C-contiguous Python buffer and copies
149
- read-only buffers. Do not detach, transfer or resize shared backing memory.
150
- - Release owned proxies with `[Symbol.dispose]()` when practical, including
151
- `PythonError.exception`. GC is nondeterministic. Disposal drops the reference
152
- immediately; on free-threaded builds CPython may run the object's destructor
153
- later, when the thread that created it next runs Python code. `PythonError` exposes `type`,
154
- `traceback`, `exception` and, when available, the original JavaScript `cause`.
155
-
156
- Only one JavaScript thread per process may host Python. A Node.js worker can
157
- isolate synchronous access and conversions, but must finalize before terminating.
158
- Wait for application work and Python threads before finalization; do not finalize
159
- inside a Python callback. Repeated finalization is harmless; restart and
160
- subinterpreters are not supported. Never use Python proxies or Python-backed
161
- memory afterward.
162
-
163
- Closing rejects new calls and drains accepted native operations, not every
164
- pending coroutine: remaining awaits are rejected during teardown. Cleanup also
165
- runs on normal `beforeExit`; `process.exit()` is not orderly finalization.
166
- Shutdown can wait for Python threads and has no overall timeout.
167
- Execute trusted Python code only.
168
-
169
- ## Examples and tests
170
-
171
- Run examples directly, for example `node examples/basics.ts`.
172
- They cover usage in more detail than this overview:
173
-
174
- | Example | Focus |
175
- | --------------------------------------------- | --------------------------------------------- |
176
- | [basics.ts](./examples/basics.ts) | Values, live objects, errors and conversions |
177
- | [callbacks.ts](./examples/callbacks.ts) | JavaScript callbacks and constructors |
178
- | [threads.ts](./examples/threads.ts) | Python threads and cross-thread callbacks |
179
- | [async.ts](./examples/async.ts) | Await, cancellation and async iteration |
180
- | [module.ts](./examples/module.ts) | JavaScript modules and local Python imports |
181
- | [worker.ts](./examples/worker.ts) | Hosting Python in a Node.js worker |
182
- | [cryptography.ts](./examples/cryptography.ts) | Python cryptography integration |
183
- | [lxml.ts](./examples/lxml.ts) | XML parsing, XPath, XSLT and canonicalization |
184
-
185
- Optional packages are needed only for the corresponding examples and must be
186
- installed in the selected interpreter. Set `PYTHON` to that executable if it
187
- differs from the one found automatically. The suite regression-tests callbacks
188
- and missing-package diagnostics; other example scenarios are manual.
189
-
190
- ```sh
191
- npm run typecheck
192
- npm test
193
- npm run test:unit
194
- npm run test:integration
195
- npm run test:types
196
- npm run test:backlog
197
- npm run test:stress
198
- ```
199
-
200
- `npm test` builds and runs the ordinary suite; integration tests require shared
201
- CPython. Typechecks include sources, examples and test helpers.
202
- `test:backlog` checks queued ownership, every outcome and shutdown under load.
203
- `test:stress` adds a 60-second mixed workload; set `NODE_PYTHON_STRESS_SECONDS`
204
- to change its duration. Both are opt-in, force GC in isolated children and report
205
- memory/latency diagnostics, not performance or leak-certification guarantees.
206
- The runtime does not impose application backpressure.
207
-
208
- The [CI workflow](./.github/workflows/ci.yml) runs `npm test` with Python
209
- 3.12, 3.13, 3.14, 3.14t and 3.15 on Windows, Linux and macOS. It is discovered only when
210
- this package is a repository root, not while nested in another repository.
211
- Pushing a `v<version>` tag that matches `package.json` publishes to npm once the
212
- whole matrix passes (npm Trusted Publishing; versions with a `-` go to `next`).
213
- For implementation diagrams and ownership invariants, see [FLOWS.md](./FLOWS.md)
214
- (Italian).
1
+ # node-python (`@node-ctypes/python`)
2
+
3
+ Embed CPython in Node.js with a TypeScript API powered by
4
+ [node-ctypes](https://www.npmjs.com/package/node-ctypes).
5
+ This standalone ESM package ships compiled JavaScript and declarations.
6
+ Python runs in-process, not in a subprocess or sandbox.
7
+
8
+ ## Requirements and installation
9
+
10
+ - Node.js 24+ and an ESM application.
11
+ - Python 3.12+ with a shared library matching Node.js architecture and Python ABI.
12
+ - Windows, Linux or macOS.
13
+
14
+ Windows and macOS installations normally include the shared library. On
15
+ Debian/Ubuntu install the matching `libpython3.x` package; with pyenv use
16
+ `PYTHON_CONFIGURE_OPTS=--enable-shared`.
17
+ Install optional Python dependencies into the selected interpreter's environment.
18
+ Neither Python nor its packages are bundled.
19
+
20
+ ```sh
21
+ npm install @node-ctypes/python
22
+ ```
23
+
24
+ To build from source, run from this directory:
25
+
26
+ ```sh
27
+ npm install
28
+ npm run build
29
+ npm test
30
+ npm pack
31
+ ```
32
+
33
+ Install the resulting tarball into your application with
34
+ `npm install /path/to/node-ctypes-python-0.1.0.tgz`.
35
+ The runtime dependency is published `node-ctypes` (`^2.10.0`); no custom native
36
+ bridge, core patch or JavaScript worker is required.
37
+
38
+ ## Quick start
39
+
40
+ ```typescript
41
+ import { Python, kwargs } from "@node-ctypes/python";
42
+
43
+ const python = await Python.initialize({ stdin: false, stdout: "node", stderr: "node" });
44
+ try {
45
+ const math = await python.import("math");
46
+ console.log(await math.sqrt(81)); // 9
47
+
48
+ await python.exec("def add(a, b): return a + b");
49
+ console.log(await python.main.add(20, 22)); // 42
50
+
51
+ const json = await python.import("json");
52
+ console.log(await json.dumps({ b: 2, a: 1 }, kwargs({ sort_keys: true })));
53
+
54
+ python.module("node", { greet: (name: string) => `Hello ${name}` });
55
+ await python.exec("import node\nprint(node.greet('Python'))");
56
+ } finally {
57
+ await python.finalize();
58
+ }
59
+ ```
60
+
61
+ ### Configuration
62
+
63
+ `Python.initialize({ executable, library, stdin, stdout, stderr, synchronousCallbacks, switchInterval })`
64
+ returns the runtime singleton. Options apply to the first initialization.
65
+
66
+ - `executable`, or `PYTHON`, selects the interpreter; an explicit choice never
67
+ falls back. Otherwise discovery tries installed Python commands.
68
+ - `library`, or `PYTHON_LIBRARY`, overrides shared-library discovery. The selected
69
+ interpreter supplies `sys.path`, including virtualenv paths. Each discovery
70
+ probe has a 10-second timeout.
71
+ - `stdin: false` leaves standard input to Node.js. `stdout` and `stderr` accept
72
+ `"inherit"` (default), `"node"`, `"console"` or a text callback. `"console"`
73
+ sends whole lines to `console.log` / `console.error` (a line without its newline
74
+ on `flush()` or at finalization). Without a console, as in an Electron renderer
75
+ or a packaged GUI app on Windows, Python's `sys.stdout` and `sys.stderr` are
76
+ `None` and `"inherit"` discards the output, as `pythonw` does: use `"console"`
77
+ (DevTools) or a callback (e.g. a log file).
78
+ - `synchronousCallbacks: true` enables native callback dispatch during
79
+ interruptible synchronous Python waits. It requires an available SIGURG wakeup
80
+ on POSIX, or Windows Python 3.14+ with its interrupt event available.
81
+ Unsupported configurations fail explicitly; the default is `false`.
82
+ - `switchInterval` sets the GIL switch interval in milliseconds
83
+ (`sys.setswitchinterval`). The default is `5`, as in CPython. Every Python call
84
+ acquires the GIL on the Node.js thread, so while Python threads run CPU-bound
85
+ code each call can stall the event loop for several intervals: on Windows we
86
+ measured stalls of 150–250 ms with the default. `0.5` reduced them to under
87
+ 50 ms, but slowed two contending CPU-bound Python threads by 40% or more.
88
+ To keep the main thread free without that cost, host Python in a worker
89
+ (`examples/worker.ts`).
90
+
91
+ Native objects are always enabled; there is no `nativeObjects` mode.
92
+ Free-threaded builds require their matching executable and shared library;
93
+ an ABI3t compatibility DLL alone does not enable free threading.
94
+
95
+ ## API and execution model
96
+
97
+ | API | Purpose |
98
+ | ------------------------------------------------ | ------------------------------------------------------ |
99
+ | `Python.initialize(options)` | Initialize the singleton asynchronously |
100
+ | `python.main`, `python.builtins` | Live module proxies |
101
+ | `python.version`, `.executable`, `.library` | Selected interpreter information |
102
+ | `await python.exec(code)` | Execute statements in `__main__` |
103
+ | `await python.eval<T>(expression)` | Evaluate and deeply convert the result |
104
+ | `await python.import<T>(name)` | Import a live module, including dotted names |
105
+ | `python.module(name, members)` | Register JavaScript members as a Python module |
106
+ | `python.toPython<T>(value)` | Create an explicitly disposable Python proxy |
107
+ | `python.run(operation, { signal })` | Await a Python operation or awaitable, with abort |
108
+ | `await python.with(manager, body)` / `asyncWith` | Run a context manager, including exception suppression |
109
+ | `python.stats()` | Inspect shared-reference and scheduler counters |
110
+ | `await python.finalize()` | Drain accepted native calls and close the runtime |
111
+
112
+ Exports also include `PythonError`, `Tuple`, `kwargs`, `byReference` and
113
+ `cancellable`. Types and generics describe the dynamic API; they do not validate
114
+ Python types at runtime.
115
+
116
+ **Calls are asynchronous; live access is synchronous.** Python functions, methods,
117
+ classes and builtins return Promises, including `await new cls(...)`.
118
+ Calls, imports, `exec` and `eval` execute in order on one native thread (a
119
+ node-ctypes `Executor`) without occupying a waiting libuv worker. Arguments and
120
+ results are converted on Node.js, so thousands of concurrent calls (e.g.
121
+ `Promise.all` over an array) hold Node.js while they are submitted and while
122
+ their results are converted: pass the data to one Python call instead, or host
123
+ Python in a worker (`examples/worker.ts`). Attributes, indices, assignment, enumeration, ordinary iteration, conversion and
124
+ disposal remain synchronous and can block Node.js. Native initialization and
125
+ finalization also run synchronously on the hosting Node.js thread.
126
+
127
+ Python coroutine results are automatically awaited through a separate asyncio
128
+ thread. Async iterators work in both directions. An async JavaScript callback
129
+ must be awaited from Python; a synchronous Python callback cannot return a
130
+ JavaScript Promise. `cancellable(fn)` adds an `AbortSignal` to callbacks that
131
+ cooperate with Python cancellation.
132
+
133
+ `python.run(operation, { signal })` accepts the Promise of a call, `exec`,
134
+ `eval` or `import`, or a Python awaitable, and rejects with `signal.reason`
135
+ on abort (`AbortSignal.timeout(ms)` for time limits). A queued operation is
136
+ skipped; running Python code receives one `KeyboardInterrupt`, so `finally`
137
+ blocks run and `except Exception` does not swallow it. On CPython 3.12 only,
138
+ a one-line loop that starts a `try` block (`try:` followed by `while True: ...`)
139
+ skips that `finally` when interrupted; put the loop body on its own line.
140
+ Native calls are
141
+ interrupted only when they return; asyncio work is cancelled. Synchronous proxy
142
+ access and JavaScript work cannot be aborted.
143
+
144
+ ### Values, memory and lifetime
145
+
146
+ - Scalars convert naturally; Python integers outside JavaScript's safe range
147
+ become bigints. Arrays, `Tuple`, objects/Maps and Sets copy to Python containers.
148
+ Dates become UTC datetimes; Temporal conversions require runtime support.
149
+ - Other Python objects remain live proxies. `eval()` and `proxy.toJS()` perform
150
+ deep conversion; ordinary call results use shallow conversion. Circular copies
151
+ are rejected; use live proxies or `byReference()` instead.
152
+ - Arbitrary JavaScript instances remain shared references. `byReference(value)`
153
+ also shares ordinary containers. Python attributes take precedence over dict keys.
154
+ - Buffer/Uint8Array values copy to Python bytes; other typed arrays, ArrayBuffers
155
+ and DataViews expose shared memoryviews. `byReference(buffer)` shares writable
156
+ memory. `proxy.toTypedArray()` requires a C-contiguous Python buffer and copies
157
+ read-only buffers. Do not detach, transfer or resize shared backing memory.
158
+ - Release owned proxies with `[Symbol.dispose]()` when practical, including
159
+ `PythonError.exception`. GC is nondeterministic. Disposal drops the reference
160
+ immediately; on free-threaded builds CPython may run the object's destructor
161
+ later, when the thread that created it next runs Python code. `PythonError` exposes `type`,
162
+ `traceback`, `exception` and, when available, the original JavaScript `cause`.
163
+
164
+ Only one JavaScript thread per process may host Python. A Node.js worker can
165
+ isolate synchronous access and conversions, but must finalize before terminating.
166
+ Wait for application work and Python threads before finalization; do not finalize
167
+ inside a Python callback. Repeated finalization is harmless; restart and
168
+ subinterpreters are not supported. Never use Python proxies or Python-backed
169
+ memory afterward.
170
+
171
+ Closing rejects new calls and drains accepted native operations, not every
172
+ pending coroutine: remaining awaits are rejected during teardown. Cleanup also
173
+ runs on normal `beforeExit`; `process.exit()` is not orderly finalization.
174
+ Shutdown can wait for Python threads and has no overall timeout.
175
+ Execute trusted Python code only.
176
+
177
+ ## Examples and tests
178
+
179
+ Run examples directly, for example `node examples/basics.ts`.
180
+ They cover usage in more detail than this overview:
181
+
182
+ | Example | Focus |
183
+ | --------------------------------------------- | --------------------------------------------- |
184
+ | [basics.ts](./examples/basics.ts) | Values, live objects, errors and conversions |
185
+ | [callbacks.ts](./examples/callbacks.ts) | JavaScript callbacks and constructors |
186
+ | [threads.ts](./examples/threads.ts) | Python threads and cross-thread callbacks |
187
+ | [async.ts](./examples/async.ts) | Await, cancellation and async iteration |
188
+ | [module.ts](./examples/module.ts) | JavaScript modules and local Python imports |
189
+ | [worker.ts](./examples/worker.ts) | Hosting Python in a Node.js worker |
190
+ | [cryptography.ts](./examples/cryptography.ts) | Python cryptography integration |
191
+ | [lxml.ts](./examples/lxml.ts) | XML parsing, XPath, XSLT and canonicalization |
192
+
193
+ Optional packages are needed only for the corresponding examples and must be
194
+ installed in the selected interpreter. Set `PYTHON` to that executable if it
195
+ differs from the one found automatically. The suite regression-tests callbacks
196
+ and missing-package diagnostics; other example scenarios are manual.
197
+
198
+ ```sh
199
+ npm run typecheck
200
+ npm test
201
+ npm run test:unit
202
+ npm run test:integration
203
+ npm run test:types
204
+ npm run test:backlog
205
+ npm run test:stress
206
+ ```
207
+
208
+ `npm test` builds and runs the ordinary suite; integration tests require shared
209
+ CPython. Typechecks include sources, examples and test helpers.
210
+ `test:backlog` checks queued ownership, every outcome and shutdown under load.
211
+ `test:stress` adds a 60-second mixed workload; set `NODE_PYTHON_STRESS_SECONDS`
212
+ to change its duration. Both are opt-in, force GC in isolated children and report
213
+ memory/latency diagnostics, not performance or leak-certification guarantees.
214
+ The runtime does not impose application backpressure.
215
+
216
+ Two manual checks run in Electron's main process after `npm run build`
217
+ (`electron <file>`, with `ELECTRON_RUN_AS_NODE` unset):
218
+ [tests/electron/main.mjs](./tests/electron/main.mjs) prints a JSON report of
219
+ calls, a free UI thread during a long call and bursts of calls;
220
+ [tests/electron/ui/main.mjs](./tests/electron/ui/main.mjs) opens a window that
221
+ charts frame times and main-process IPC latency while bursts run in the main
222
+ process or in the renderer (`--auto` runs both, prints the table and quits).
223
+
224
+ The [CI workflow](./.github/workflows/ci.yml) runs `npm test` with Python
225
+ 3.12, 3.13, 3.14, 3.14t and 3.15 on Windows, Linux and macOS. It is discovered only when
226
+ this package is a repository root, not while nested in another repository.
227
+ Pushing a `v<version>` tag that matches `package.json` publishes to npm once the
228
+ whole matrix passes (npm Trusted Publishing; versions with a `-` go to `next`).
229
+ For implementation diagrams and ownership invariants, see [FLOWS.md](./FLOWS.md)
230
+ (Italian).
@@ -5,11 +5,21 @@ export declare function nextCompletionToken(previous: number, pending: ReadonlyM
5
5
  export interface Cancellable {
6
6
  cancel?: () => void;
7
7
  }
8
- /** Python owns execution; completion notifications do not occupy libuv workers. */
8
+ /** A request's result (new reference), or the exception it raised (new reference). */
9
+ export type Outcome = {
10
+ readonly value: bigint;
11
+ } | {
12
+ readonly error: bigint;
13
+ };
14
+ /**
15
+ * Python requests run in order on a node-ctypes Executor thread (no libuv
16
+ * worker waits for them). Each request is a call of a Python ctypes callback
17
+ * on that thread; the thread keeps one Python thread state from start to close.
18
+ */
9
19
  export declare class PythonExecutor {
10
20
  #private;
11
- constructor(api: PythonLibrary, check: (ptr: Pointer) => bigint, withGIL: <T>(fn: () => T) => T, consume: (outcome: Pointer) => Pointer);
12
- callAsync(request: Pointer, control?: Cancellable): Promise<Pointer>;
21
+ constructor(api: PythonLibrary, check: (ptr: Pointer) => bigint, withGIL: <T>(fn: () => T) => T);
22
+ callAsync(request: Pointer, control?: Cancellable): Promise<Outcome>;
13
23
  close(): Promise<void>;
14
24
  abandon(): void;
15
25
  }