Starlark-pyo3

2025.2.5 · active · verified Sat Apr 11

Starlark-pyo3 is a Python wrapper for the `starlark-rust` interpreter, bringing Google's Starlark language (a dialect of Python used in Bazel) to Python applications. It enables executing Starlark scripts, evaluating expressions, and integrating with Python objects. The library is currently at version 2025.2.5 and follows a rapid release cadence, often tied to updates in its underlying Rust dependencies.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Starlark interpreter, define a load function for importing other Starlark files, evaluate a Starlark script, and access global variables and functions from the evaluated context. It also shows how to pass Python objects as globals into the Starlark environment.

from starlark_pyo3 import Starlark, init_once
import os

# Initialize the Starlark interpreter (safe to call multiple times)
init_once()

# Define a simple Starlark script
starlark_script = '''
load('foo.star', 'my_func')
def greet(name):
    return f"Hello, {name}!"

my_value = greet("Starlark")
'''

# Define a load function for external Starlark files
def load_func(name):
    if name == 'foo.star':
        return "def my_func(x): return x * 2"
    raise ValueError(f"Unknown module: {name}")

# Create a Starlark instance with custom globals and a load function
starlark_interpreter = Starlark(globals={'MAGIC_NUMBER': 42}, load_func=load_func)

# Evaluate the script
result_globals = starlark_interpreter.eval(starlark_script)

# Access a variable from the evaluated script
print(f"Result from Starlark: {result_globals['my_value']}")

# Call a function directly from the evaluated module
print(f"Calling greet: {result_globals['greet']('World')}")

# Verify a global was passed
print(f"Magic number: {result_globals['MAGIC_NUMBER']}")

# Evaluate an expression directly
expression_result = starlark_interpreter.eval('10 * MAGIC_NUMBER')
print(f"Expression result: {expression_result}")

view raw JSON →