CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-graalvm-polyglot--python

GraalVM Polyglot API for embedding and executing Python code within Java applications.

Pending
Overview
Eval results
Files

context-management.mddocs/

Context Management

Context management provides the core functionality for creating, configuring, and managing Python execution environments within Java applications. Each context represents an isolated runtime with configurable security policies and resource limits.

Capabilities

Context Creation

Create execution contexts for Python with optional language restrictions and configuration.

/**
 * Creates a new context with the specified permitted languages
 * @param permittedLanguages languages allowed in this context (e.g., "python")
 * @return new Context instance
 */
public static Context create(String... permittedLanguages);

/**
 * Creates a builder for advanced context configuration
 * @param permittedLanguages languages allowed in this context
 * @return Context.Builder for fluent configuration
 */
public static Context newBuilder(String... permittedLanguages);

Usage Examples:

// Simple context creation
Context context = Context.create("python");

// Builder-based creation with configuration
Context context = Context.newBuilder("python")
    .allowHostAccess(HostAccess.EXPLICIT)
    .allowIO(IOAccess.NONE)
    .sandbox(SandboxPolicy.CONSTRAINED)
    .build();

Code Evaluation

Execute Python code within the context and retrieve results.

/**
 * Evaluates source code in the specified language
 * @param languageId the language identifier (use "python" for Python)
 * @param source the source code to evaluate
 * @return Value representing the evaluation result
 * @throws PolyglotException if evaluation fails
 */
public Value eval(String languageId, CharSequence source);

/**
 * Evaluates a Source object
 * @param source the Source object to evaluate
 * @return Value representing the evaluation result
 * @throws PolyglotException if evaluation fails
 */
public Value eval(Source source);

Usage Examples:

// Direct evaluation
Value result = context.eval("python", "2 + 3");
int sum = result.asInt(); // 5

// Multi-line Python code
String pythonCode = """
    def fibonacci(n):
        if n <= 1:
            return n
        return fibonacci(n-1) + fibonacci(n-2)
    
    fibonacci(10)
    """;
Value fibResult = context.eval("python", pythonCode);
int fib10 = fibResult.asInt(); // 55

// Using Source objects
Source source = Source.create("python", "import math; math.pi");
Value pi = context.eval(source);
double piValue = pi.asDouble(); // 3.141592653589793

Bindings Access

Access and manipulate the global namespace of languages within the context.

/**
 * Gets the bindings object for a specific language
 * @param languageId the language identifier
 * @return Value representing the language's global bindings
 */
public Value getBindings(String languageId);

/**
 * Gets the polyglot bindings shared across all languages
 * @return Value representing shared polyglot bindings
 */
public Value getPolyglotBindings();

Usage Examples:

// Access Python globals
context.eval("python", "x = 42; y = 'hello'");
Value pythonBindings = context.getBindings("python");
Value x = pythonBindings.getMember("x");
Value y = pythonBindings.getMember("y");

// Set values in Python namespace
pythonBindings.putMember("z", 100);
Value result = context.eval("python", "x + z"); // 142

// Access built-in functions
Value printFunction = pythonBindings.getMember("print");
printFunction.execute("Hello from Python!");

// Share data between languages via polyglot bindings
Value polyglotBindings = context.getPolyglotBindings();
polyglotBindings.putMember("shared_data", Arrays.asList(1, 2, 3));
context.eval("python", "shared_list = polyglot.import_value('shared_data')");

Language Initialization

Force initialization of languages for performance optimization.

/**
 * Initializes the specified language in this context
 * @param languageId the language to initialize
 */
public void initialize(String languageId);

Usage Examples:

// Pre-initialize Python for faster first evaluation
context.initialize("python");

// Now evaluations will be faster
Value result = context.eval("python", "print('Hello, World!')");

Context Lifecycle

Manage context lifecycle with proper resource cleanup and thread safety.

/**
 * Closes the context and releases all associated resources
 * Waits for any currently executing code to complete
 */
public void close();

/**  
 * Closes the context with optional cancellation of executing code
 * @param cancelIfExecuting if true, cancels any currently executing code
 */
public void close(boolean cancelIfExecuting);

