Language Basics
Starlark Language Basics
Section titled “Starlark Language Basics”A quick tour of Starlark syntax and features.
Data Types
Section titled “Data Types”Primitives
Section titled “Primitives”# Numberscount = 42pi = 3.14159
# Stringsname = "Starlark"multiline = """This is amultiline string"""
# Booleansenabled = Truedisabled = False
# Noneempty = NoneCollections
Section titled “Collections”# Lists (mutable until frozen)fruits = ["apple", "banana", "cherry"]fruits.append("date")
# Tuples (immutable)point = (10, 20)
# Dictionariesperson = { "name": "Alice", "age": 30, "languages": ["Python", "Go"],}
# Sets (via dict keys)unique = {x: True for x in [1, 2, 2, 3]}.keys() # [1, 2, 3]Functions
Section titled “Functions”Basic Functions
Section titled “Basic Functions”def add(x, y): return x + y
result = add(2, 3) # 5Named Arguments
Section titled “Named Arguments”def greet(name, greeting="Hello"): return "{}, {}!".format(greeting, name)
greet("World") # Hello, World!greet("World", "Hi") # Hi, World!greet(greeting="Hey", name="You") # Hey, You!Variadic Functions
Section titled “Variadic Functions”# *args - positional argumentsdef sum_all(*numbers): total = 0 for n in numbers: total += n return total
sum_all(1, 2, 3, 4) # 10
# **kwargs - keyword argumentsdef configure(**options): return options
configure(debug=True, verbose=False) # {"debug": True, "verbose": False}Control Flow
Section titled “Control Flow”Conditionals
Section titled “Conditionals”def classify(age): if age < 13: return "child" elif age < 20: return "teenager" else: return "adult"For Loops
Section titled “For Loops”# Iterate over listfor fruit in ["apple", "banana"]: print(fruit)
# Iterate with indexfor i, fruit in enumerate(["apple", "banana"]): print(i, fruit)
# Iterate over dictfor key, value in {"a": 1, "b": 2}.items(): print(key, value)
# Range-based loopfor i in range(5): print(i) # 0, 1, 2, 3, 4Comprehensions
Section titled “Comprehensions”# List comprehensionsquares = [x * x for x in range(5)] # [0, 1, 4, 9, 16]
# With conditionevens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# Dict comprehensionword_lengths = {word: len(word) for word in ["hello", "world"]}# {"hello": 5, "world": 5}String Operations
Section titled “String Operations”name = "Starlark"
# Methodsname.upper() # "STARLARK"name.lower() # "starlark"name.startswith("Star") # Truename.replace("ark", "fish") # "Starlfish"
# Formatting"Hello, {}!".format("World") # "Hello, World!""x={}, y={}".format(10, 20) # "x=10, y=20"
# Join and split", ".join(["a", "b", "c"]) # "a, b, c""a,b,c".split(",") # ["a", "b", "c"]Loading Modules
Section titled “Loading Modules”# Load symbols from another fileload("//lib:utils.star", "helper", "CONSTANT")
# Load with aliasload("//lib:math.star", my_add = "add")
# Use loaded symbolsresult = helper()value = CONSTANTsum = my_add(1, 2)Structs
Section titled “Structs”Starlark doesn’t have classes, but you can use structs for structured data:
# Create a struct constructordef make_person(name, age): return struct( name = name, age = age, is_adult = age >= 18, )
alice = make_person("Alice", 25)print(alice.name) # "Alice"print(alice.is_adult) # TrueProviders (Bazel)
Section titled “Providers (Bazel)”In Bazel rules, providers are the standard way to pass information:
MyInfo = provider(fields = ["value", "files"])
def _my_rule_impl(ctx): return [MyInfo( value = "hello", files = ctx.files.srcs, )]Best Practices
Section titled “Best Practices”- Prefer immutability - Don’t modify data after creation
- Use descriptive names - Starlark code is often configuration
- Keep functions pure - Same inputs, same outputs
- Document with docstrings - Tools like
skydocextract them - Test your Starlark - Use
skytestfor unit tests
Try It Online
Section titled “Try It Online”Practice Starlark in the browser: