Starlark-pyo3
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
- breaking Major version upgrades of `pyo3` and `starlark-rust` can introduce breaking changes in API behavior or underlying data structures, especially if you're interacting with lower-level components or custom extensions. Always review the release notes carefully.
- gotcha The `init_once()` function must be called to initialize the underlying Rust Starlark interpreter. While it's safe to call multiple times, forgetting it will lead to errors.
- gotcha Changes to Starlark's type system or evaluation rules (e.g., `typecheck` introduction, handling of Python objects) might subtly alter script behavior or introduce new errors.
- gotcha The `FrozenModule.call` method gained `kwargs` support in `v2025.2.3`. If you previously had workarounds for passing keyword arguments or expected specific behavior, this change might impact your code.
Install
-
pip install starlark-pyo3
Imports
- Starlark
from starlark_pyo3 import Starlark
- init_once
from starlark_pyo3 import init_once
Quickstart
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}")