Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/erlang_python_app.erl
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
-export([start/2, stop/1]).

start(_StartType, _StartArgs) ->
%% Initialize the import registry ETS tables
py_import:init(),
erlang_python_sup:start_link().

stop(_State) ->
Expand Down
3 changes: 3 additions & 0 deletions src/erlang_python_sup.erl
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ init([]) ->
%% Initialize shared state ETS table (owned by supervisor for resilience)
ok = py_state:init_tab(),

%% Initialize import/path registry and load config (before contexts start)
ok = py_import:init(),

%% Register ALL system callbacks early, before any gen_server starts.
%% This ensures callbacks like _py_sleep and _whereis are available immediately.
ok = py_callback:register_callbacks(),
Expand Down
42 changes: 38 additions & 4 deletions src/py_import.erl
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@
%%% applied to all Python interpreters. Imports and paths are applied
%%% immediately to all running interpreters and stored for new interpreters.
%%%
%%% == Configuration ==
%%%
%%% Imports and paths can be configured in the application environment:
%%%
%%% ```
%%% {erlang_python, [
%%% {imports, [{json, dumps}, {math, sqrt}, {os, getcwd}]},
%%% {paths, ["/path/to/modules"]}
%%% ]}
%%% '''
%%%
%%% == Examples ==
%%%
%%% ```
Expand Down Expand Up @@ -70,28 +81,27 @@
%% @doc Initialize the import and path registry ETS tables.
%%
%% This is called automatically during application startup.
%% Also loads imports and paths from application config.
%% Safe to call multiple times - does nothing if already initialized.
%%
%% @returns ok
-spec init() -> ok.
init() ->
case ets:info(?IMPORT_REGISTRY) of
undefined ->
%% Use bag type to allow multiple entries with same module name
%% e.g., {<<"json">>, all} and {<<"json">>, <<"dumps">>}
ets:new(?IMPORT_REGISTRY, [bag, public, named_table]),
ok;
_ ->
ok
end,
case ets:info(?PATH_REGISTRY) of
undefined ->
%% Use set type - paths are unique, ordered by insertion
ets:new(?PATH_REGISTRY, [ordered_set, public, named_table]),
ok;
_ ->
ok
end.
end,
load_config().

%%% ============================================================================
%%% Module Import Registry
Expand Down Expand Up @@ -353,6 +363,30 @@ is_path_added(Path) ->
ensure_binary(S) ->
py_util:to_binary(S).

%% @private Load imports and paths from application config
load_config() ->
%% Load imports: [{Module, Func}]
Imports = application:get_env(erlang_python, imports, []),
lists:foreach(
fun({Module, Func}) ->
ModuleBin = ensure_binary(Module),
FuncBin = ensure_binary(Func),
ets:insert(?IMPORT_REGISTRY, {ModuleBin, FuncBin})
end,
Imports
),
%% Load paths
Paths = application:get_env(erlang_python, paths, []),
lists:foreach(
fun(Path) ->
PathBin = ensure_binary(Path),
Key = erlang:monotonic_time(),
ets:insert(?PATH_REGISTRY, {Key, PathBin})
end,
Paths
),
ok.

%% @private Apply import to all running interpreters (contexts + event loops)
apply_import_to_interpreters(ModuleBin) ->
Imports = [{ModuleBin, all}],
Expand Down
62 changes: 60 additions & 2 deletions test/py_import_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@
add_path_test/1,
%% Immediate application tests
import_applies_to_running_interpreter_test/1,
path_applies_to_running_interpreter_test/1
path_applies_to_running_interpreter_test/1,
%% Config initialization tests
init_from_config_test/1
]).

all() ->
Expand Down Expand Up @@ -82,7 +84,9 @@ groups() ->
add_path_test,
%% Immediate application tests
import_applies_to_running_interpreter_test,
path_applies_to_running_interpreter_test
path_applies_to_running_interpreter_test,
%% Config initialization tests
init_from_config_test
]}].

init_per_suite(Config) ->
Expand Down Expand Up @@ -845,3 +849,57 @@ path_applies_to_running_interpreter_test(Config) ->
ok = py_import:clear_paths(),

ct:pal("add_path applies immediately to running interpreter").

%% ============================================================================
%% Config Initialization Tests
%% ============================================================================

%% @doc Test that imports and paths are loaded from application config
init_from_config_test(Config) ->
%% Clear existing state
ok = py_import:clear_imports(),
ok = py_import:clear_paths(),

%% Create test module in priv_dir
PrivDir = ?config(priv_dir, Config),
ModuleDir = filename:join(PrivDir, "config_test"),
ok = filelib:ensure_dir(filename:join(ModuleDir, "dummy")),
ModulePath = filename:join(ModuleDir, "config_test_mod.py"),
ok = file:write_file(ModulePath, <<"CONFIG_VALUE = 123\n">>),

%% Set application config
ok = application:set_env(erlang_python, imports, [{json, dumps}, {base64, b64encode}]),
ok = application:set_env(erlang_python, paths, [ModuleDir]),

%% Re-run init to load config
ok = py_import:init(),

%% Verify imports were loaded in registry
Imports = py_import:all_imports(),
?assert(lists:member({<<"json">>, <<"dumps">>}, Imports)),
?assert(lists:member({<<"base64">>, <<"b64encode">>}, Imports)),

%% Verify paths were loaded in registry
Paths = py_import:all_paths(),
ModuleDirBin = list_to_binary(ModuleDir),
?assert(lists:member(ModuleDirBin, Paths)),

%% Create a new context and verify imports/paths are applied
{ok, Ctx} = py_context:new(#{mode => worker}),

%% Verify json.dumps works (from config imports)
{ok, JsonResult} = py_context:call(Ctx, json, dumps, [[1, 2, 3]], #{}),
?assertEqual(<<"[1, 2, 3]">>, JsonResult),

%% Verify custom module from config path works
{ok, ConfigValue} = py_context:eval(Ctx, <<"__import__('config_test_mod').CONFIG_VALUE">>),
?assertEqual(123, ConfigValue),

%% Clean up
py_context:destroy(Ctx),
ok = application:unset_env(erlang_python, imports),
ok = application:unset_env(erlang_python, paths),
ok = py_import:clear_imports(),
ok = py_import:clear_paths(),

ct:pal("init loads imports and paths from config and applies to new contexts").
Loading