py_preload (erlang_python v3.0.0)

View Source

Python preload code registry.

Allows users to preload Python code that executes during interpreter initialization. The resulting globals become the base namespace that process-local environments inherit from.

Usage

   %% At application startup
   py_preload:set_code(<<"
   import json
   import os
  
   def shared_helper(x):
       return x * 2
  
   CONFIG = {'debug': True}
   ">>).
  
   %% Later, any context will have these preloaded
   {ok, Ctx} = py_context:new(#{mode => worker}),
   {ok, 10} = py:eval(Ctx, <<"shared_helper(5)">>).

Storage

Uses persistent_term for the preload code. Changes only affect newly created contexts; existing contexts are not modified.

Summary

Functions

Apply preload code to a context reference.

Clear the preload code.

Get the current preload code.

Check if preload code is configured.

Set preload code to be executed once per interpreter at init.

Functions

apply_preload(Ref)

-spec apply_preload(reference()) -> ok | {error, term()}.

Apply preload code to a context reference.

Called internally by py_context during context initialization. Executes the preload code in the context's interpreter.

clear_code()

-spec clear_code() -> ok.

Clear the preload code.

New contexts will start with empty globals. Existing contexts are not affected.

get_code()

-spec get_code() -> binary() | undefined.

Get the current preload code.

has_preload()

-spec has_preload() -> boolean().

Check if preload code is configured.

set_code(Code)

-spec set_code(binary() | iolist()) -> ok.

Set preload code to be executed once per interpreter at init.

The code is executed in the interpreter's __main__ namespace. All defined functions, variables, and imports become available in process-local environments.