/**
 * Checks if the context has been closed
 * @return true if the context is closed
 */
public boolean isClosed();

Usage Examples:

// Try-with-resources (recommended)
try (Context context = Context.create("python")) {
    Value result = context.eval("python", "2 + 2");
    // Context automatically closed
}

// Manual lifecycle management
Context context = Context.create("python");
try {
    // Use context
    Value result = context.eval("python", "len([1, 2, 3])");
} finally {
    context.close();
}

// Force cancellation of long-running code
context.close(true);

Thread Safety

Manage context access across multiple threads safely.

/**
 * Enters the context for the current thread
 * Must be paired with leave() call
 */
public void enter();

/**
 * Leaves the context for the current thread
 * Must be called after enter()
 */
public void leave();

Usage Examples:

Context context = Context.create("python");

// Thread-safe context access
context.enter();
try {
    Value result = context.eval("python", "import threading; threading.current_thread().name");
    String threadName = result.asString();
} finally {
    context.leave();
}

// Multiple thread access
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
    int taskId = i;
    executor.submit(() -> {
        context.enter();
        try {
            Value result = context.eval("python", "task_id = " + taskId + "; task_id * 2");
            System.out.println("Task " + taskId + " result: " + result.asInt());
        } finally {
            context.leave();
        }
    });
}

Resource Management

Control resource usage and limits within the context.

/**
 * Resets all resource limits to their initial values
 */
public void resetLimits();

/**
 * Triggers a safepoint, allowing for resource limit checks
 * and potential interruption of executing code
 */
public void safepoint();

Usage Examples:

// Context with resource limits
Context context = Context.newBuilder("python")
    .resourceLimits(ResourceLimits.newBuilder()
        .statementLimit(10000, null)
        .timeLimit(Duration.ofSeconds(30))
        .build())
    .build();

try {
    // Long-running operation
    context.eval("python", "sum(range(1000000))");
} catch (PolyglotException e) {
    if (e.isResourceExhausted()) {
        System.out.println("Resource limit exceeded");
        context.resetLimits(); // Reset for next operation
    }
}

Types

/**
 * Builder class for creating configured Context instances
 */
public static final class Context.Builder {
    /**
     * Sets the host access policy for this context
     * @param config HostAccess configuration
     * @return this builder
     */
    public Builder allowHostAccess(HostAccess config);
    
    /**
     * Sets the polyglot access policy for inter-language evaluation
     * @param config PolyglotAccess configuration  
     * @return this builder
     */
    public Builder allowPolyglotAccess(PolyglotAccess config);
    
    /**
     * Sets the I/O access policy for file system operations
     * @param config IOAccess configuration
     * @return this builder
     */
    public Builder allowIO(IOAccess config);
    
    /**
     * Sets the sandbox policy for security level
     * @param policy SandboxPolicy level
     * @return this builder
     */
    public Builder sandbox(SandboxPolicy policy);
    
    /**
     * Sets the current working directory
     * @param workingDirectory path to working directory
     * @return this builder
     */
    public Builder currentWorkingDirectory(Path workingDirectory);
    
    /**
     * Sets an engine option
     * @param key option key
     * @param value option value  
     * @return this builder
     */
    public Builder option(String key, String value);
    
    /**
     * Sets multiple engine options
     * @param options map of option key-value pairs
     * @return this builder
     */
    public Builder options(Map<String, String> options);
    
    /**
     * Sets input stream for guest language standard input
     * @param in InputStream for stdin
     * @return this builder
     */
    public Builder in(InputStream in);
    
    /**
     * Sets output stream for guest language standard output
     * @param out OutputStream for stdout
     * @return this builder
     */
    public Builder out(OutputStream out);
    
    /**
     * Sets error stream for guest language standard error
     * @param err OutputStream for stderr
     * @return this builder
     */
    public Builder err(OutputStream err);
    
    /**
     * Builds the configured Context
     * @return new Context instance
     */
    public Context build();
}

Install with Tessl CLI

npx tessl i tessl/maven-org-graalvm-polyglot--python

docs

context-management.md

engine-language-management.md

index.md

java-python-interop.md

security-access-control.md

source-management.md

value-operations.md

tile.json