Skip to content

Commit 2424f00

Browse files
committed
Add convenience wrappers to py_context API
- new/1: Create context with options map (mode => auto|subinterp|worker|owngil) - destroy/1: Alias for stop/1 for API consistency - call/4: Wrapper for call/5 with empty kwargs - eval/2: Wrapper for eval/3 with empty locals
1 parent 34d69b8 commit 2424f00

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

src/py_context.erl

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,14 @@
3535

3636
-export([
3737
start_link/2,
38+
new/1,
3839
stop/1,
40+
destroy/1,
41+
call/4,
3942
call/5,
4043
call/6,
4144
call/7,
45+
eval/2,
4246
eval/3,
4347
eval/4,
4448
eval/5,
@@ -121,6 +125,38 @@ stop(Ctx) when is_pid(Ctx) ->
121125
ok
122126
end.
123127

128+
%% @doc Create a new context with options map.
129+
%%
130+
%% Options:
131+
%% - `mode' - Context mode (auto | subinterp | worker | owngil), default: auto
132+
%%
133+
%% @param Opts Options map
134+
%% @returns {ok, Pid} | {error, Reason}
135+
-spec new(map()) -> {ok, context()} | {error, term()}.
136+
new(Opts) when is_map(Opts) ->
137+
Mode = maps:get(mode, Opts, auto),
138+
Id = erlang:unique_integer([positive]),
139+
start_link(Id, Mode).
140+
141+
%% @doc Alias for stop/1 for API consistency.
142+
-spec destroy(context()) -> ok.
143+
destroy(Ctx) ->
144+
stop(Ctx).
145+
146+
%% @doc Call a Python function with empty kwargs.
147+
%%
148+
%% This is a convenience wrapper for call/5 that defaults Kwargs to #{}.
149+
%%
150+
%% @param Ctx Context process
151+
%% @param Module Python module name
152+
%% @param Func Function name
153+
%% @param Args List of arguments
154+
%% @returns {ok, Result} | {error, Reason}
155+
-spec call(context(), atom() | binary(), atom() | binary(), list()) ->
156+
{ok, term()} | {error, term()}.
157+
call(Ctx, Module, Func, Args) ->
158+
call(Ctx, Module, Func, Args, #{}).
159+
124160
%% @doc Call a Python function.
125161
%%
126162
%% @param Ctx Context process
@@ -181,6 +217,18 @@ call(Ctx, Module, Func, Args, Kwargs, Timeout, EnvRef) when is_pid(Ctx), is_refe
181217
{error, timeout}
182218
end.
183219

220+
%% @doc Evaluate a Python expression with empty locals.
221+
%%
222+
%% This is a convenience wrapper for eval/3 that defaults Locals to #{}.
223+
%%
224+
%% @param Ctx Context process
225+
%% @param Code Python code to evaluate
226+
%% @returns {ok, Result} | {error, Reason}
227+
-spec eval(context(), binary() | string()) ->
228+
{ok, term()} | {error, term()}.
229+
eval(Ctx, Code) ->
230+
eval(Ctx, Code, #{}).
231+
184232
%% @doc Evaluate a Python expression.
185233
%%
186234
%% @param Ctx Context process

0 commit comments

Comments
 (0)