### Enumerate Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates using `enumerate` to create pairs of indices and values from a collection. Shows usage with and without a starting index. ```python enumerate(["zero", "one", "two"]) # [(0, "zero"), (1, "one"), (2, "two")] enumerate(["one", "two"], 1) # [(1, "one"), (2, "two")] ``` -------------------------------- ### Examples of Function Parameter Lists Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Provides various examples of valid function parameter list syntaxes in Starlark. ```python def f(): pass def f(a, b, c): pass def f(a, b, c=1): pass def f(a, b, c=1, *args): pass def f(a, b, c=1, *args, **kwargs): pass def f(**kwargs): pass def f(a, b, c=1, *, d=1): pass ``` -------------------------------- ### Starlark Literal Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Provides examples of integer, floating-point, string, and bytes literals in Starlark. ```text 0 # int 123 # decimal int 0x7f # hexadecimal int 0o755 # octal int 0.0 0. .0 # float 1e10 1e+10 1e-10 1.1e10 1.1e+10 1.1e-10 "hello" 'hello' # string '''hello''' """hello""" # triple-quoted string r'hello' r"hello" # raw string literal b"hello" b'hello' # bytes b'''hello''' b"""hello""" # triple-quoted bytes rb'hello' br"hello" # raw bytes literal ``` -------------------------------- ### Empty List Source: https://github.com/bazelbuild/starlark/blob/master/spec.md An example of creating an empty list. ```python [] # [], empty list ``` -------------------------------- ### String Method Call Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates calling built-in string methods like index and count. ```python ["able", "baker", "charlie"].index("baker") # 1 ``` ```python "banana".count("a") # 3 ``` ```python "banana".reverse() # error: string has no .reverse field or method ``` -------------------------------- ### String Slicing Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows half-open indexing for extracting subsequences from a string. The start index is inclusive, and the end index is exclusive. ```python "hello"[1:4] # "ell" ``` -------------------------------- ### Simple Assignment Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates basic assignment to variables, list/dictionary elements, and object fields. ```python k = 1 a[i] = v o.f = "" o.g(1)[2] = None ``` -------------------------------- ### Pass Statement Usage Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows practical examples of using the 'pass' statement in function definitions and loops where no operation is required. ```python def noop(): pass def list_to_dict(items): # Convert list of tuples to dict m = {} for k, m[k] in items: pass return m ``` -------------------------------- ### Empty Dictionary Source: https://github.com/bazelbuild/starlark/blob/master/spec.md An example of creating an empty dictionary. ```python {} ``` -------------------------------- ### List Comprehension Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates creating lists with and without conditional filtering, and nested loops. ```python [x*x for x in range(5)] # [0, 1, 4, 9, 16] ``` ```python [x*x for x in range(5) if x%2 == 0] # [0, 4, 16] ``` ```python [(x, y) for x in range(5) if x%2 == 0 for y in range(5) if y > x] # [(0, 1), (0, 2), (0, 3), (0, 4), (2, 3), (2, 4)] ``` -------------------------------- ### String Attributes Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows how to list the available attributes (methods) of a string object using the `dir()` function. ```python dir("hello") # ['capitalize', 'count', ...], the methods of a string ``` -------------------------------- ### Dictionary Creation Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates creating dictionaries using no arguments, an iterable of pairs, and keyword arguments. Shows combining different input methods. ```python dict() # {}, empty dictionary dict([(1, 2), (3, 4)]) # {1: 2, 3: 4} dict([(1, 2), ["a", "b"]]) # {1: 2, "a": "b"} dict(one=1, two=2) # {"one": 1, "two", 1} dict([(1, 2)], x=3) # {1: 2, "x": 3} ``` -------------------------------- ### List Comprehension Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates how to create a new list by applying an expression to each element of an existing sequence using a list comprehension. ```python [x*x for x in [1, 2, 3, 4]] # [1, 4, 9, 16] ``` -------------------------------- ### Augmented Assignment Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Provides examples of augmented assignments for arithmetic and bitwise operations on variables, object fields, and list elements. ```python x -= 1 x.filename += ".sky" a[index()] *= 2 ``` -------------------------------- ### Return Statement Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows different ways to use the 'return' statement to return values from a function: None, a single value, or a tuple of values. ```python return # returns None return 1 # returns 1 return 1, 2 # returns (1, 2) ``` -------------------------------- ### Compound Assignment Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates assignments to multiple targets using tuples and lists, including nested structures. ```python a, b = 2, 3 (x, y) = f() [zero, one, two] = range(3) [] = () ``` -------------------------------- ### Bytes Conversion Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates converting strings and iterables of integers to bytes. Shows handling of invalid UTF-8 sequences and type errors. ```python bytes("hello 😃") # b"hello 😃" bytes(b"hello 😃") # b"hello 😃" bytes("hello 😃"[:-1]) # b"hello " bytes([65, 66, 67]) # b"ABC" bytes(65) # error: got int, want string, bytes, or iterable of int ``` -------------------------------- ### Check if string starts with a prefix Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Reports whether the string (or a slice of it) starts with a specified prefix. The prefix can also be a tuple of strings to check for any of them. ```python "filename.sky".startswith("filename") # True ``` ```python "filename.star".startswith("name", 4) # True ``` ```python "filename.star".startswith("name", 4, 7) # False ``` ```python 'abc'.startswith(('a', 'A')) # True ``` ```python 'ABC'.startswith(('a', 'A')) # True ``` ```python 'def'.startswith(('a', 'A')) # False ``` -------------------------------- ### Starlark Identifier Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates valid identifiers in Starlark, which are sequences of Unicode letters, digits, and underscores, not starting with a digit. ```text None True len x index starts_with arg0 ``` -------------------------------- ### Function with Closure Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates a function that creates a closure, capturing a variable from its enclosing scope and accessing it later. ```python def f(x): res = [] def get_x(): res.append(x) get_x() x = 2 get_x() f(1) # returns [1, 2] ``` -------------------------------- ### Expression Statement Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates an expression statement, specifically calling a method for its side effect. ```python list.append(1) ``` -------------------------------- ### Find First Substring Occurrence (Error on Not Found) Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use `S.index(sub[, start[, end]])` to get the index of the first occurrence of a substring. This method fails if the substring is not found, unlike `S.find()`. ```python "bonbon".index("on") # 1 ``` ```python "bonbon".index("on", 2) # 4 ``` ```python "bonbon".index("on", 2, 5) # error: substring not found (in "nbo") ``` -------------------------------- ### Boolean Arithmetic Example Source: https://github.com/bazelbuild/starlark/blob/master/design.md These examples illustrate that Starlark booleans are a distinct type and do not inherit from integers, unlike Python. Attempting arithmetic or comparison operations between booleans and integers will result in a runtime error. ```starlark True + True ``` ```starlark True < 2 ``` -------------------------------- ### String Length Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates the varying lengths of string encodings for different Unicode characters based on the implementation's character unit size (e.g., UTF-8 or UTF-16). ```python len("A") # 1 len("Д") # 2 (UTF-8) or 1 (UTF-16) len("界") # 3 (UTF-8) or 1 (UTF-16) len("😀") # 4 (UTF-8) or 2 (UTF-16) ``` -------------------------------- ### Starlark Syntax Example Source: https://github.com/bazelbuild/starlark/blob/master/README.md This snippet demonstrates basic Starlark syntax, including variable definitions, dictionary manipulation, function definition, list comprehensions, and control flow. It is also valid Python code. ```python # Define a number number = 18 # Define a dictionary people = { "Alice": 22, "Bob": 40, "Charlie": 55, "Dave": 14, } names = ", ".join(people.keys()) # Alice, Bob, Charlie, Dave # Define a function def greet(name): """Return a greeting.""" return "Hello {}!".format(name) greeting = greet(names) above30 = [name for name, age in people.items() if age >= 30] print("{} people are above 30.".format(len(above30))) def fizz_buzz(n): """Print Fizz Buzz numbers from 1 to n.""" for i in range(1, n + 1): s = "" if i % 3 == 0: s += "Fizz" if i % 5 == 0: s += "Buzz" print(s if s else i) fizz_buzz(20) ``` -------------------------------- ### Get dictionary value by key with default Source: https://github.com/bazelbuild/starlark/blob/master/spec.md The `get(key[, default])` method retrieves the value for a given key. If the key is not found, it returns `None` or the specified default value. ```python x = {"one": 1, "two": 2} x.get("one") # 1 x.get("three") # None x.get("three", 0) # 0 ``` -------------------------------- ### Lambda Expression Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates the usage of a lambda expression within a map function to apply a transformation to each element of a list. ```python def map(f, list): return [f(x) for x in list] map(lambda x: 2*x, range(3)) # [2, 4, 6] ``` -------------------------------- ### Starlark Name Binding Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates various ways names are bound in Starlark, including load statements, function definitions, parameters, and assignments (simple and augmented). ```python load("lib.star", "a", b="B") def c(d): e = 0 for f in d: print([True for g in f]) e += 1 h = [2*i for i in a] ``` -------------------------------- ### String Indexing Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates zero-based indexing for accessing individual characters in a string. Accessing an index equal to or greater than the string length results in an error. ```python "hello"[0] # "h" "hello"[4] # "o" "hello"[5] # error: index out of range ``` -------------------------------- ### Call Function with Unpacked Dictionary Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates calling a function `f` by unpacking a dictionary of keyword arguments using the `**` operator. Includes examples of successful calls and calls that result in errors due to missing or unexpected keyword arguments. ```python def f(a, b, c=5): return a * b + c f(**dict(b=3, a=2)) # 11 f(**dict(c=7, a=2, b=3)) # 13 f(**dict(a=2)) # error: f takes at least 2 arguments (1 given) f(**dict(d=4)) # error: f got unexpected keyword argument "d" ``` -------------------------------- ### Single Assignment Example Source: https://github.com/bazelbuild/starlark/blob/master/design.md Demonstrates the single assignment rule at the top level. Global values like 'magic' and 'square' cannot be reassigned after their initial definition. ```starlark magic = 17 def square(x): return x ``` -------------------------------- ### Set Discard Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Removes a value from the set if it is present. Does not raise an error if the value is not found. ```python s = set(["x", "y"]) s.discard("y") # None; s == set(["x"]) s.discard("y") # None; s == set(["x"]) ``` -------------------------------- ### Set Difference Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Returns a new set with elements in the first set but not in others. Accepts arbitrary collections as arguments. ```python set([1, 2, 3]).difference([2]) # set([1, 3]) set([1, 2, 3]).difference([0, 1], [3, 4]) # set([2]) ``` -------------------------------- ### dict.get Source: https://github.com/bazelbuild/starlark/blob/master/spec.md `D.get(key[, default])` returns the dictionary value corresponding to the given key. If the dictionary contains no such value, `get` returns `None`, or the value of the optional `default` parameter if present. `get` fails if `key` is unhashable, or the dictionary is frozen or has active iterators. ```APIDOC ## dict.get ### Description Returns the value for a given key, or a default value if the key is not found. ### Method `get(key[, default])` ### Parameters - **key**: The key to look up in the dictionary. - **default**: Optional. The value to return if the key is not found. Defaults to `None`. ### Response - The value associated with the key, or the default value if the key is not present. ### Request Example ```python x = {"one": 1, "two": 2} x.get("one") x.get("three") x.get("three", 0) ``` ### Response Example ``` 1 None 0 ``` ``` -------------------------------- ### Logical OR Operator Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates the 'or' operator, which returns the first operand if it's truthy, otherwise the second. Uses short-circuit evaluation. ```python False or False # False False or True # True True or False # True True or True # True 0 or "hello" # "hello" 1 or "hello" # 1 ``` -------------------------------- ### Set Intersection Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Returns a new set with elements common to the set and all other specified collections. Accepts arbitrary collections. ```python set([1, 2]).intersection([2, 3]) # set([2]) set([1, 2, 3]).intersection([0, 1], [1, 2]) # set([1]) ``` -------------------------------- ### Starlark Function Return Values Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates how Starlark functions return values based on `return` statements or completion of the function body. Shows examples of returning `None` and specific values. ```python def f(x): if x == 0: return if x < 0: return -x print(x) f(1) # returns None after printing "1" f(0) # returns None without printing f(-1) # returns 1 without printing ``` -------------------------------- ### Get all keys from a dictionary Source: https://github.com/bazelbuild/starlark/blob/master/spec.md The `keys()` method returns a list of all keys in the dictionary, in the same order as they would be iterated. ```python x = {"one": 1, "two": 2} x.keys() # ["one", "two"] ``` -------------------------------- ### Logical AND Operator Examples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates the 'and' operator, which returns the first operand if it's falsy, otherwise the second. Uses short-circuit evaluation. ```python False and False # False False and True # False True and False # False True and True # True 0 and "hello" # 0 1 and "hello" # "hello" ``` -------------------------------- ### Convert string to titlecase Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Returns a copy of the string with letters converted to titlecase. Letters at the start of words are uppercased, and others are lowercased. ```python "hElLo, WoRlD!".title() # "Hello, World!" ``` -------------------------------- ### Set Difference Update Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Removes elements from the set that are also present in any of the other collections. Modifies the set in-place. ```python s = set([1, 2, 3, 4]) s.difference_update([2]) # None; s is set([1, 3, 4]) s.difference_update([0, 1], [4, 5]) # None; s is set([3]) ``` -------------------------------- ### Starlark Local Variable Scope Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates that variable usage within a scope refers to the binding within that scope, even if the use appears before the binding. The binding of 'y' makes it local to the 'hello' function. ```python y = "goodbye" def hello(): for x in (1, 2): if x == 2: print(y) # prints "hello" if x == 1: y = "hello" ``` -------------------------------- ### Generate Integer Sequences with Range Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Creates an immutable sequence of integers defined by start, stop, and step parameters. The sequence is not materialized but represented by a range value. ```python list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` ```python list(range(3, 10)) # [3, 4, 5, 6, 7, 8, 9] ``` ```python list(range(3, 10, 2)) # [3, 5, 7, 9] ``` ```python list(range(10, 3, -2)) # [10, 8, 6, 4] ``` -------------------------------- ### String Slicing with Omitted Indices Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates string slicing where omitting the start index defaults to 0 and omitting the end index defaults to the string length. ```python "hello"[1:] # "ello" "hello"[:4] # "hell" ``` -------------------------------- ### Get index of last occurrence of a substring with optional bounds Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use rindex(sub[, start[, end]]) to find the highest index where substring 'sub' is found. Raises an error if not found. Optional start and end indices define the search range. ```python "bonbon".rindex("on") # 4 "bonbon".rindex("on", None, 5) # 1 (in "bonbo") "bonbon".rindex("on", 2, 5) # error: substring not found (in "nbo") ``` -------------------------------- ### Find First Substring Occurrence Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use `S.find(sub[, start[, end]])` to get the index of the first occurrence of a substring. Returns -1 if not found. Search can be limited to a subrange. ```python "bonbon".find("on") # 1 ``` ```python "bonbon".find("on", 2) # 4 ``` ```python "bonbon".find("on", 2, 5) # -1 ``` -------------------------------- ### String Concatenation Example Source: https://github.com/bazelbuild/starlark/blob/master/design.md This code snippet demonstrates a common error in Starlark due to missing commas, which prevents implicit string concatenation. Use the '+' operator for explicit string concatenation. ```starlark arguments = [ "-c", "-O2", "-Wall" "-Werror", ] ``` -------------------------------- ### Short-Circuit Evaluation with 'and' and 'or' Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Provides examples of short-circuit evaluation for 'and' and 'or' operators, preventing evaluation of the second operand when the result is already determined. ```python len(x) > 0 and x[0] == 1 # x[0] is not evaluated if x is empty x and x[0] == 1 len(x) == 0 or x[0] == "" not x or not x[0] ``` -------------------------------- ### Dictionary Literal with Duplicate Keys in Starlark Source: https://github.com/bazelbuild/starlark/blob/master/design.md This example demonstrates a dictionary literal with a duplicate key ('//conditions:default'). Starlark throws an error when duplicate keys are present, unlike Python where the last key wins. This prevents accidental data duplication bugs. ```python defines = select({ "//conditions:default": [], "//tensorflow": ["FOO"], "//bazel": ["BAR"], # ... "//conditions:default": ["BAZ"], }), ``` -------------------------------- ### Remove a prefix from a string Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use removeprefix(x) to remove the specified prefix 'x' from the beginning of a string. If the string does not start with 'x', the original string is returned. Fails if 'x' is not a string. ```python "banana".removeprefix("ban") # "ana" "banana".removeprefix("ana") # "banana" "bbaa".removeprefix("b") # "baa" ``` -------------------------------- ### dict.setdefault Source: https://github.com/bazelbuild/starlark/blob/master/spec.md `D.setdefault(key[, default])` returns the dictionary value corresponding to the given key. If the dictionary contains no such value, `setdefault`, like `get`, returns `None` or the value of the optional `default` parameter if present; `setdefault` additionally inserts the new key/value entry into the dictionary. `setdefault` fails if the key is unhashable, or if the dictionary is frozen or has active iterators. ```APIDOC ## dict.setdefault ### Description Returns the value for a key if it exists, otherwise inserts the key with a default value and returns the default value. ### Method `setdefault(key[, default])` ### Parameters - **key**: The key to look up or insert. - **default**: Optional. The value to insert if the key is not found. Defaults to `None`. ### Response - The value associated with the key. If the key was not present, it's the newly inserted default value. ### Request Example ```python x = {"one": 1, "two": 2} x.setdefault("one") x.setdefault("three", 3) x.setdefault("three", 33) x.setdefault("four") ``` ### Response Example ``` 1 3 3 None ``` ``` -------------------------------- ### Creating Empty and Populated Lists Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates the syntax for creating empty lists and lists with one or more elements. ```python [] # an empty list [1] # a 1-element list [1, 2] # a 2-element list ``` -------------------------------- ### Find last occurrence of a substring with optional bounds Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use rfind(sub[, start[, end]]) to find the highest index where substring 'sub' is found. Returns -1 if not found. Optional start and end indices define the search range. ```python "bonbon".rfind("on") # 4 "bonbon".rfind("on", None, 5) # 1 "bonbon".rfind("on", 2, 5) # -1 ``` -------------------------------- ### Bound Method Usage Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows how to capture a method as a bound method and call it later. ```python f = "banana".count f # f("a") # 3 f("n") # 2 ``` -------------------------------- ### Tuple Creation Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates the creation of tuples, including the empty tuple, single-element tuples, and multi-element tuples using parentheses. ```python () (1,) (1, 2) (1, 2, 3) ``` -------------------------------- ### Set Intersection Update Example Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Removes elements from the set that are not present in any of the other collections. Modifies the set in-place. ```python s = set([1, 2, 3, 4]) s.intersection_update([0, 1, 2]) # None; s is set([1, 2]) s.intersection_update([0, 1], [1, 2]) # None; s is set([1]) ``` -------------------------------- ### Function with Varargs and Keyword-Only Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates a function with required, varargs, and keyword-only parameters. Highlights potential errors related to argument passing. ```python def g(a, *args, b=2, c): print(a, b, c, args) g(1, 3) # error: function g missing 1 argument (c) g(1, *[4, 5], c=3) # error: keyword argument c may not follow *args g(1, 4, c=3) # "1 2 3 (4,)" g(1, c=3, *[4, 5]) # "1 2 3 (4, 5)" ``` -------------------------------- ### Basic Value Operations Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates the string representation, type checking, boolean conversion, and hashing of Starlark values. ```text str(x) -- return a string representation of x type(x) -- return a string describing the type of x bool(x) -- convert x to a Boolean truth value hash(x) -- return a hash code for x ``` -------------------------------- ### string.endswith Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Reports whether the string S[start:end] has the specified suffix. The suffix can also be a tuple of strings. ```APIDOC ## string.endswith ### Description Reports whether the string S[start:end] has the specified suffix. ### Parameters - **suffix** (string or tuple[string]) - The suffix to check for. - **start** (int, optional) - The starting index of the slice to search within. - **end** (int, optional) - The ending index of the slice to search within. ### Example ```python "filename.sky".endswith(".sky") # True "filename.sky".endswith(".sky", 9, 12) # False "filename.sky".endswith("name", 0, 8) # True 'foo.cc'.endswith(('.cc', '.h')) # True ``` ``` -------------------------------- ### Creating Empty and Populated Tuples Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows the syntax for creating an empty tuple, a 1-tuple, and multi-element tuples. ```python () # the empty tuple (1,) # a 1-tuple (1, 2) # a 2-tuple ("pair") (1, 2, 3) # a 3-tuple ``` -------------------------------- ### Create an empty set Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use set() to create an empty set. This is useful for initializing a set when no elements are known. ```python set() ``` -------------------------------- ### Call Function with Named Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates calling the `idiv` function using named arguments, showing that order does not matter for named arguments. ```python idiv(x=6, y=3) # 2 idiv(y=3, x=6) # 2 ``` -------------------------------- ### Starlark Integer Arithmetic and Conversion Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates basic integer arithmetic operations like floored division, multiplication, and addition, as well as converting a hexadecimal string to an integer. ```python 100 // 5 * 9 + 32 # 212 3 // 2 # 1 111111111 * 111111111 # 12345678987654321 int("0xffff", 16) # 65535 ``` -------------------------------- ### Basic Arithmetic and Parentheses Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates standard arithmetic operations and the use of parentheses to control order of evaluation. ```python 1 + 2 * 3 + 4 # 11 (1 + 2) * (3 + 4) # 21 ``` -------------------------------- ### Get Dictionary Values Source: https://github.com/bazelbuild/starlark/blob/master/spec.md The `values()` method returns a new list containing all values from the dictionary in the order they would be iterated. ```python x = {"one": 1, "two": 2} x.values() # [1, 2] ``` -------------------------------- ### Get all key-value pairs from a dictionary Source: https://github.com/bazelbuild/starlark/blob/master/spec.md The `items()` method returns a list of all key-value pairs in the dictionary, preserving the order of iteration. ```python x = {"one": 1, "two": 2} x.items() # [("one", 1), ("two", 2)] ``` -------------------------------- ### Get Minimum Element in a Collection Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Returns the least element in a collection. Supports an optional key function for custom comparison. ```python min([3, 1, 4, 1, 5, 9]) # 1 ``` ```python min("two", "three", "four") # "four", the lexicographically least ``` ```python min("two", "three", "four", key=len) # "two", the shortest ``` -------------------------------- ### Function with Keyword-Only Arguments using Bare '*' Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates defining a function with keyword-only arguments using a bare '*' to separate positional and keyword-only parameters. Shows error cases for missing arguments. ```python def f(a, *, b=2, c): print(a, b, c) f(1) # error: function f missing 1 argument (c) f(1, 3) # error: function f accepts 1 positional argument (2 given) f(1, c=3) # "1 2 3" ``` -------------------------------- ### Call Function with Unpacked List Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates calling a function `f` by unpacking a list of positional arguments using the `*` operator. Shows successful calls and a call that results in an error due to insufficient arguments. ```python def f(a, b, c=5): return a * b + c f(*[2, 3]) # 11 f(*[2, 3, 7]) # 13 f(*[2]) # error: f takes at least 2 arguments (1 given) ``` -------------------------------- ### Get Maximum Element in a Collection Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Returns the greatest element in a collection. Supports an optional key function for custom comparison. ```python max([3, 1, 4, 1, 5, 9]) # 9 ``` ```python max("two", "three", "four") # "two", the lexicographically greatest ``` ```python max("two", "three", "four", key=len) # "three", the longest ``` -------------------------------- ### Bitwise Operations on Integers Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates bitwise AND, OR, XOR, left shift, and right shift operations on integers. Right shifts are arithmetic. ```python 0x12345678 & 0xFF # 0x00000078 0x12345678 | 0xFF # 0x123456FF 0b01011101 ^ 0b110101101 # 0b111110000 0b01011101 >> 2 # 0b010111 0b01011101 << 2 # 0b0101110100 -1 >> 100 # -1 ``` -------------------------------- ### String Slicing: Remove First and Last Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Extract a substring by specifying both start and end indices to exclude the first and last characters. ```python "abc"[1:-1] # "b" (remove first and last element) ``` -------------------------------- ### Dictionary with Single Key-Value Pair Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates creating a dictionary with one key-value pair. ```python {"one": 1} ``` -------------------------------- ### Partition string by first occurrence of a separator Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use partition(x) to split a string into three parts: the part before the first occurrence of 'x', 'x' itself, and the part after 'x'. If 'x' is not found, it returns (original_string, '', ''). Fails if 'x' is empty or not a string. ```python "one/two/three".partition("/") # ("one", "/", "two/three") ``` -------------------------------- ### String Slicing: Remove First/Last Element Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Extract a substring by omitting the start or end index to remove the first or last character. ```python "abc"[1:] # "bc" (remove first element) "abc"[:-1] # "ab" (remove last element) ``` -------------------------------- ### Get byte elements as integers Source: https://github.com/bazelbuild/starlark/blob/master/spec.md The `elems()` method returns an iterable of integer byte values. It can be converted to a list for easy inspection. ```python type(b"ABC".elems()) # "bytes.elems" b"ABC".elems() # b"ABC".elems() list(b"ABC".elems()) # [65, 66, 67] ``` -------------------------------- ### Define and Call Function with Variadic Keyword Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Defines a function `f` that accepts a variable number of keyword arguments using `**kwargs`. Demonstrates calls with no surplus keyword arguments, with named arguments, and with unexpected keyword arguments. ```python def f(x, y, **kwargs): return x, y, kwargs f(1, 2) # (1, 2, {}) f(x=2, y=1) # (2, 1, {}) f(x=2, y=1, z=3) # (2, 1, {"z": 3}) ``` -------------------------------- ### Boolean Context in Starlark Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates how values are evaluated in a boolean context in Starlark, showing conditional logic and explicit boolean conversion. ```python "A" if 1 + 1 else "B" # "A" "A" if 0.0 else "B" # "B" if not mylist: empty = True 1 == True # False bool(1) == True # True ``` -------------------------------- ### Get the type of a value Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use type(value) to obtain a string representing the data type of the operand. This is helpful for type checking or debugging. ```python type(None) ``` ```python type(0) ``` ```python type(0.0) ``` -------------------------------- ### List with Single Element Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates creating a list containing a single element. ```python [1] # [1], a 1-element list ``` -------------------------------- ### Def vs Lambda Function Naming Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates the difference in naming conventions between functions defined with 'def' and those created with lambda expressions. ```python def twice(x): return x * 2 twice = lambda x: x * 2 ``` -------------------------------- ### Check String Suffix Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use `S.endswith(suffix[, start[, end]])` to check if a string ends with a specified suffix, optionally within a given range. ```python "filename.sky".endswith(".sky") # True ``` ```python "filename.sky".endswith(".sky", 9, 12) # False ``` ```python "filename.sky".endswith("name", 0, 8) # True ``` -------------------------------- ### Tuple Unpacking in Assignment and Return Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows how tuples can be used without parentheses in assignment statements and return statements. ```python x, y = 1, 2 return 1, 2 ``` -------------------------------- ### String Concatenation Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows how to concatenate two strings using the '+' operator. ```python "Hello, " + "world" # "Hello, world" ``` -------------------------------- ### Escaping Literal Backslash and Newline Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates how to represent a literal backslash using '\\' and how an escaped newline allows splitting a long string across multiple source lines. ```python "abc\ def" ``` -------------------------------- ### Iterate Over String Elements Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use `S.elems()` to get an iterable of 1-element substrings. The type is 'string.elems'. Note: This splits codepoints into potentially invalid text strings. ```python "Hello, 123".elems() # "Hello, 123".elems() ``` ```python type("Hello, 123".elems()) # "string.elems" ``` ```python list("Hello, 123".elems()) # ["H", "e", "l", "l", "o", ",", " ", "1", "2", "3"] ``` -------------------------------- ### Define and Call a Simple Function Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Defines a function `idiv` that performs integer division and demonstrates calling it with positional arguments. ```python def idiv(x, y): return x // y idiv(6, 3) # 2 ``` -------------------------------- ### Tuple Syntax Variations and Errors Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Highlights syntax errors related to trailing commas in unparenthesized tuple expressions and shows valid examples of trailing commas in other contexts. ```python for k, v, in dict.items(): pass # syntax error at 'in' _ = [(v, k) for k, v, in dict.items()] # syntax error at 'in' sorted(3, 1, 4, 1,) # ok [1, 2, 3, ] # ok {1: 2, 3:4, } # ok ``` -------------------------------- ### Define and Call Function with Variadic Positional Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Defines a function `f` that accepts a variable number of positional arguments using `*args`. Demonstrates calls with no surplus arguments and with multiple surplus arguments. ```python def f(x, y, *args): return x, y, args f(1, 2) # (1, 2, ()) f(1, 2, 3, 4) # (1, 2, (3, 4)) ``` -------------------------------- ### List Mutation and Aliasing Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates how list mutations are observed through aliases due to call-by-value and reference passing. ```python x = [] # x refers to a new empty list variable y = x # y becomes an alias for x x.append(1) # changes the variable referred to by x print(y) # "[1]"; y observes the mutation ``` -------------------------------- ### Starlark Call and Arguments Syntax Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Defines the grammar for function calls and their arguments, including keyword and splat arguments. ```text CallSuffix = '(' [Arguments [',']] ')' . Arguments = Argument {',' Argument} . Argument = Expression | identifier '=' Expression | '*' Expression | '**' Expression . ``` -------------------------------- ### Define and Call Function with Optional Parameter Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Defines a function `f` with an optional parameter `y` that has a default value. Demonstrates calling it with and without providing a value for the optional parameter. ```python def f(x, y=3): return x, y f(1, 2) # (1, 2) f(1) # (1, 3) ``` -------------------------------- ### Basic Function Definition Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Defines a simple function that doubles its input. Shows how to call the function and its string representation. ```python def twice(x): return x * 2 str(twice) # "" twice(2) # 4 twice("two") # "twotwo" ``` -------------------------------- ### string.format Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Returns a version of the format string S in which bracketed portions `{...}` are replaced by arguments from args and kwargs. ```APIDOC ## string.format ### Description Returns a version of the format string S in which bracketed portions `{...}` are replaced by arguments from `args` and `kwargs`. ### Parameters - **args** (any, optional) - Positional arguments to format. - **kwargs** (any, optional) - Keyword arguments to format. ### Example ```python "a{x}b{y}c".format(1, x=2, y=3) # "a2b3c1" "a{}b{}c".format(1, 2) # "a1b2c" "({1}, {0})".format("zero", "one") # "(one, zero)" ``` ``` -------------------------------- ### Bitwise Inversion with '~' Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Shows the '~' operator for bitwise inversion of integers. The result is defined as -(x+1). ```python ~1 # -2 ~-1 # 0 ~0 # -1 ``` -------------------------------- ### Type and Equality of Float and Int Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates the type conversion and equality comparison between a float and an int in Starlark. Note that a large integer may not be exactly representable as a float. ```python (type(1.0), type(1)) # ("float", "int") 1.0 == 1 # True big = (1<<53)+1 # first int not exactly representable as float (big + 0.0) == big # False (addition caused rounding down) (big + 0.0) - big # 0.0 (both operands subject to rounding down) ``` -------------------------------- ### Print Arguments with Custom Separator Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Prints arguments formatted as strings, separated by a specified string (default is space). Output typically goes to standard error. ```python print(1, "hi", x=3) # "1 hi x=3\n" ``` ```python print("hello", "world") # "hello world\n" ``` ```python print("hello", "world", sep=", ") # "hello, world\n" ``` -------------------------------- ### Handling Tuples as Operands in String Interpolation Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates the correct way to use a tuple as an operand for a single conversion specifier in string interpolation. A singleton tuple is required to wrap the actual tuple operand. ```python "coordinates=%s" % (40, -74) # error: too many arguments for format string ``` ```python "coordinates=%s" % ((40, -74),) # "coordinates=(40, -74)" ``` -------------------------------- ### Tuple Syntax: 1-Element Tuples Source: https://github.com/bazelbuild/starlark/blob/master/design.md Illustrates the Starlark syntax requirement for 1-element tuples, which must be enclosed in parentheses. This differs from Python's syntax and helps prevent parsing errors. ```starlark x = max(3, 4, 6), # parse error ``` ```starlark x = (max(3, 4, 6),) # tuple with one element ``` -------------------------------- ### Floating-Point Arithmetic Operations Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates various floating-point arithmetic operations in Starlark, including multiplication, division, and floored division. ```python 1.23e45 * 1.23e45 # 1.5129e+90 1.111111111111111 * 1.111111111111111 # 1.23457 3.0 / 2 # 1.5 3 / 2.0 # 1.5 float(3) / 2 # 1.5 3.0 // 2.0 # 1.0 ``` -------------------------------- ### Dictionary Construction and Update Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Constructs a dictionary from a list of pairs and updates it with another list of pairs. ```python x = dict([("a", 1), ("b", 2)]) # {"a": 1, "b": 2} x.update([("a", 3), ("c", 4)]) # {"a": 3, "b": 2, "c": 4} ``` -------------------------------- ### Bytes Literals in Starlark Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Demonstrates various forms of bytes literals in Starlark, including single-quoted, double-quoted, triple-quoted, raw, and prefixed variants. ```python b"abc" b'abc' b"""abc""" b'''abc''' br"abc" br'abc' rb"abc" rb'abc' ``` -------------------------------- ### Format String with Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Use `S.format(*args, **kwargs)` to replace bracketed placeholders `{}` in a string with provided positional or keyword arguments. Literal braces can be escaped as `{{` or `}}`. ```text {} ``` ```text {field} ``` ```python "a{x}b{y}c".format(1, x=2, y=3) # "a2b3c1" ``` ```python "a{}b{}".format(1, 2) # "a1b2c" ``` ```python "({1}, {0})".format("zero", "one") # "(one, zero)" ``` -------------------------------- ### Call Function with Mixed Arguments Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates calling the `idiv` function with a mix of positional and named arguments, adhering to the rule that positional arguments must precede named arguments. ```python idiv(6, y=3) # 2 ``` -------------------------------- ### String Indexing with Negative Indices Source: https://github.com/bazelbuild/starlark/blob/master/spec.md Illustrates how negative indices are handled by adding the sequence length, allowing access to elements from the end of the string. ```python "hello"[-1] # "o", like "hello"[4] "hello"[-3:-1] # "ll", like "hello"[2:4] ```