### Bitwise Inversion Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows examples of the '~' operator for bitwise inversion of integers. ```python ~1 # -2 ~-1 # 0 ~0 # -1 ``` -------------------------------- ### Dictionary Literal Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Provides examples of creating empty and populated dictionaries using literal syntax. ```python {} {"one": 1} {"one": 1, "two": 2,} ``` -------------------------------- ### List Literal Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows examples of creating empty and populated lists using literal syntax, including trailing commas. ```python [] # [], empty list [1] # [1], a 1-element list [1, 2, 3,] # [1, 2, 3], a 3-element list ``` -------------------------------- ### Install Starlark Interpreter Source: https://github.com/google/starlark-go/blob/master/README.md Installs the Starlark interpreter command-line tool into your Go bin directory. Ensure your Go environment is set up correctly. ```shell # check out the code and dependencies, # and install interpreter in $GOPATH/bin $ go install go.starlark.net/cmd/starlark@latest ``` -------------------------------- ### String Slicing with Half-Open Indexing Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Explains and demonstrates Starlark's half-open indexing for string slicing, where the start index is inclusive and the end index is exclusive. Shows a basic slicing example. ```python "hello"[1:4] ``` -------------------------------- ### string·startswith Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Reports whether the string starts with a specified prefix. ```APIDOC ## string·startswith ### Description Reports whether the string `S[start:end]` has the specified `prefix`. The `prefix` can also be a tuple of strings, in which case it returns true if any of the strings in the tuple is a prefix. ### Method Implicit (String method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python "filename.star".startswith("filename") # True 'abc'.startswith(('a', 'A')) # True 'ABC'.startswith(('a', 'A')) # True 'def'.startswith(('a', 'A')) # False ``` ### Response #### Success Response (200) - **boolean** - True if the string starts with the prefix, False otherwise. #### Response Example ```json { "example": true } ``` ``` -------------------------------- ### Run Starlark Script Source: https://github.com/google/starlark-go/blob/master/README.md Executes a Starlark script file using the installed 'starlark' command-line tool. The example demonstrates a simple Starlark program that processes a dictionary of coins. ```starlark coins = { 'dime': 10, 'nickel': 5, 'penny': 1, 'quarter': 25, } print('By name:\t' + ', '.join(sorted(coins.keys()))) print('By value:\t' + ', '.join(sorted(coins.keys(), key=coins.get))) ``` ```console $ starlark coins.star By name: dime, nickel, penny, quarter By value: penny, nickel, dime, quarter ``` -------------------------------- ### Starlark Floating-Point Literal Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows examples of floating-point literals in Starlark, including different formats and exponent notations. ```text 0.0 0. .0 # float 1e10 1e+10 1e-10 1.1e10 1.1e+10 1.1e-10 ``` -------------------------------- ### Order of Operations Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates how parentheses affect the order of operations in arithmetic expressions. ```python 1 + 2 * 3 + 4 # 11 (1 + 2) * (3 + 4) # 21 ``` -------------------------------- ### 'or' Operator Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates the 'or' operator's behavior with Boolean and non-Boolean operands. ```starlark False or False # False False or True # True True or False # True True or True # True 0 or "hello" # "hello" 1 or "hello" # 1 ``` -------------------------------- ### String Concatenation Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates string concatenation using the '+' operator. Ensure operands are of the same type. ```python "Hello, " + "world" # "Hello, world" ``` -------------------------------- ### List Comprehension Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates basic list comprehensions, including filtering with an if clause 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)] ``` -------------------------------- ### List Comprehension Example Source: https://github.com/google/starlark-go/blob/master/doc/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] ``` -------------------------------- ### Tuple Unpacking and Return Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows contexts where tuples can be expressed without parentheses, such as in assignments, return statements, and for loops. ```python x, y = 1, 2 return 1, 2 for x in 1, 2: print(x) ``` -------------------------------- ### List Construction Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates different ways to construct lists in Starlark, including empty lists, lists with elements, and lists created from iterables. ```python [] # an empty list [1] # a 1-element list [1, 2] # a 2-element list ``` -------------------------------- ### Starlark Core Value Operations Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Provides examples of core Starlark value operations: converting to string, getting the type, and converting to a boolean. ```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 ``` -------------------------------- ### Pass Statement Usage Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows examples of using the 'pass' statement in Starlark, such as in an empty function body or within a loop. ```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 ``` -------------------------------- ### Python Slice Expression Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates various slice operations on strings in Python, demonstrating how to extract sub-sequences. ```python "abc"[1:] # "bc" (remove first element) ``` ```python "abc"[:-1] # "ab" (remove last element) ``` ```python "abc"[1:-1] # "b" (remove first and last element) ``` ```python "banana"[1::2] # "aaa" (select alternate elements starting at index 1) ``` ```python "banana"[4::-2] # "nnb" (select alternate elements in reverse, starting at index 4) ``` -------------------------------- ### Set Union Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates set union using the '|' operator. Preserves element order from the left operand. ```python set([1, 2]) | set([2, 3]) # set([1, 2, 3]) ``` -------------------------------- ### Unary Plus and Minus Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates the usage of unary plus and minus operators, which return the number unchanged. ```python if x > 0: return +1 else if x < 0: return -1 else: return 0 ``` -------------------------------- ### 'and' Operator Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates the 'and' operator's behavior with Boolean and non-Boolean operands. ```starlark False and False # False False and True # False True and False # False True and True # True 0 and "hello" # 0 1 and "hello" # "hello" ``` -------------------------------- ### List Concatenation Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates list concatenation with the '+' operator. Operands must be lists. ```python [1, 2] + [3, 4] # [1, 2, 3, 4] ``` -------------------------------- ### Logical Negation Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates the behavior of the 'not' operator with various operand types. ```python not True # False not False # True not [1, 2, 3] # False not "" # True not 0 # True ``` -------------------------------- ### String Repetition Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates string repetition using the '*' operator with an integer. Negative integers behave like zero. ```python 'mur' * 2 # 'murmur' ``` -------------------------------- ### For loop with break and continue Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Example demonstrating the use of continue to skip odd numbers and break to exit the loop early. ```python for x in range(10): if x%2 == 1: continue # skip odd numbers if x > 7: break # stop at 8 print(x) # prints "0", "2", "4", "6" ``` -------------------------------- ### Create Dictionary with Comprehension Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Build a dictionary by iterating over an iterable and defining key-value expressions. This example maps words to their lengths. ```python words = ["able", "baker", "charlie"] {x: len(x) for x in words} # {"charlie": 7, "baker": 5, "able": 4} ``` -------------------------------- ### Tuple Concatenation Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows tuple concatenation using the '+' operator. Operands must be tuples. ```python (1, 2) + (3, 4) # (1, 2, 3, 4) ``` -------------------------------- ### Short-Circuit Evaluation Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows how 'and' and 'or' operators use short-circuit evaluation to avoid unnecessary computations. ```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] ``` -------------------------------- ### Bitwise AND and OR Operations Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Examples of bitwise AND and OR operations on integers. The result is the bitwise intersection or union. ```python 0x12345678 & 0xFF # 0x00000078 0x12345678 | 0xFF # 0x123456FF ``` -------------------------------- ### Starlark function parameter list examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates various valid function signature definitions in Starlark, including empty parameters, multiple parameters, default values, varargs, keyword-only arguments, and keyword arguments. ```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 def f( a, *args, **kwargs, ) ``` -------------------------------- ### Sequence Repetition Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows sequence repetition using the '*' operator with an integer. The order of operands does not matter. ```python 3 * range(3) # [0, 1, 2, 0, 1, 2, 0, 1, 2] ``` -------------------------------- ### Get iterable of 1-byte substrings Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Use `elems()` to get an iterable of successive 1-byte substrings. Apply `list(...)` to materialize the entire sequence. ```python list('Hello, 世界'.elems()) # ["H", "e", "l", "l", "o", ",", " ", "\xe4", "\xb8", "\x96", "\xe7", "\x95", "\x8c"] ``` -------------------------------- ### Starlark Integer Literal Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates various forms of integer literals in Starlark, including decimal, hexadecimal, octal, and binary representations. ```text 0 # int 123 # decimal int 0x7f # hexadecimal int 0o755 # octal int 0b1011 # binary int ``` -------------------------------- ### Augmented Assignment Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates the usage of augmented assignment operators for in-place updates of variables, object fields, and list elements. ```python x -= 1 x.filename += ".star" a[index()] *= 2 ``` -------------------------------- ### Lambda Expression Usage Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates the use of a lambda expression with a map function to apply a transformation to list elements. ```python def map(f, list): return [f(x) for x in list] map(lambda x: 2*x, range(3)) # [0, 2, 4] ``` -------------------------------- ### enumerate(x, start=0) Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a list of (index, value) pairs from an iterable, with an optional starting index. ```APIDOC ## enumerate(x, start=0) ### Description Returns a list of (index, value) pairs, each containing successive values of the iterable sequence `x` and the index of the value within the sequence. The optional second parameter, `start`, specifies an integer value to add to each index. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json { "example": "enumerate([\"zero\", \"one\", \"two\"])" } ``` ```json { "example": "enumerate([\"one\", \"two\"], 1)" } ``` ### Response #### Success Response (200) - **list** (list) - A list of tuples, where each tuple is (index, value). #### Response Example ```json { "example": "[(0, \"zero\"), (1, \"one\"), (2, \"two\")]" } ``` ```json { "example": "[(1, \"one\"), (2, \"two\")]" } ``` ``` -------------------------------- ### Loading Module Values Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Examples of Starlark load statements. The first argument is the module path, followed by names to extract. Local names can be specified using `local_name="module_name"`. ```starlark load("module.star", "x", "y", "z") # assigns x, y, and z ``` ```starlark load("module.star", "x", y2="y", "z") # assigns x, y2, and z ``` -------------------------------- ### Set Intersection Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows set intersection using the '&' operator. Requires operands of type 'set'. ```python set([1, 2]) & set([2, 3]) # set([2]) ``` -------------------------------- ### Basic String Indexing in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates how to access individual characters in a Starlark string using zero-based indexing. Shows examples of accessing the first and last characters, and an out-of-bounds index error. ```python "hello"[0] "hello"[4] "hello"[5] ``` -------------------------------- ### Starlark String Literal Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates different ways to define string literals in Starlark, including single-quoted, double-quoted, triple-quoted, and raw strings. ```text "hello" 'hello' # string '''hello''' """hello""" # triple-quoted string r'hello' r"hello" # raw string literal ``` -------------------------------- ### Set Difference Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows set difference using the '-' operator. Returns elements in the first set but not the second. ```python set([1, 2]) - set([2, 3]) # set([1]) ``` -------------------------------- ### Starlark Scope Example with Early Binding Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates that in Starlark, a name's scope is the entire block, even if the use appears before the binding. This differs from Python's behavior. ```python y = "goodbye" def hello(): for x in (1, 2): if x == 2: print(y) # prints "hello" if x == 1: y = "hello" ``` -------------------------------- ### Starlark Name Binding Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates various ways names are bound in Starlark: load statements, function definitions, function parameters, and assignments (including augmented assignments). ```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] ``` -------------------------------- ### Check if string starts with a prefix Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Use `startswith()` to check if a string begins with a specified prefix. The `prefix` can also be a tuple of strings to check for any of them. ```python "filename.star".startswith("filename") # True ``` ```python 'abc'.startswith(('a', 'A')) # True ``` ```python 'ABC'.startswith(('a', 'A')) # True ``` ```python 'def'.startswith(('a', 'A')) # False ``` -------------------------------- ### Boolean Truthiness Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates how integer values are evaluated in a boolean context. Non-zero integers evaluate to True, while zero evaluates to False. ```python 1 + 1 == 2 # True 2 + 2 == 5 # False if 1 + 1: print("True") else: print("False") ``` -------------------------------- ### Floating-Point Arithmetic Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates various arithmetic operations with floating-point numbers, including multiplication, division, and floored division. Note that integer operands are implicitly converted to floats in mixed operations. ```python 1.23e45 * 1.23e45 # 1.5129e+90 ``` ```python 1.111111111111111 * 1.111111111111111 # 1.23457 ``` ```python 3.0 / 2 # 1.5 ``` ```python 3 / 2.0 # 1.5 ``` ```python float(3) / 2 # 1.5 ``` ```python 3.0 // 2.0 # 1.0 ``` -------------------------------- ### Starlark REPL Fibonacci Example Source: https://github.com/google/starlark-go/blob/master/README.md Interacts with the Starlark read-eval-print loop (REPL) by defining and calling a Fibonacci function. Type Ctrl-D to exit the REPL. ```python >>> def fibonacci(n): ... res = list(range(n)) ... for i in res[2:]: ... res[i] = res[i-2] + res[i-1] ... return res ... >>> fibonacci(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> ``` -------------------------------- ### Set Symmetric Difference Example Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates set symmetric difference using the '^' operator. Returns elements in either set, but not both. ```python set([1, 2]) ^ set([2, 3]) # set([1, 3]) ``` -------------------------------- ### Define a simple function in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Use the `def` keyword to create a named function. The function body must be indented. This example shows a basic function and its usage. ```python def twice(x): return x * 2 str(twice) # "" twice(2) # 4 twice("two") # "twotwo" ``` -------------------------------- ### Starlark Identifier Examples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Provides examples of valid identifiers in Starlark, which are used for naming values. Identifiers consist of Unicode letters, digits, and underscores, not starting with a digit. ```text None True len x index starts_with arg0 ``` -------------------------------- ### Starlark Tuple Syntax Errors Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates syntax errors in Starlark related to unparenthesized tuples and trailing commas in specific contexts. These examples highlight restrictions compared to Python. ```python for k, v, in dict.items(): pass _ = [(v, k) for k, v, in dict.items()] f = lambda a, b, : None ``` -------------------------------- ### dict.setdefault(key, default) - Get or set default Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the value for a key. If the key is not found, inserts the key with a default value and returns the default. Fails if the key is unhashable or the dictionary is frozen. ```python x = {"one": 1, "two": 2} x.setdefault("one") # 1 x.setdefault("three", 0) # 0 x # {"one": 1, "two": 2, "three": 0} x.setdefault("four") # None x # {"one": 1, "two": 2, "three": 0, "four": None} ``` -------------------------------- ### Starlark function with optional and keyword-only parameters Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates defining functions with required, default, varargs, and keyword-only parameters. Note the error handling 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" ``` ```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, c=3) # "1 2 3 (4,)" ``` -------------------------------- ### Get iterable of Unicode code points Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Use `codepoints()` to get an iterable of substrings, each encoding a single Unicode code point. Invalid code points are replaced with U+FFFD. Apply `list(...)` to materialize the entire sequence. ```python list('Hello, 世界'.codepoints()) # ['H', 'e', 'l', 'l', 'o', ',', ' ', '世', '界'] ``` ```python for cp in 'Hello, 世界'.codepoints(): print(cp) # prints 'H', 'e', 'l', 'l', 'o', ',', ' ', '世', '界' ``` -------------------------------- ### String Slicing with Omitted Indices Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows how to perform string slicing in Starlark when either the start or end index is omitted. Omitting the start index defaults to 0, and omitting the end index defaults to the string's length. ```python "hello"[1:] "hello"[:4] ``` -------------------------------- ### Get the type of an operand with type() Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a string describing the type of its operand. ```python type(None) type(0) type(0.0) ``` -------------------------------- ### len() - Get Length Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the number of elements in its argument. Fails if the argument is not a sequence. ```APIDOC ## len() ### Description Returns the number of elements in its argument. ### Parameters #### Path Parameters - **x** (sequence) - The sequence to get the length of. ### Request Example ```python len([1, 2, 3]) len("hello") ``` ### Response #### Success Response (200) - **result** (int) - The number of elements in the sequence. ``` -------------------------------- ### Embed Starlark Interpreter in Go Source: https://github.com/google/starlark-go/blob/master/README.md Demonstrates how to embed and execute Starlark code within a Go program. This involves initializing a Starlark thread, executing a file, retrieving a global variable, and calling a Starlark function from Go. ```go import "go.starlark.net/starlark" // Execute Starlark program in a file. thread := &starlark.Thread{Name: "my thread"} globals, err := starlark.ExecFile(thread, "fibonacci.star", nil, nil) if err != nil { ... } // Retrieve a module global. fibonacci := globals["fibonacci"] // Call Starlark function from Go. v, err := starlark.Call(thread, fibonacci, starlark.Tuple{starlark.MakeInt(10)}, nil) if err != nil { ... } fmt.Printf("fibonacci(10) = %v\n", v) // fibonacci(10) = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` -------------------------------- ### Constructing Starlark Tuples Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates various ways to construct tuples in Starlark, including empty, 1-element, and multi-element tuples. Note the required trailing comma for 1-tuples. ```python () (1,) (1, 2) (1, 2, 3) ``` -------------------------------- ### Using Bound Methods in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows how to assign a method to a variable and call it later. The bound method is already associated with its receiver. ```python f = "banana".count f # f("a") # 3 f("n") # 2 ``` -------------------------------- ### Call Function with Named Arguments Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates calling the `idiv` function using named arguments, showing flexibility in argument order. Ensure the `-set` flag is enabled if using sets. ```python idiv(x=6, y=3) # 2 idiv(y=3, x=6) # 2 ``` -------------------------------- ### String and List Method Calls in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates calling methods on string and list objects. Note that strings do not have a 'reverse' method. ```python ["able", "baker", "charlie"].index("baker") # 1 "banana".count("a") # 3 "banana".reverse() # error: string has no .reverse field or method ``` -------------------------------- ### dict.keys() - Get dictionary keys Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a new list containing the keys of the dictionary. The order matches iteration order. ```python x = {"one": 1, "two": 2} x.keys() # ["one", "two"] ``` -------------------------------- ### dict.items() - Get key-value pairs Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a new list of key/value pairs from the dictionary. The order matches iteration order. ```python x = {"one": 1, "two": 2} x.items() # [("one", 1), ("two", 2)] ``` -------------------------------- ### Starlark Slice Expression Syntax Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Defines the grammar for slice expressions in Starlark, which can include start, stop, and stride operands. ```grammar SliceSuffix = '[' [Expression] [':' Test [':' Test]] ']' ``` -------------------------------- ### Variadic Arguments in Starlark Functions Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Use *args to accept an arbitrary number of positional arguments. Surplus arguments are collected into a tuple. ```python def f(x, y, *args): return x, y, args f(1, 2) # (1, 2, ()) f(1, 2, 3, 4) # (1, 2, (3, 4)) ``` -------------------------------- ### print() - Print Arguments Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Prints its arguments, followed by a newline. Arguments are formatted as strings and separated by a space, or a custom separator. ```APIDOC ## print() ### Description Prints its arguments, followed by a newline. ### Parameters #### Path Parameters - **args** (any) - Variable number of arguments to print. - **sep** (string) - Optional. The separator to use between arguments (defaults to space). ### Request Example ```python print(1, "hello") print("a", "b", sep=",") ``` ### Response #### Success Response (200) - **result** (string) - The formatted string that was printed. ``` -------------------------------- ### dict.values() - Get dictionary values Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a new list containing the dictionary's values. The order matches iteration order. ```python x = {"one": 1, "two": 2} x.values() # [1, 2] ``` -------------------------------- ### min() - Get Minimum Element Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the least element in an iterable sequence. Supports an optional 'key' function for custom comparison. ```APIDOC ## min() ### Description Returns the least element in the iterable sequence. ### Parameters #### Path Parameters - **x** (iterable) - The iterable sequence to find the minimum element in. - **key** (function) - Optional. A function to apply to each element before comparison. ### Request Example ```python min([1, 5, 2]) min("abc", key=len) ``` ### Response #### Success Response (200) - **result** (any) - The least element in the sequence. ``` -------------------------------- ### list() - Create List Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Constructs a list. With no argument, returns an empty list. Otherwise, returns a new list containing the elements of the iterable sequence. ```APIDOC ## list() ### Description Constructs a list. ### Parameters #### Path Parameters - **x** (iterable) - Optional. An iterable sequence to populate the list with. ### Request Example ```python list() list([1, 2, 3]) ``` ### Response #### Success Response (200) - **result** (list) - A new list. ``` -------------------------------- ### max() - Get Maximum Element Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the greatest element in an iterable sequence. Supports an optional 'key' function for custom comparison. ```APIDOC ## max() ### Description Returns the greatest element in the iterable sequence. ### Parameters #### Path Parameters - **x** (iterable) - The iterable sequence to find the maximum element in. - **key** (function) - Optional. A function to apply to each element before comparison. ### Request Example ```python max([1, 5, 2]) max("abc", key=len) ``` ### Response #### Success Response (200) - **result** (any) - The greatest element in the sequence. ``` -------------------------------- ### dict() Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Creates a dictionary. Can be initialized with an iterable of key-value pairs or keyword arguments. ```APIDOC ## dict() ### Description Creates a dictionary. It accepts up to one positional argument, which is interpreted as an iterable of two-element sequences (pairs), each specifying a key/value pair in the resulting dictionary. It also accepts any number of keyword arguments, each of which specifies a key/value pair; each keyword is treated as a string. With no arguments, `dict()` returns a new empty dictionary. `dict(x)` where x is a dictionary returns a new copy of x. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **iterable_of_pairs** (iterable) - Optional. An iterable of two-element sequences (e.g., lists or tuples) where each sequence represents a key-value pair. - **keyword_arguments** (any) - Optional. Keyword arguments where the keyword is the key (as a string) and the value is the corresponding value. ### Request Example ```json { "example": "dict([(1, 2), \"a\", \"b\"])" } ``` ```json { "example": "dict(one=1, two=2)" } ``` ### Response #### Success Response (200) - **dictionary** (dict) - A new dictionary. #### Response Example ```json { "example": "{1: 2, \"a\": \"b\"}" } ``` ```json { "example": "{\"one\": 1, \"two\": 2}" } ``` ``` -------------------------------- ### Set Comparison Operators Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Explains the usage of comparison operators (<, >, <=, >=) for set objects, indicating subset and superset relationships. ```shell dict # equal contents set # equal contents function # identity builtin_function_or_method # identity ``` -------------------------------- ### dir(x) Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a new sorted list of the names of the attributes (fields and methods) of its operand. ```APIDOC ## dir(x) ### Description Returns a new sorted list of the names of the attributes (fields and methods) of its operand. The attributes of a value `x` are the names `f` such that `x.f` is a valid expression. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json { "example": "dir(\"hello\")" } ``` ### Response #### Success Response (200) - **list** (list) - A sorted list of attribute names (strings). #### Response Example ```json { "example": "['capitalize', 'count', ...]" } ``` ``` -------------------------------- ### Remove Prefix from String Source: https://github.com/google/starlark-go/blob/master/doc/spec.md removeprefix() returns a copy of the string with the specified prefix removed if the string starts with it. Otherwise, it returns the original string. ```python "banana".removeprefix("ban") # "ana" "banana".removeprefix("foo") # "banana" "foofoobar".removeprefix("foo") # "foobar" ``` -------------------------------- ### List Mutation and Aliasing in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Demonstrates how assigning a list variable creates an alias, and mutations through one alias are visible through others. ```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 ``` -------------------------------- ### string.partition() Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Splits a string into three parts based on the first occurrence of a separator. ```APIDOC ## string.partition() ### Description Splits string S into three parts and returns them as a tuple: the portion before the first occurrence of string `x`, `x` itself, and the portion following it. If S does not contain `x`, `partition` returns `(S, "", "")`. Fails if `x` is not a string or is the empty string. ### Method `partition(x)` ### Parameters - **x** (string) - The separator string. ### Request Example ```python "one/two/three".partition("/") # ("one", "/", "two/three") ``` ### Response Tuple: A tuple of three strings: (part before separator, separator, part after separator). ``` -------------------------------- ### Get byte ordinals from string Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns an iterable of numeric byte values for the string. Apply list() to materialize the sequence. Not provided by the Java implementation. ```python list("Hello, 世界".elem_ords()) # [72, 101, 108, 108, 111, 44, 32, 228, 184, 150, 231, 149, 140] ``` -------------------------------- ### Keyword-Variadic Arguments in Starlark Functions Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Use **kwargs to accept an arbitrary number of keyword arguments. Surplus arguments are collected into a dictionary. ```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}) ``` -------------------------------- ### Get Index of Last Occurrence Source: https://github.com/google/starlark-go/blob/master/doc/spec.md rindex() is similar to rfind(), but raises an error if the substring is not found. It returns the index of the last occurrence within the specified 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") ``` -------------------------------- ### Create Index-Value Pairs with enumerate Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Generates a list of (index, value) pairs from an iterable. An optional start index can be provided to offset the default zero-based indexing. ```python enumerate(["zero", "one", "two"]) # [(0, "zero"), (1, "one"), (2, "two")] enumerate(["one", "two"], 1) # [(1, "one"), (2, "two")] ``` -------------------------------- ### string.format Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a formatted string by replacing bracketed placeholders with arguments. ```APIDOC ## string.format ### Description Returns a version of the format string `S` in which bracketed portions `{...}` are replaced by arguments from `args` and `kwargs`. Supports positional and keyword arguments, conversions (`!r`, `!s`), and format specifiers (currently reserved). ### Method String method ### Endpoint N/A (Method on string object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python "a{x}b{y}c".format(1, x=2, y=3) # "a2b3c1" "a{}b{}".format(1, 2) # "a1b2c" "({1}, {0})".format("zero", "one") # "(one, zero)" "Is {0!r} {0!s}?".format('heterological') # 'Is "heterological" heterological?' ``` ### Response #### Success Response (200) - **formatted_string** (string) - The resulting formatted string. ``` -------------------------------- ### Create an integer sequence with range() Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Generates an immutable sequence of integers. Requires one to three integer arguments (stop, start/stop, start/stop/step). Step cannot be zero. Returns a range value representing the sequence, which is iterable and indexable. ```python range(stop) range(start, stop) range(start, stop, step) ``` ```python list(range(10)) list(range(3, 10)) list(range(3, 10, 2)) list(range(10, 3, -2)) ``` -------------------------------- ### Get Attribute Value with getattr Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the value of an attribute (field or method) of an object. If the attribute does not exist, a dynamic error occurs unless a default value is provided. ```python getattr("banana", "split")("a") # ["b", "n", "n", ""], equivalent to "banana".split("a") ``` -------------------------------- ### List Comprehension Parse Errors Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows examples of invalid list comprehension syntax that result in parse errors, specifically with unparenthesized tuples and lambda expressions as loop operands. ```python [x*x for x in 1, 2, 3] # parse error: unexpected comma ``` ```python [x*x for x in lambda: 0] # parse error: unexpected lambda ``` -------------------------------- ### Partition String by First Occurrence Source: https://github.com/google/starlark-go/blob/master/doc/spec.md partition() splits a string into three parts based on the first occurrence of a separator string: the part before, the separator itself, and the part after. If the separator is not found, it returns the original string and two empty strings. ```python "one/two/three".partition("/") # ("one", "/", "two/three") ``` -------------------------------- ### Get Index of First Substring Occurrence in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the index of the first occurrence of a substring within a string or a specified slice. 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") ``` -------------------------------- ### Define and Call Function with Optional Parameter Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Shows a function `f` with an optional parameter `y` that has a default value. Demonstrates calling with and without providing a value for the optional parameter. Ensure the `-set` flag is enabled if using sets. ```python def f(x, y=3): return x, y f(1, 2) # (1, 2) f(1) # (1, 3) ``` -------------------------------- ### ord() - Get Unicode Code Point Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns the integer value of the sole Unicode code point encoded by the string. Fails if the string does not encode exactly one code point. ```APIDOC ## ord() ### Description Returns the integer value of the sole Unicode code point encoded by the string. ### Parameters #### Path Parameters - **s** (string) - The string containing a single Unicode code point. ### Request Example ```python ord("A") ord("😿") ``` ### Response #### Success Response (200) - **result** (int) - The integer value of the Unicode code point. ``` -------------------------------- ### Simple and Compound Assignment Targets Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates various forms of assignment targets, including simple variables, indexed elements, object fields, and compound targets. ```python k = 1 a[i] = v m.f = "" ``` ```python pi, e = 3.141, 2.718 (x, y) = f() [zero, one, two] = range(3) ``` ```python [(a, b), (c, d)] = {"a": "b", "c": "d"}.items() a, b = {"a": 1, "b": 2} ``` -------------------------------- ### Sequence Indexing in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Illustrates accessing elements of strings and tuples using positive and negative indices. ```python "abc"[0] # "a" "abc"[1] # "b" "abc"[-1] # "c" ("zero", "one", "two")[0] # "zero" ("zero", "one", "two")[1] # "one" ("zero", "one", "two")[-1] # "two" ``` -------------------------------- ### Format String with Arguments in Starlark Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns a formatted string by replacing bracketed placeholders with arguments. Supports positional and keyword arguments, and basic conversions like !r (repr) and !s (str). Format specifiers are reserved for future use. ```python "a{x}b{y}c".format(1, x=2, y=3) # "a2b3c1" ``` ```python "a{}b{}".format(1, 2) # "a1b2" ``` ```python "({1}, {0})".format("zero", "one") # "(one, zero)" ``` ```python "Is {0!r} {0!s}?".format('heterological') # 'Is "heterological" heterological?' ``` -------------------------------- ### string·elems Source: https://github.com/google/starlark-go/blob/master/doc/spec.md Returns an iterable of successive 1-byte substrings of the string. ```APIDOC ## string·elems ### Description Returns an iterable value containing successive 1-byte substrings of S. To materialize the entire sequence, apply `list(...)` to the result. ### Method Implicit (String method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python list('Hello, 世界'.elems()) # ["H", "e", "l", "l", "o", ",", " ", "\xe4", "\xb8", "\x96", "\xe7", "\x95", "\x8c"] ``` ### Response #### Success Response (200) - **iterable[string]** - An iterable of 1-byte substrings. #### Response Example ```json { "example": ["H", "e", "l", "l", "o", ",", " ", "\xe4", "\xb8", "\x96", "\xe7", "\x95", "\x8c"] } ``` ```