Repository navigation
Expand file tree
/
Copy pathpy.erl
More file actions
1659 lines (1519 loc) · 61.9 KB
/
Copy pathpy.erl
File metadata and controls
1659 lines (1519 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%% Copyright 2026 Benoit Chesneau
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%% @doc High-level API for executing Python code from Erlang.
%%%
%%% This module provides a simple interface to call Python functions,
%%% execute Python code, and stream results from Python generators.
%%%
%%% == Examples ==
%%%
%%% ```
%%% %% Call a Python function
%%% {ok, Result} = py:call(json, dumps, [#{foo => bar}]).
%%%
%%% %% Call with keyword arguments
%%% {ok, Result} = py:call(json, dumps, [Data], #{indent => 2}).
%%%
%%% %% Execute raw Python code
%%% {ok, Result} = py:eval("1 + 2").
%%%
%%% %% Stream from a generator
%%% {ok, Stream} = py:stream(mymodule, generate_tokens, [Prompt]),
%%% lists:foreach(fun(Token) -> io:format("~s", [Token]) end, Stream).
%%% '''
-module(py).
-export([
call/3,
call/4,
call/5,
cast/3,
cast/4,
cast/5,
spawn_call/3,
spawn_call/4,
spawn_call/5,
await/1,
await/2,
eval/1,
eval/2,
eval/3,
exec/1,
exec/2,
stream/3,
stream/4,
stream_eval/1,
stream_eval/2,
stream_start/3,
stream_start/4,
stream_cancel/1,
version/0,
memory_stats/0,
gc/0,
gc/1,
tracemalloc_start/0,
tracemalloc_start/1,
tracemalloc_stop/0,
register_function/2,
register_function/3,
unregister_function/1,
%% Asyncio integration
async_call/3,
async_call/4,
async_await/1,
async_await/2,
async_gather/1,
async_gather/2,
%% Parallel execution + capability probe
parallel/1,
subinterp_supported/0,
%% Virtual environment
ensure_venv/2,
ensure_venv/3,
activate_venv/1,
%% Process-local Python environment
get_local_env/1,
deactivate_venv/0,
venv_info/0,
%% Execution info
execution_mode/0,
%% Shared state (accessible from Python workers)
state_fetch/1,
state_store/2,
state_remove/1,
state_keys/0,
state_clear/0,
state_incr/1,
state_incr/2,
state_decr/1,
state_decr/2,
%% Module reload
reload/1,
%% Logging and tracing
configure_logging/0,
configure_logging/1,
enable_tracing/0,
disable_tracing/0,
get_traces/0,
clear_traces/0,
%% Process-per-context API (new architecture)
context/0,
context/1,
start_contexts/0,
start_contexts/1,
stop_contexts/0,
contexts_started/0,
%% py_ref API (Python object references with auto-routing)
call_method/3,
getattr/2,
to_term/1,
is_ref/1,
%% File descriptor utilities
dup_fd/1,
%% Pool registration API
register_pool/2,
unregister_pool/1,
%% SharedDict API - process-scoped shared dictionary
shared_dict_new/0,
shared_dict_get/2,
shared_dict_get/3,
shared_dict_set/3,
shared_dict_del/2,
shared_dict_keys/1,
shared_dict_destroy/1
]).
-type py_result() :: {ok, term()} | {error, term()}.
-type py_ref() :: reference().
-type py_module() :: atom() | binary() | string().
-type py_func() :: atom() | binary() | string().
-type py_args() :: [term()].
-type py_kwargs() :: #{atom() | binary() => term()}.
-export_type([py_result/0, py_ref/0]).
%% Default timeout for synchronous calls (30 seconds)
-define(DEFAULT_TIMEOUT, 30000).
%% Process dictionary key for local Python environment
-define(LOCAL_ENV_KEY, py_local_env).
%% @doc Get or create a process-local Python environment for a context.
%%
%% Each Erlang process can have Python environments per interpreter.
%% The environments are stored in the process dictionary keyed by interpreter ID
%% and are automatically freed when the process exits.
%%
%% The environment is created inside the context's interpreter to ensure
%% the correct memory allocator is used. This is critical for subinterpreters
%% where each interpreter has its own memory allocator.
%%
%% @param Ctx Context pid
%% @returns EnvRef - NIF resource reference to the Python environment
-spec get_local_env(pid()) -> reference().
get_local_env(Ctx) when is_pid(Ctx) ->
{ok, InterpId} = py_context:get_interp_id(Ctx),
Envs = case get(?LOCAL_ENV_KEY) of
undefined -> #{};
M when is_map(M) -> M;
%% Handle legacy single-ref format (shouldn't happen but be safe)
_OldRef -> #{}
end,
case maps:get(InterpId, Envs, undefined) of
undefined ->
{ok, Ref} = py_context:create_local_env(Ctx),
put(?LOCAL_ENV_KEY, Envs#{InterpId => Ref}),
Ref;
Ref ->
Ref
end.
%%% ============================================================================
%%% Synchronous API
%%% ============================================================================
%% @doc Call a Python function synchronously.
%%
%% In worker mode, the call uses the process-local Python environment,
%% allowing access to functions defined via py:exec() in the same process.
-spec call(py_module(), py_func(), py_args()) -> py_result().
call(Module, Func, Args) ->
call(Module, Func, Args, #{}).
%% @doc Call a Python function with keyword arguments or on a named pool.
%%
%% This function has multiple signatures:
%% - `call(Ctx, Module, Func, Args)' - Call using a specific context pid
%% - `call(Pool, Module, Func, Args)' - Call using a named pool (default, io, etc.)
%% - `call(Module, Func, Args, Kwargs)' - Call with keyword arguments on default pool
%%
%% In worker mode, calls use the process-local Python environment.
%%
%% @param CtxOrPoolOrModule Context pid, pool name, or Python module
%% @param ModuleOrFunc Python module or function name
%% @param FuncOrArgs Function name or arguments list
%% @param ArgsOrKwargs Arguments list or keyword arguments
-spec call(pid(), py_module(), py_func(), py_args()) -> py_result()
; (py_context_router:pool_name(), py_module(), py_func(), py_args()) -> py_result()
; (py_module(), py_func(), py_args(), py_kwargs()) -> py_result().
call(Ctx, Module, Func, Args) when is_pid(Ctx) ->
EnvRef = get_local_env(Ctx),
py_context:call(Ctx, Module, Func, Args, #{}, infinity, EnvRef);
call(Pool, Module, Func, Args) when is_atom(Pool), is_atom(Func) ->
%% Pool-based call (e.g., py:call(io, math, sqrt, [16]))
call(Pool, Module, Func, Args, #{});
call(Module, Func, Args, Kwargs) ->
call(Module, Func, Args, Kwargs, ?DEFAULT_TIMEOUT).
%% @doc Call a Python function with keyword arguments and optional timeout or pool.
%%
%% This function has multiple signatures:
%% - `call(Ctx, Module, Func, Args, Opts)' - Call using context with options map
%% - `call(Pool, Module, Func, Args, Kwargs)' - Call using named pool with kwargs
%% - `call(Module, Func, Args, Kwargs, Timeout)' - Call on default pool with timeout
%%
%% Timeout is in milliseconds. Use `infinity' for no timeout.
%% Rate limited via ETS-based semaphore to prevent overload.
-spec call(pid(), py_module(), py_func(), py_args(), map()) -> py_result()
; (py_context_router:pool_name(), py_module(), py_func(), py_args(), py_kwargs()) -> py_result()
; (py_module(), py_func(), py_args(), py_kwargs(), timeout()) -> py_result().
call(Ctx, Module, Func, Args, Opts) when is_pid(Ctx), is_map(Opts) ->
Kwargs = maps:get(kwargs, Opts, #{}),
Timeout = maps:get(timeout, Opts, infinity),
EnvRef = get_local_env(Ctx),
py_context:call(Ctx, Module, Func, Args, Kwargs, Timeout, EnvRef);
call(Pool, Module, Func, Args, Kwargs) when is_atom(Pool), is_atom(Func), is_map(Kwargs) ->
%% Pool-based call with kwargs (e.g., py:call(io, math, pow, [2, 3], #{round => true}))
do_pool_call(Pool, Module, Func, Args, Kwargs, ?DEFAULT_TIMEOUT);
call(Module, Func, Args, Kwargs, Timeout) ->
%% Look up which pool to use based on registered module/function
Pool = py_context_router:lookup_pool(Module, Func),
do_pool_call(Pool, Module, Func, Args, Kwargs, Timeout).
%% @private
%% Call using a named pool with semaphore protection
%% Uses the process-local environment from the calling process
do_pool_call(Pool, Module, Func, Args, Kwargs, Timeout) ->
case py_semaphore:acquire(Timeout) of
ok ->
try
Ctx = py_context_router:get_context(Pool),
EnvRef = get_local_env(Ctx),
py_context:call(Ctx, Module, Func, Args, Kwargs, Timeout, EnvRef)
after
py_semaphore:release()
end;
{error, max_concurrent} ->
{error, {overloaded, py_semaphore:current(), py_semaphore:max_concurrent()}}
end.
%% @doc Evaluate a Python expression and return the result.
%%
%% In worker mode, evaluation uses the process-local Python environment.
%% Variables defined via exec are visible in eval within the same process.
-spec eval(string() | binary()) -> py_result().
eval(Code) ->
eval(Code, #{}).
%% @doc Evaluate a Python expression with local variables.
%%
%% When the first argument is a pid (context), evaluates using the new
%% process-per-context architecture with process-local environment.
-spec eval(pid(), string() | binary()) -> py_result()
; (string() | binary(), map()) -> py_result().
eval(Ctx, Code) when is_pid(Ctx) ->
EnvRef = get_local_env(Ctx),
py_context:eval(Ctx, Code, #{}, infinity, EnvRef);
eval(Code, Locals) ->
eval(Code, Locals, ?DEFAULT_TIMEOUT).
%% @doc Evaluate a Python expression with local variables and timeout.
%%
%% When the first argument is a pid (context), evaluates using the new
%% process-per-context architecture with process-local environment.
%%
%% Timeout is in milliseconds. Use `infinity' for no timeout.
-spec eval(pid(), string() | binary(), map()) -> py_result()
; (string() | binary(), map(), timeout()) -> py_result().
eval(Ctx, Code, Locals) when is_pid(Ctx), is_map(Locals) ->
EnvRef = get_local_env(Ctx),
py_context:eval(Ctx, Code, Locals, infinity, EnvRef);
eval(Code, Locals, Timeout) ->
%% Always route through context process - it handles callbacks inline using
%% suspension-based approach (no separate callback handler, no blocking)
Ctx = py_context_router:get_context(),
EnvRef = get_local_env(Ctx),
py_context:eval(Ctx, Code, Locals, Timeout, EnvRef).
%% @doc Execute Python statements (no return value expected).
%%
%% In worker mode, the code runs in a process-local Python environment.
%% Variables defined via exec persist within the calling Erlang process.
%% In owngil mode, each context has its own isolated namespace.
-spec exec(string() | binary()) -> ok | {error, term()}.
exec(Code) ->
%% Always route through context process - it handles callbacks inline using
%% suspension-based approach (no separate callback handler, no blocking)
Ctx = py_context_router:get_context(),
EnvRef = get_local_env(Ctx),
py_context:exec(Ctx, Code, EnvRef).
%% @doc Execute Python statements using a specific context.
%%
%% This is the explicit context variant of exec/1.
%% Uses the process-local environment for the calling process.
-spec exec(pid(), string() | binary()) -> ok | {error, term()}.
exec(Ctx, Code) when is_pid(Ctx) ->
EnvRef = get_local_env(Ctx),
py_context:exec(Ctx, Code, EnvRef).
%%% ============================================================================
%%% Asynchronous API
%%% ============================================================================
%% @doc Fire-and-forget Python function call.
-spec cast(py_module(), py_func(), py_args()) -> ok.
cast(Module, Func, Args) ->
cast(Module, Func, Args, #{}).
%% @doc Fire-and-forget Python function call with context or kwargs.
-spec cast(pid(), py_module(), py_func(), py_args()) -> ok;
(py_module(), py_func(), py_args(), py_kwargs()) -> ok.
cast(Ctx, Module, Func, Args) when is_pid(Ctx) ->
cast(Ctx, Module, Func, Args, #{});
cast(Module, Func, Args, Kwargs) ->
spawn(fun() ->
Ctx = py_context_router:get_context(),
_ = py_context:call(Ctx, Module, Func, Args, Kwargs)
end),
ok.
%% @doc Fire-and-forget Python function call with context and kwargs.
-spec cast(pid(), py_module(), py_func(), py_args(), py_kwargs()) -> ok.
cast(Ctx, Module, Func, Args, Kwargs) when is_pid(Ctx) ->
spawn(fun() ->
_ = py_context:call(Ctx, Module, Func, Args, Kwargs)
end),
ok.
%% @doc Spawn a Python function call, returns immediately with a ref.
-spec spawn_call(py_module(), py_func(), py_args()) -> py_ref().
spawn_call(Module, Func, Args) ->
spawn_call(Module, Func, Args, #{}).
%% @doc Spawn a Python function call with context or kwargs.
-spec spawn_call(pid(), py_module(), py_func(), py_args()) -> py_ref();
(py_module(), py_func(), py_args(), py_kwargs()) -> py_ref().
spawn_call(Ctx, Module, Func, Args) when is_pid(Ctx) ->
spawn_call(Ctx, Module, Func, Args, #{});
spawn_call(Module, Func, Args, Kwargs) ->
Ref = make_ref(),
Parent = self(),
spawn(fun() ->
Ctx = py_context_router:get_context(),
Result = py_context:call(Ctx, Module, Func, Args, Kwargs),
Parent ! {py_response, Ref, Result}
end),
Ref.
%% @doc Spawn a Python function call with context and kwargs.
-spec spawn_call(pid(), py_module(), py_func(), py_args(), py_kwargs()) -> py_ref().
spawn_call(Ctx, Module, Func, Args, Kwargs) when is_pid(Ctx) ->
Ref = make_ref(),
Parent = self(),
spawn(fun() ->
Result = py_context:call(Ctx, Module, Func, Args, Kwargs),
Parent ! {py_response, Ref, Result}
end),
Ref.
%% @doc Wait for an async call to complete.
-spec await(py_ref()) -> py_result().
await(Ref) ->
await(Ref, ?DEFAULT_TIMEOUT).
%% @doc Wait for an async call with timeout.
-spec await(py_ref(), timeout()) -> py_result().
await(Ref, Timeout) ->
receive
{py_response, Ref, Result} -> Result;
{py_error, Ref, Error} -> {error, Error}
after Timeout ->
{error, timeout}
end.
%%% ============================================================================
%%% Streaming API
%%% ============================================================================
%% @doc Stream results from a Python generator.
%% Returns a list of all yielded values.
-spec stream(py_module(), py_func(), py_args()) -> py_result().
stream(Module, Func, Args) ->
stream(Module, Func, Args, #{}).
%% @doc Stream results from a Python generator with kwargs.
-spec stream(py_module(), py_func(), py_args(), py_kwargs()) -> py_result().
stream(Module, Func, Args, Kwargs) when map_size(Kwargs) == 0 ->
%% No kwargs - use stream_start and collect results
{ok, Ref} = stream_start(Module, Func, Args),
collect_stream(Ref, []);
stream(Module, Func, Args, Kwargs) ->
%% With kwargs - use eval approach
Ctx = py_context_router:get_context(),
ModuleBin = valid_py_module(ensure_binary(Module)),
FuncBin = valid_py_ident(ensure_binary(Func)),
KwargsCode = format_kwargs(Kwargs),
ArgsCode = format_args(Args),
Code = iolist_to_binary([
<<"list(__import__('">>, ModuleBin, <<"').">>, FuncBin,
<<"(">>, ArgsCode, KwargsCode, <<"))">>
]),
py_context:eval(Ctx, Code, #{}).
%% @private Collect all stream events into a list
collect_stream(Ref, Acc) ->
receive
{py_stream, Ref, {data, Value}} ->
collect_stream(Ref, [Value | Acc]);
{py_stream, Ref, done} ->
{ok, lists:reverse(Acc)};
{py_stream, Ref, {error, Reason}} ->
{error, Reason}
after 30000 ->
{error, timeout}
end.
%% @private Format arguments for Python code
format_args([]) -> <<>>;
format_args(Args) ->
ArgStrs = [format_arg(A) || A <- Args],
iolist_to_binary(lists:join(<<", ">>, ArgStrs)).
%% @private Format a single argument
format_arg(A) when is_integer(A) -> integer_to_binary(A);
format_arg(A) when is_float(A) -> float_to_binary(A);
format_arg(A) when is_binary(A) -> <<"'", (escape_py_literal(A))/binary, "'">>;
format_arg(A) when is_atom(A) -> <<"'", (escape_py_literal(atom_to_binary(A)))/binary, "'">>;
format_arg(A) when is_list(A) -> iolist_to_binary([<<"[">>, format_args(A), <<"]">>]);
format_arg(_) -> <<"None">>.
%% @private Format kwargs for Python code
format_kwargs(Kwargs) when map_size(Kwargs) == 0 -> <<>>;
format_kwargs(Kwargs) ->
KwList = maps:fold(fun(K, V, Acc) ->
KB = valid_py_ident(if is_atom(K) -> atom_to_binary(K); is_binary(K) -> K end),
[<<KB/binary, "=", (format_arg(V))/binary>> | Acc]
end, [], Kwargs),
iolist_to_binary([<<", ">>, lists:join(<<", ">>, KwList)]).
%% @doc Stream results from a Python generator expression.
%% Evaluates the expression and if it returns a generator, streams all values.
-spec stream_eval(string() | binary()) -> py_result().
stream_eval(Code) ->
stream_eval(Code, #{}).
%% @doc Stream results from a Python generator expression with local variables.
-spec stream_eval(string() | binary(), map()) -> py_result().
stream_eval(Code, Locals) ->
%% Route through the new process-per-context system
%% Wrap the code in list() to collect generator values
Ctx = py_context_router:get_context(),
CodeBin = ensure_binary(Code),
WrappedCode = <<"list(", CodeBin/binary, ")">>,
py_context:eval(Ctx, WrappedCode, Locals).
%%% ============================================================================
%%% True Streaming API (Event-driven)
%%% ============================================================================
%% @doc Start a true streaming iteration from a Python generator.
%%
%% Unlike stream/3,4 which collects all values at once, this function
%% returns immediately with a reference and sends values as events
%% to the calling process as they are yielded.
%%
%% Events sent to the owner process:
%% - `{py_stream, Ref, {data, Value}}' - Each yielded value
%% - `{py_stream, Ref, done}' - Stream completed
%% - `{py_stream, Ref, {error, Reason}}' - Stream error
%%
%% Supports both sync generators and async generators (coroutines).
%%
%% Example:
%% ```
%% {ok, Ref} = py:stream_start(builtins, iter, [[1,2,3,4,5]]),
%% receive_loop(Ref).
%%
%% receive_loop(Ref) ->
%% receive
%% {py_stream, Ref, {data, Value}} ->
%% io:format("Got: ~p~n", [Value]),
%% receive_loop(Ref);
%% {py_stream, Ref, done} ->
%% io:format("Complete~n");
%% {py_stream, Ref, {error, Reason}} ->
%% io:format("Error: ~p~n", [Reason])
%% after 30000 ->
%% timeout
%% end.
%% '''
-spec stream_start(py_module(), py_func(), py_args()) -> {ok, reference()}.
stream_start(Module, Func, Args) ->
stream_start(Module, Func, Args, #{}).
%% @doc Start a true streaming iteration with options.
%%
%% Options:
%% - `owner => pid()' - Process to receive events (default: self())
%%
%% @param Module Python module name
%% @param Func Python function name
%% @param Args Function arguments
%% @param Opts Options map
%% @returns {ok, Ref} where Ref is used to identify stream events
-spec stream_start(py_module(), py_func(), py_args(), map()) -> {ok, reference()}.
stream_start(Module, Func, Args, Opts) ->
Owner = maps:get(owner, Opts, self()),
Ref = make_ref(),
ModuleBin = ensure_binary(Module),
FuncBin = ensure_binary(Func),
RefHash = erlang:phash2(Ref),
%% Store owner and ref for Python to retrieve
%% Use binary keys because Python strings become binaries
py_state:store({<<"stream_owner">>, RefHash}, Owner),
py_state:store({<<"stream_ref">>, RefHash}, Ref),
py_state:store({<<"stream_args">>, RefHash}, Args),
%% Spawn an Erlang process to run the streaming iteration
spawn(fun() ->
stream_run_python(ModuleBin, FuncBin, RefHash)
end),
{ok, Ref}.
%% @private Run the streaming via Python code
stream_run_python(ModuleBin0, FuncBin0, RefHash) ->
ModuleBin = valid_py_module(ModuleBin0),
FuncBin = valid_py_ident(FuncBin0),
RefHashBin = integer_to_binary(RefHash),
%% Build Python code that streams values using callbacks
Code = iolist_to_binary([
<<"import erlang\n">>,
<<"_rh = ">>, RefHashBin, <<"\n">>,
<<"_args = erlang.call('state_get', ('stream_args', _rh))\n">>,
<<"if _args is None:\n">>,
<<" _args = []\n">>,
<<"try:\n">>,
<<" _mod = __import__('">>, ModuleBin, <<"')\n">>,
<<" _fn = getattr(_mod, '">>, FuncBin, <<"')\n">>,
<<" _gen = _fn(*_args) if _args else _fn()\n">>,
<<" for _val in _gen:\n">>,
<<" if erlang.call('_py_stream_cancelled', _rh):\n">>,
<<" erlang.call('_py_stream_send', _rh, 'error', 'cancelled')\n">>,
<<" break\n">>,
<<" erlang.call('_py_stream_send', _rh, 'data', _val)\n">>,
<<" else:\n">>,
<<" erlang.call('_py_stream_send', _rh, 'done', None)\n">>,
<<"except Exception as _e:\n">>,
<<" erlang.call('_py_stream_send', _rh, 'error', str(_e))\n">>,
<<"finally:\n">>,
<<" erlang.call('_py_stream_cleanup', _rh)\n">>
]),
%% Execute the streaming code
case exec(Code) of
ok -> ok;
{error, Reason} ->
%% Try to notify owner of error
case py_state:fetch({<<"stream_owner">>, RefHash}) of
{ok, Owner} ->
case py_state:fetch({<<"stream_ref">>, RefHash}) of
{ok, Ref} ->
Owner ! {py_stream, Ref, {error, Reason}},
py_state:remove({<<"stream_owner">>, RefHash}),
py_state:remove({<<"stream_ref">>, RefHash}),
py_state:remove({<<"stream_args">>, RefHash});
_ -> ok
end;
_ -> ok
end
end.
%% @doc Cancel an active stream.
%%
%% Sends a cancellation signal to stop the stream iteration.
%% Any pending values may still be delivered before the stream stops.
%%
%% @param Ref The stream reference from stream_start/3,4
%% @returns ok
-spec stream_cancel(reference()) -> ok.
stream_cancel(Ref) when is_reference(Ref) ->
%% Store cancellation flag that the streaming task checks
%% Use hash because we can't pass Erlang refs to Python callbacks easily
%% Use binary key because Python strings become binaries
RefHash = erlang:phash2(Ref),
py_state:store({<<"stream_cancelled_hash">>, RefHash}, true),
ok.
%%% ============================================================================
%%% Info
%%% ============================================================================
%% @doc Get Python version string.
-spec version() -> {ok, binary()} | {error, term()}.
version() ->
py_nif:version().
%%% ============================================================================
%%% Memory and GC
%%% ============================================================================
%% @doc Get Python memory statistics.
%% Returns a map containing:
%% - gc_stats: List of per-generation GC statistics
%% - gc_count: Tuple of object counts per generation
%% - gc_threshold: Collection thresholds per generation
%% - traced_memory_current: Current traced memory (if tracemalloc enabled)
%% - traced_memory_peak: Peak traced memory (if tracemalloc enabled)
-spec memory_stats() -> {ok, map()} | {error, term()}.
memory_stats() ->
py_nif:memory_stats().
%% @doc Force Python garbage collection.
%% Performs a full collection (all generations).
%% Returns the number of unreachable objects collected.
-spec gc() -> {ok, integer()} | {error, term()}.
gc() ->
py_nif:gc().
%% @doc Force garbage collection of a specific generation.
%% Generation 0 collects only the youngest objects.
%% Generation 1 collects generations 0 and 1.
%% Generation 2 (default) performs a full collection.
-spec gc(0..2) -> {ok, integer()} | {error, term()}.
gc(Generation) when Generation >= 0, Generation =< 2 ->
py_nif:gc(Generation).
%% @doc Start memory allocation tracing.
%% After starting, memory_stats() will include traced_memory_current
%% and traced_memory_peak values.
-spec tracemalloc_start() -> ok | {error, term()}.
tracemalloc_start() ->
py_nif:tracemalloc_start().
%% @doc Start memory tracing with specified frame depth.
%% Higher frame counts provide more detailed tracebacks but use more memory.
-spec tracemalloc_start(pos_integer()) -> ok | {error, term()}.
tracemalloc_start(NFrame) when is_integer(NFrame), NFrame > 0 ->
py_nif:tracemalloc_start(NFrame).
%% @doc Stop memory allocation tracing.
-spec tracemalloc_stop() -> ok | {error, term()}.
tracemalloc_stop() ->
py_nif:tracemalloc_stop().
%%% ============================================================================
%%% Erlang Function Registration
%%% ============================================================================
%% @doc Register an Erlang function to be callable from Python.
%% Python code can then call: erlang.call('name', arg1, arg2, ...)
%% The function should accept a list of arguments and return a term.
-spec register_function(Name :: atom() | binary(), Fun :: fun((list()) -> term())) -> ok.
register_function(Name, Fun) when is_function(Fun, 1) ->
py_callback:register(Name, Fun).
%% @doc Register an Erlang module:function to be callable from Python.
%% The function will be called as Module:Function(Args).
-spec register_function(Name :: atom() | binary(), Module :: atom(), Function :: atom()) -> ok.
register_function(Name, Module, Function) when is_atom(Module), is_atom(Function) ->
py_callback:register(Name, {Module, Function}).
%% @doc Unregister a previously registered function.
-spec unregister_function(Name :: atom() | binary()) -> ok.
unregister_function(Name) ->
py_callback:unregister(Name).
%%% ============================================================================
%%% Asyncio Integration
%%% ============================================================================
%% @doc Call a Python async function (coroutine).
%% Returns immediately with a reference. Use async_await/1,2 to get the result.
%% This is for calling functions defined with `async def' in Python.
%%
%% Example:
%% ```
%% Ref = py:async_call(aiohttp, get, [<<"https://example.com">>]),
%% {ok, Response} = py:async_await(Ref).
%% '''
-spec async_call(py_module(), py_func(), py_args()) -> py_ref().
async_call(Module, Func, Args) ->
async_call(Module, Func, Args, #{}).
%% @doc Call a Python async function with keyword arguments.
-spec async_call(py_module(), py_func(), py_args(), py_kwargs()) -> py_ref().
async_call(Module, Func, Args, Kwargs) ->
py_event_loop:create_task(Module, Func, Args, Kwargs).
%% @doc Wait for an async call to complete.
-spec async_await(py_ref()) -> py_result().
async_await(Ref) ->
async_await(Ref, ?DEFAULT_TIMEOUT).
%% @doc Wait for an async call with timeout.
-spec async_await(py_ref(), timeout()) -> py_result().
async_await(Ref, Timeout) ->
py_event_loop:await(Ref, Timeout).
%% @doc Execute multiple async Python calls concurrently.
%%
%% Each call is submitted to the event loop independently, so they run
%% concurrently. Results are collected in the order of the input list.
%% Sync functions are accepted and resolve immediately (the event loop
%% short-circuits non-coroutines).
%%
%% Returns `{ok, [Result1, Result2, ...]}' when every call succeeds, where
%% each `ResultN' is the value returned by the corresponding call.
%% Returns `{error, {gather_failed, Errors}}' if any call fails, where
%% `Errors' is a list of `{Index, Reason}' tuples for each failure.
%%
%% Example:
%% ```
%% {ok, [R1, R2, R3]} = py:async_gather([
%% {aiohttp, get, [Url1]},
%% {aiohttp, get, [Url2]},
%% {aiohttp, get, [Url3]}
%% ]).
%% '''
-spec async_gather([{py_module(), py_func(), py_args()}]) -> py_result().
async_gather(Calls) ->
async_gather(Calls, ?DEFAULT_TIMEOUT).
%% @doc Like async_gather/1 with explicit per-call timeout.
-spec async_gather([{py_module(), py_func(), py_args()}], timeout()) -> py_result().
async_gather(Calls, Timeout) when is_list(Calls) ->
Refs = [async_call(M, F, A) || {M, F, A} <- Calls],
Results = [async_await(R, Timeout) || R <- Refs],
Errors = [{Idx, Reason}
|| {Idx, {error, Reason}} <- lists:zip(lists:seq(1, length(Results)), Results)],
case Errors of
[] ->
Values = [V || {ok, V} <- Results],
{ok, Values};
_ ->
{error, {gather_failed, Errors}}
end.
%%% ============================================================================
%%% Parallel Execution (Python 3.12+ Sub-interpreters)
%%% ============================================================================
%% @doc Check if true parallel execution is supported.
%% Returns true on Python 3.12+ which supports per-interpreter GIL.
-spec subinterp_supported() -> boolean().
subinterp_supported() ->
py_nif:subinterp_supported().
%% @doc Execute multiple Python calls in true parallel using sub-interpreters.
%% Each call runs in its own sub-interpreter with its own GIL, allowing
%% CPU-bound Python code to run in parallel.
%%
%% Requires Python 3.12+. Use subinterp_supported/0 to check availability.
%%
%% Example:
%% ```
%% %% Run numpy matrix operations in parallel
%% {ok, Results} = py:parallel([
%% {numpy, dot, [MatrixA, MatrixB]},
%% {numpy, dot, [MatrixC, MatrixD]},
%% {numpy, dot, [MatrixE, MatrixF]}
%% ]).
%% '''
%%
%% On older Python versions, returns {error, subinterpreters_not_supported}.
-spec parallel([{py_module(), py_func(), py_args()}]) -> py_result().
parallel(Calls) when is_list(Calls) ->
%% Distribute calls across available contexts for true parallel execution
NumContexts = py_context_router:num_contexts(),
Parent = self(),
Ref = make_ref(),
%% Spawn processes to execute calls in parallel
CallsWithIdx = lists:zip(lists:seq(1, length(Calls)), Calls),
_ = [spawn(fun() ->
%% Distribute calls round-robin across contexts
CtxIdx = ((Idx - 1) rem NumContexts) + 1,
Ctx = py_context_router:get_context(CtxIdx),
Result = py_context:call(Ctx, M, F, A, #{}),
Parent ! {Ref, Idx, Result}
end) || {Idx, {M, F, A}} <- CallsWithIdx],
%% Collect results in order
Results = [receive
{Ref, Idx, Result} -> {Idx, Result}
after ?DEFAULT_TIMEOUT ->
{Idx, {error, timeout}}
end || {Idx, _} <- CallsWithIdx],
%% Sort by index and extract results
SortedResults = [R || {_, R} <- lists:keysort(1, Results)],
%% Check if all succeeded
case lists:all(fun({ok, _}) -> true; (_) -> false end, SortedResults) of
true ->
{ok, [V || {ok, V} <- SortedResults]};
false ->
%% Return first error or all results
case lists:keyfind(error, 1, SortedResults) of
{error, _} = Err -> Err;
false -> {ok, SortedResults}
end
end.
%%% ============================================================================
%%% Virtual Environment Support
%%% ============================================================================
%% @doc Ensure a virtual environment exists and activate it.
%%
%% Creates a venv at `Path' if it doesn't exist, installs dependencies from
%% `RequirementsFile', and activates the venv.
%%
%% RequirementsFile can be:
%% - `"requirements.txt"' - standard pip requirements file
%% - `"pyproject.toml"' - PEP 621 project file (installs with -e .)
%%
%% Example:
%% ```
%% ok = py:ensure_venv("priv/venv", "requirements.txt").
%% '''
-spec ensure_venv(string() | binary(), string() | binary()) -> ok | {error, term()}.
ensure_venv(Path, RequirementsFile) ->
ensure_venv(Path, RequirementsFile, []).
%% @doc Ensure a virtual environment exists with options.
%%
%% Options:
%% - `{extras, [string()]}' - Install optional dependencies (pyproject.toml)
%% - `{installer, uv | pip}' - Package installer (default: auto-detect)
%% - `{python, string()}' - Python executable for venv creation
%% - `force' - Recreate venv even if it exists
%%
%% Example:
%% ```
%% %% With pyproject.toml and dev extras
%% ok = py:ensure_venv("priv/venv", "pyproject.toml", [
%% {extras, ["dev", "test"]}
%% ]).
%%
%% %% Force uv installer
%% ok = py:ensure_venv("priv/venv", "requirements.txt", [
%% {installer, uv}
%% ]).
%% '''
-spec ensure_venv(string() | binary(), string() | binary(), list()) -> ok | {error, term()}.
ensure_venv(Path, RequirementsFile, Opts) ->
PathStr = to_string(Path),
ReqFileStr = to_string(RequirementsFile),
Force = proplists:get_bool(force, Opts),
%% Create venv if needed
VenvReady = case venv_exists(PathStr) of
true when not Force ->
ok;
_ ->
create_venv(PathStr, Opts)
end,
case VenvReady of
ok ->
%% Always install/update dependencies (pip/uv skip existing)
case install_deps(PathStr, ReqFileStr, Opts) of
ok ->
activate_venv(PathStr);
{error, _} = Err ->
Err
end;
{error, _} = Err ->
Err
end.
%% @private Check if venv exists by looking for pyvenv.cfg
-spec venv_exists(string()) -> boolean().
venv_exists(Path) ->
filelib:is_file(filename:join(Path, "pyvenv.cfg")).
%% @private Create a new virtual environment
-spec create_venv(string(), list()) -> ok | {error, term()}.
create_venv(Path, Opts) ->
Installer = detect_installer(Opts),
Python = case proplists:get_value(python, Opts, undefined) of
undefined -> get_python_executable();
P -> P
end,
case Installer of
uv ->
%% uv venv is faster, use --python to match the running interpreter
run_cmd(uv_exe(), ["venv", "--python", Python, Path], []);
pip ->
run_cmd(Python, ["-m", "venv", Path], [])
end.
%% @private Get the Python executable path
%% When embedded, sys.executable returns the embedding app (beam.smp)
%% so we reconstruct the path from sys.prefix and version info
-spec get_python_executable() -> string().
get_python_executable() ->
%% Use a single expression to find the Python executable
%% Searches for pythonX.Y, python3, python in sys.prefix/bin (Unix)
%% or python.exe in sys.prefix (Windows)
Expr = <<"(lambda: (__import__('os').path.join(__import__('sys').prefix, 'python.exe') if __import__('sys').platform == 'win32' and __import__('os').path.isfile(__import__('os').path.join(__import__('sys').prefix, 'python.exe')) else next((p for p in [__import__('os').path.join(__import__('sys').prefix, 'bin', f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python3'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python')] if __import__('os').path.isfile(p)), 'python3')))()">>,
case eval(Expr) of
{ok, Path} when is_binary(Path) -> binary_to_list(Path);
_ -> "python3"
end.
%% @private Install dependencies from requirements file
-spec install_deps(string(), string(), list()) -> ok | {error, term()}.
install_deps(Path, RequirementsFile, Opts) ->
Installer = detect_installer(Opts),
{Exe, BaseArgs, PortOpts} = pip_command(Path, Installer),
Extras = proplists:get_value(extras, Opts, []),
%% Determine file type and build the install argument list (no shell).
Args = case filename:extension(RequirementsFile) of
".txt" ->
BaseArgs ++ ["install", "-r", RequirementsFile];
".toml" ->
%% pyproject.toml - install as editable.
%% filename:dirname returns "." for files without directory component
InstallPath = filename:dirname(RequirementsFile),
case Extras of
[] ->
BaseArgs ++ ["install", "-e", InstallPath];
_ ->
ExtrasStr = string:join(Extras, ","),
BaseArgs ++ ["install", "-e", InstallPath ++ "[" ++ ExtrasStr ++ "]"]
end;
_ ->
BaseArgs ++ ["install", "-r", RequirementsFile]
end,
run_cmd(Exe, Args, PortOpts).
%% @private Detect which installer to use (uv or pip)
-spec detect_installer(list()) -> uv | pip.
detect_installer(Opts) ->
case proplists:get_value(installer, Opts, auto) of
auto ->
case os:find_executable("uv") of
false -> pip;
_ -> uv
end;
Installer ->
Installer
end.
%% @private Resolve the installer into {Executable, BaseArgs, PortOpts}.
%% For uv the venv is selected via the VIRTUAL_ENV port env option (not a shell
%% prefix); for pip we use the venv's own pip binary.
-spec pip_command(string(), uv | pip) -> {string(), [string()], list()}.
pip_command(VenvPath, uv) ->
{uv_exe(), ["pip"], [{env, [{"VIRTUAL_ENV", VenvPath}]}]};
pip_command(VenvPath, pip) ->
PipExe = case os:type() of
{win32, _} ->
filename:join([VenvPath, "Scripts", "pip"]);
_ ->
filename:join([VenvPath, "bin", "pip"])
end,
{PipExe, [], []}.
%% @private Full path to the uv executable (falls back to the bare name).
-spec uv_exe() -> string().
uv_exe() ->
case os:find_executable("uv") of
false -> "uv";
P -> P
end.
%% @private Run an executable with an argv list (no shell) and return ok or error.
-spec run_cmd(string(), [string()], list()) -> ok | {error, term()}.
run_cmd(Exe, Args, ExtraOpts) ->
case resolve_exe(Exe) of
{error, _} = Err ->
Err;
ExeFull ->
try open_port({spawn_executable, ExeFull},
[exit_status, stderr_to_stdout, binary, {args, Args} | ExtraOpts]) of
Port -> collect_port(Port, [])
catch
error:Reason -> {error, {spawn_failed, Exe, Reason}}
end