1*4947cdc7SCole Faust# Starlark in Go: Language definition 2*4947cdc7SCole Faust 3*4947cdc7SCole FaustStarlark is a dialect of Python intended for use as a configuration 4*4947cdc7SCole Faustlanguage. A Starlark interpreter is typically embedded within a larger 5*4947cdc7SCole Faustapplication, and this application may define additional 6*4947cdc7SCole Faustdomain-specific functions and data types beyond those provided by the 7*4947cdc7SCole Faustcore language. For example, Starlark is embedded within (and was 8*4947cdc7SCole Faustoriginally developed for) the [Bazel build tool](https://bazel.build), 9*4947cdc7SCole Faustand [Bazel's build language](https://docs.bazel.build/versions/master/starlark/language.html) is based on Starlark. 10*4947cdc7SCole Faust 11*4947cdc7SCole FaustThis document describes the Go implementation of Starlark 12*4947cdc7SCole Faustat go.starlark.net/starlark. 13*4947cdc7SCole FaustThe language it defines is similar but not identical to 14*4947cdc7SCole Faust[the Java-based implementation](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/starlark/Starlark.java) 15*4947cdc7SCole Faustused by Bazel. 16*4947cdc7SCole FaustWe identify places where their behaviors differ, and an 17*4947cdc7SCole Faust[appendix](#dialect-differences) provides a summary of those 18*4947cdc7SCole Faustdifferences. 19*4947cdc7SCole FaustWe plan to converge both implementations on a single specification. 20*4947cdc7SCole Faust 21*4947cdc7SCole FaustThis document is maintained by Alan Donovan <[email protected]>. 22*4947cdc7SCole FaustIt was influenced by the Python specification, 23*4947cdc7SCole FaustCopyright 1990–2017, Python Software Foundation, 24*4947cdc7SCole Faustand the Go specification, Copyright 2009–2017, The Go Authors. 25*4947cdc7SCole Faust 26*4947cdc7SCole FaustStarlark was designed and implemented in Java by Laurent Le Brun, 27*4947cdc7SCole FaustDmitry Lomov, Jon Brandvin, and Damien Martin-Guillerez, standing on 28*4947cdc7SCole Faustthe shoulders of the Python community. 29*4947cdc7SCole FaustThe Go implementation was written by Alan Donovan and Jay Conrod; 30*4947cdc7SCole Faustits scanner was derived from one written by Russ Cox. 31*4947cdc7SCole Faust 32*4947cdc7SCole Faust## Overview 33*4947cdc7SCole Faust 34*4947cdc7SCole FaustStarlark is an untyped dynamic language with high-level data types, 35*4947cdc7SCole Faustfirst-class functions with lexical scope, and automatic memory 36*4947cdc7SCole Faustmanagement or _garbage collection_. 37*4947cdc7SCole Faust 38*4947cdc7SCole FaustStarlark is strongly influenced by Python, and is almost a subset of 39*4947cdc7SCole Faustthat language. In particular, its data types and syntax for 40*4947cdc7SCole Fauststatements and expressions will be very familiar to any Python 41*4947cdc7SCole Faustprogrammer. 42*4947cdc7SCole FaustHowever, Starlark is intended not for writing applications but for 43*4947cdc7SCole Faustexpressing configuration: its programs are short-lived and have no 44*4947cdc7SCole Faustexternal side effects and their main result is structured data or side 45*4947cdc7SCole Fausteffects on the host application. 46*4947cdc7SCole FaustAs a result, Starlark has no need for classes, exceptions, reflection, 47*4947cdc7SCole Faustconcurrency, and other such features of Python. 48*4947cdc7SCole Faust 49*4947cdc7SCole FaustStarlark execution is _deterministic_: all functions and operators 50*4947cdc7SCole Faustin the core language produce the same execution each time the program 51*4947cdc7SCole Faustis run; there are no sources of random numbers, clocks, or unspecified 52*4947cdc7SCole Faustiterators. This makes Starlark suitable for use in applications where 53*4947cdc7SCole Faustreproducibility is paramount, such as build tools. 54*4947cdc7SCole Faust 55*4947cdc7SCole Faust## Contents 56*4947cdc7SCole Faust 57*4947cdc7SCole Faust<!-- WTF? No automatic TOC? --> 58*4947cdc7SCole Faust 59*4947cdc7SCole Faust * [Overview](#overview) 60*4947cdc7SCole Faust * [Contents](#contents) 61*4947cdc7SCole Faust * [Lexical elements](#lexical-elements) 62*4947cdc7SCole Faust * [Data types](#data-types) 63*4947cdc7SCole Faust * [None](#none) 64*4947cdc7SCole Faust * [Booleans](#booleans) 65*4947cdc7SCole Faust * [Integers](#integers) 66*4947cdc7SCole Faust * [Floating-point numbers](#floating-point-numbers) 67*4947cdc7SCole Faust * [Strings](#strings) 68*4947cdc7SCole Faust * [Lists](#lists) 69*4947cdc7SCole Faust * [Tuples](#tuples) 70*4947cdc7SCole Faust * [Dictionaries](#dictionaries) 71*4947cdc7SCole Faust * [Sets](#sets) 72*4947cdc7SCole Faust * [Functions](#functions) 73*4947cdc7SCole Faust * [Built-in functions](#built-in-functions) 74*4947cdc7SCole Faust * [Name binding and variables](#name-binding-and-variables) 75*4947cdc7SCole Faust * [Value concepts](#value-concepts) 76*4947cdc7SCole Faust * [Identity and mutation](#identity-and-mutation) 77*4947cdc7SCole Faust * [Freezing a value](#freezing-a-value) 78*4947cdc7SCole Faust * [Hashing](#hashing) 79*4947cdc7SCole Faust * [Sequence types](#sequence-types) 80*4947cdc7SCole Faust * [Indexing](#indexing) 81*4947cdc7SCole Faust * [Expressions](#expressions) 82*4947cdc7SCole Faust * [Identifiers](#identifiers) 83*4947cdc7SCole Faust * [Literals](#literals) 84*4947cdc7SCole Faust * [Parenthesized expressions](#parenthesized-expressions) 85*4947cdc7SCole Faust * [Dictionary expressions](#dictionary-expressions) 86*4947cdc7SCole Faust * [List expressions](#list-expressions) 87*4947cdc7SCole Faust * [Unary operators](#unary-operators) 88*4947cdc7SCole Faust * [Binary operators](#binary-operators) 89*4947cdc7SCole Faust * [Conditional expressions](#conditional-expressions) 90*4947cdc7SCole Faust * [Comprehensions](#comprehensions) 91*4947cdc7SCole Faust * [Function and method calls](#function-and-method-calls) 92*4947cdc7SCole Faust * [Dot expressions](#dot-expressions) 93*4947cdc7SCole Faust * [Index expressions](#index-expressions) 94*4947cdc7SCole Faust * [Slice expressions](#slice-expressions) 95*4947cdc7SCole Faust * [Lambda expressions](#lambda-expressions) 96*4947cdc7SCole Faust * [Statements](#statements) 97*4947cdc7SCole Faust * [Pass statements](#pass-statements) 98*4947cdc7SCole Faust * [Assignments](#assignments) 99*4947cdc7SCole Faust * [Augmented assignments](#augmented-assignments) 100*4947cdc7SCole Faust * [Function definitions](#function-definitions) 101*4947cdc7SCole Faust * [Return statements](#return-statements) 102*4947cdc7SCole Faust * [Expression statements](#expression-statements) 103*4947cdc7SCole Faust * [If statements](#if-statements) 104*4947cdc7SCole Faust * [For loops](#for-loops) 105*4947cdc7SCole Faust * [Break and Continue](#break-and-continue) 106*4947cdc7SCole Faust * [Load statements](#load-statements) 107*4947cdc7SCole Faust * [Module execution](#module-execution) 108*4947cdc7SCole Faust * [Built-in constants and functions](#built-in-constants-and-functions) 109*4947cdc7SCole Faust * [None](#none) 110*4947cdc7SCole Faust * [True and False](#true-and-false) 111*4947cdc7SCole Faust * [any](#any) 112*4947cdc7SCole Faust * [all](#all) 113*4947cdc7SCole Faust * [bool](#bool) 114*4947cdc7SCole Faust * [chr](#chr) 115*4947cdc7SCole Faust * [dict](#dict) 116*4947cdc7SCole Faust * [dir](#dir) 117*4947cdc7SCole Faust * [enumerate](#enumerate) 118*4947cdc7SCole Faust * [fail](#fail) 119*4947cdc7SCole Faust * [float](#float) 120*4947cdc7SCole Faust * [getattr](#getattr) 121*4947cdc7SCole Faust * [hasattr](#hasattr) 122*4947cdc7SCole Faust * [hash](#hash) 123*4947cdc7SCole Faust * [int](#int) 124*4947cdc7SCole Faust * [len](#len) 125*4947cdc7SCole Faust * [list](#list) 126*4947cdc7SCole Faust * [max](#max) 127*4947cdc7SCole Faust * [min](#min) 128*4947cdc7SCole Faust * [ord](#ord) 129*4947cdc7SCole Faust * [print](#print) 130*4947cdc7SCole Faust * [range](#range) 131*4947cdc7SCole Faust * [repr](#repr) 132*4947cdc7SCole Faust * [reversed](#reversed) 133*4947cdc7SCole Faust * [set](#set) 134*4947cdc7SCole Faust * [sorted](#sorted) 135*4947cdc7SCole Faust * [str](#str) 136*4947cdc7SCole Faust * [tuple](#tuple) 137*4947cdc7SCole Faust * [type](#type) 138*4947cdc7SCole Faust * [zip](#zip) 139*4947cdc7SCole Faust * [Built-in methods](#built-in-methods) 140*4947cdc7SCole Faust * [dict·clear](#dict·clear) 141*4947cdc7SCole Faust * [dict·get](#dict·get) 142*4947cdc7SCole Faust * [dict·items](#dict·items) 143*4947cdc7SCole Faust * [dict·keys](#dict·keys) 144*4947cdc7SCole Faust * [dict·pop](#dict·pop) 145*4947cdc7SCole Faust * [dict·popitem](#dict·popitem) 146*4947cdc7SCole Faust * [dict·setdefault](#dict·setdefault) 147*4947cdc7SCole Faust * [dict·update](#dict·update) 148*4947cdc7SCole Faust * [dict·values](#dict·values) 149*4947cdc7SCole Faust * [list·append](#list·append) 150*4947cdc7SCole Faust * [list·clear](#list·clear) 151*4947cdc7SCole Faust * [list·extend](#list·extend) 152*4947cdc7SCole Faust * [list·index](#list·index) 153*4947cdc7SCole Faust * [list·insert](#list·insert) 154*4947cdc7SCole Faust * [list·pop](#list·pop) 155*4947cdc7SCole Faust * [list·remove](#list·remove) 156*4947cdc7SCole Faust * [set·union](#set·union) 157*4947cdc7SCole Faust * [string·capitalize](#string·capitalize) 158*4947cdc7SCole Faust * [string·codepoint_ords](#string·codepoint_ords) 159*4947cdc7SCole Faust * [string·codepoints](#string·codepoints) 160*4947cdc7SCole Faust * [string·count](#string·count) 161*4947cdc7SCole Faust * [string·elem_ords](#string·elem_ords) 162*4947cdc7SCole Faust * [string·elems](#string·elems) 163*4947cdc7SCole Faust * [string·endswith](#string·endswith) 164*4947cdc7SCole Faust * [string·find](#string·find) 165*4947cdc7SCole Faust * [string·format](#string·format) 166*4947cdc7SCole Faust * [string·index](#string·index) 167*4947cdc7SCole Faust * [string·isalnum](#string·isalnum) 168*4947cdc7SCole Faust * [string·isalpha](#string·isalpha) 169*4947cdc7SCole Faust * [string·isdigit](#string·isdigit) 170*4947cdc7SCole Faust * [string·islower](#string·islower) 171*4947cdc7SCole Faust * [string·isspace](#string·isspace) 172*4947cdc7SCole Faust * [string·istitle](#string·istitle) 173*4947cdc7SCole Faust * [string·isupper](#string·isupper) 174*4947cdc7SCole Faust * [string·join](#string·join) 175*4947cdc7SCole Faust * [string·lower](#string·lower) 176*4947cdc7SCole Faust * [string·lstrip](#string·lstrip) 177*4947cdc7SCole Faust * [string·partition](#string·partition) 178*4947cdc7SCole Faust * [string·replace](#string·replace) 179*4947cdc7SCole Faust * [string·rfind](#string·rfind) 180*4947cdc7SCole Faust * [string·rindex](#string·rindex) 181*4947cdc7SCole Faust * [string·rpartition](#string·rpartition) 182*4947cdc7SCole Faust * [string·rsplit](#string·rsplit) 183*4947cdc7SCole Faust * [string·rstrip](#string·rstrip) 184*4947cdc7SCole Faust * [string·split](#string·split) 185*4947cdc7SCole Faust * [string·splitlines](#string·splitlines) 186*4947cdc7SCole Faust * [string·startswith](#string·startswith) 187*4947cdc7SCole Faust * [string·strip](#string·strip) 188*4947cdc7SCole Faust * [string·title](#string·title) 189*4947cdc7SCole Faust * [string·upper](#string·upper) 190*4947cdc7SCole Faust * [Dialect differences](#dialect-differences) 191*4947cdc7SCole Faust 192*4947cdc7SCole Faust 193*4947cdc7SCole Faust## Lexical elements 194*4947cdc7SCole Faust 195*4947cdc7SCole FaustA Starlark program consists of one or more modules. 196*4947cdc7SCole FaustEach module is defined by a single UTF-8-encoded text file. 197*4947cdc7SCole Faust 198*4947cdc7SCole FaustA complete grammar of Starlark can be found in [grammar.txt](../syntax/grammar.txt). 199*4947cdc7SCole FaustThat grammar is presented piecemeal throughout this document 200*4947cdc7SCole Faustin boxes such as this one, which explains the notation: 201*4947cdc7SCole Faust 202*4947cdc7SCole Faust```grammar {.good} 203*4947cdc7SCole FaustGrammar notation 204*4947cdc7SCole Faust 205*4947cdc7SCole Faust- lowercase and 'quoted' items are lexical tokens. 206*4947cdc7SCole Faust- Capitalized names denote grammar productions. 207*4947cdc7SCole Faust- (...) implies grouping. 208*4947cdc7SCole Faust- x | y means either x or y. 209*4947cdc7SCole Faust- [x] means x is optional. 210*4947cdc7SCole Faust- {x} means x is repeated zero or more times. 211*4947cdc7SCole Faust- The end of each declaration is marked with a period. 212*4947cdc7SCole Faust``` 213*4947cdc7SCole Faust 214*4947cdc7SCole FaustThe contents of a Starlark file are broken into a sequence of tokens of 215*4947cdc7SCole Faustfive kinds: white space, punctuation, keywords, identifiers, and literals. 216*4947cdc7SCole FaustEach token is formed from the longest sequence of characters that 217*4947cdc7SCole Faustwould form a valid token of each kind. 218*4947cdc7SCole Faust 219*4947cdc7SCole Faust```grammar {.good} 220*4947cdc7SCole FaustFile = {Statement | newline} eof . 221*4947cdc7SCole Faust``` 222*4947cdc7SCole Faust 223*4947cdc7SCole Faust*White space* consists of spaces (U+0020), tabs (U+0009), carriage 224*4947cdc7SCole Faustreturns (U+000D), and newlines (U+000A). Within a line, white space 225*4947cdc7SCole Fausthas no effect other than to delimit the previous token, but newlines, 226*4947cdc7SCole Faustand spaces at the start of a line, are significant tokens. 227*4947cdc7SCole Faust 228*4947cdc7SCole Faust*Comments*: A hash character (`#`) appearing outside of a string 229*4947cdc7SCole Faustliteral marks the start of a comment; the comment extends to the end 230*4947cdc7SCole Faustof the line, not including the newline character. 231*4947cdc7SCole FaustComments are treated like other white space. 232*4947cdc7SCole Faust 233*4947cdc7SCole Faust*Punctuation*: The following punctuation characters or sequences of 234*4947cdc7SCole Faustcharacters are tokens: 235*4947cdc7SCole Faust 236*4947cdc7SCole Faust```text 237*4947cdc7SCole Faust+ - * / // % = 238*4947cdc7SCole Faust+= -= *= /= //= %= == != 239*4947cdc7SCole Faust^ < > << >> & | 240*4947cdc7SCole Faust^= <= >= <<= >>= &= |= 241*4947cdc7SCole Faust. , ; : ~ ** 242*4947cdc7SCole Faust( ) [ ] { } 243*4947cdc7SCole Faust``` 244*4947cdc7SCole Faust 245*4947cdc7SCole Faust*Keywords*: The following tokens are keywords and may not be used as 246*4947cdc7SCole Faustidentifiers: 247*4947cdc7SCole Faust 248*4947cdc7SCole Faust```text 249*4947cdc7SCole Faustand elif in or 250*4947cdc7SCole Faustbreak else lambda pass 251*4947cdc7SCole Faustcontinue for load return 252*4947cdc7SCole Faustdef if not while 253*4947cdc7SCole Faust``` 254*4947cdc7SCole Faust 255*4947cdc7SCole FaustThe tokens below also may not be used as identifiers although they do not 256*4947cdc7SCole Faustappear in the grammar; they are reserved as possible future keywords: 257*4947cdc7SCole Faust 258*4947cdc7SCole Faust<!-- and to remain a syntactic subset of Python --> 259*4947cdc7SCole Faust 260*4947cdc7SCole Faust```text 261*4947cdc7SCole Faustas finally nonlocal 262*4947cdc7SCole Faustassert from raise 263*4947cdc7SCole Faustclass global try 264*4947cdc7SCole Faustdel import with 265*4947cdc7SCole Faustexcept is yield 266*4947cdc7SCole Faust``` 267*4947cdc7SCole Faust 268*4947cdc7SCole Faust<b>Implementation note:</b> 269*4947cdc7SCole FaustThe Go implementation permits `assert` to be used as an identifier, 270*4947cdc7SCole Faustand this feature is widely used in its tests. 271*4947cdc7SCole Faust 272*4947cdc7SCole Faust*Identifiers*: an identifier is a sequence of Unicode letters, decimal 273*4947cdc7SCole Faust digits, and underscores (`_`), not starting with a digit. 274*4947cdc7SCole FaustIdentifiers are used as names for values. 275*4947cdc7SCole Faust 276*4947cdc7SCole FaustExamples: 277*4947cdc7SCole Faust 278*4947cdc7SCole Faust```text 279*4947cdc7SCole FaustNone True len 280*4947cdc7SCole Faustx index starts_with arg0 281*4947cdc7SCole Faust``` 282*4947cdc7SCole Faust 283*4947cdc7SCole Faust*Literals*: literals are tokens that denote specific values. Starlark 284*4947cdc7SCole Fausthas string, integer, and floating-point literals. 285*4947cdc7SCole Faust 286*4947cdc7SCole Faust```text 287*4947cdc7SCole Faust0 # int 288*4947cdc7SCole Faust123 # decimal int 289*4947cdc7SCole Faust0x7f # hexadecimal int 290*4947cdc7SCole Faust0o755 # octal int 291*4947cdc7SCole Faust0b1011 # binary int 292*4947cdc7SCole Faust 293*4947cdc7SCole Faust0.0 0. .0 # float 294*4947cdc7SCole Faust1e10 1e+10 1e-10 295*4947cdc7SCole Faust1.1e10 1.1e+10 1.1e-10 296*4947cdc7SCole Faust 297*4947cdc7SCole Faust"hello" 'hello' # string 298*4947cdc7SCole Faust'''hello''' """hello""" # triple-quoted string 299*4947cdc7SCole Faustr'hello' r"hello" # raw string literal 300*4947cdc7SCole Faust``` 301*4947cdc7SCole Faust 302*4947cdc7SCole FaustInteger and floating-point literal tokens are defined by the following grammar: 303*4947cdc7SCole Faust 304*4947cdc7SCole Faust```grammar {.good} 305*4947cdc7SCole Faustint = decimal_lit | octal_lit | hex_lit | binary_lit . 306*4947cdc7SCole Faustdecimal_lit = ('1' … '9') {decimal_digit} | '0' . 307*4947cdc7SCole Faustoctal_lit = '0' ('o'|'O') octal_digit {octal_digit} . 308*4947cdc7SCole Fausthex_lit = '0' ('x'|'X') hex_digit {hex_digit} . 309*4947cdc7SCole Faustbinary_lit = '0' ('b'|'B') binary_digit {binary_digit} . 310*4947cdc7SCole Faust 311*4947cdc7SCole Faustfloat = decimals '.' [decimals] [exponent] 312*4947cdc7SCole Faust | decimals exponent 313*4947cdc7SCole Faust | '.' decimals [exponent] 314*4947cdc7SCole Faust . 315*4947cdc7SCole Faustdecimals = decimal_digit {decimal_digit} . 316*4947cdc7SCole Faustexponent = ('e'|'E') ['+'|'-'] decimals . 317*4947cdc7SCole Faust 318*4947cdc7SCole Faustdecimal_digit = '0' … '9' . 319*4947cdc7SCole Faustoctal_digit = '0' … '7' . 320*4947cdc7SCole Fausthex_digit = '0' … '9' | 'A' … 'F' | 'a' … 'f' . 321*4947cdc7SCole Faustbinary_digit = '0' | '1' . 322*4947cdc7SCole Faust``` 323*4947cdc7SCole Faust 324*4947cdc7SCole Faust### String literals 325*4947cdc7SCole Faust 326*4947cdc7SCole FaustA Starlark string literal denotes a string value. 327*4947cdc7SCole FaustIn its simplest form, it consists of the desired text 328*4947cdc7SCole Faustsurrounded by matching single- or double-quotation marks: 329*4947cdc7SCole Faust 330*4947cdc7SCole Faust```python 331*4947cdc7SCole Faust"abc" 332*4947cdc7SCole Faust'abc' 333*4947cdc7SCole Faust``` 334*4947cdc7SCole Faust 335*4947cdc7SCole FaustLiteral occurrences of the chosen quotation mark character must be 336*4947cdc7SCole Faustescaped by a preceding backslash. So, if a string contains several 337*4947cdc7SCole Faustof one kind of quotation mark, it may be convenient to quote the string 338*4947cdc7SCole Faustusing the other kind, as in these examples: 339*4947cdc7SCole Faust 340*4947cdc7SCole Faust```python 341*4947cdc7SCole Faust'Have you read "To Kill a Mockingbird?"' 342*4947cdc7SCole Faust"Yes, it's a classic." 343*4947cdc7SCole Faust 344*4947cdc7SCole Faust"Have you read \"To Kill a Mockingbird?\"" 345*4947cdc7SCole Faust'Yes, it\'s a classic.' 346*4947cdc7SCole Faust``` 347*4947cdc7SCole Faust 348*4947cdc7SCole FaustLiteral occurrences of the _opposite_ kind of quotation mark, such as 349*4947cdc7SCole Faustan apostrophe within a double-quoted string literal, may be escaped 350*4947cdc7SCole Faustby a backslash, but this is not necessary: `"it's"` and `"it\'s"` are 351*4947cdc7SCole Faustequivalent. 352*4947cdc7SCole Faust 353*4947cdc7SCole Faust 354*4947cdc7SCole Faust#### String escapes 355*4947cdc7SCole Faust 356*4947cdc7SCole FaustWithin a string literal, the backslash character `\` indicates the 357*4947cdc7SCole Fauststart of an _escape sequence_, a notation for expressing things that 358*4947cdc7SCole Faustare impossible or awkward to write directly. 359*4947cdc7SCole Faust 360*4947cdc7SCole FaustThe following *traditional escape sequences* represent the ASCII control 361*4947cdc7SCole Faustcodes 7-13: 362*4947cdc7SCole Faust 363*4947cdc7SCole Faust``` 364*4947cdc7SCole Faust\a \x07 alert or bell 365*4947cdc7SCole Faust\b \x08 backspace 366*4947cdc7SCole Faust\f \x0C form feed 367*4947cdc7SCole Faust\n \x0A line feed 368*4947cdc7SCole Faust\r \x0D carriage return 369*4947cdc7SCole Faust\t \x09 horizontal tab 370*4947cdc7SCole Faust\v \x0B vertical tab 371*4947cdc7SCole Faust``` 372*4947cdc7SCole Faust 373*4947cdc7SCole FaustA *literal backslash* is written using the escape `\\`. 374*4947cdc7SCole Faust 375*4947cdc7SCole FaustAn *escaped newline*---that is, a backslash at the end of a line---is ignored, 376*4947cdc7SCole Faustallowing a long string to be split across multiple lines of the source file. 377*4947cdc7SCole Faust 378*4947cdc7SCole Faust```python 379*4947cdc7SCole Faust"abc\ 380*4947cdc7SCole Faustdef" # "abcdef" 381*4947cdc7SCole Faust``` 382*4947cdc7SCole Faust 383*4947cdc7SCole FaustAn *octal escape* encodes a single byte using its octal value. 384*4947cdc7SCole FaustIt consists of a backslash followed by one, two, or three octal digits [0-7]. 385*4947cdc7SCole FaustIt is error if the value is greater than decimal 255. 386*4947cdc7SCole Faust 387*4947cdc7SCole Faust```python 388*4947cdc7SCole Faust'\0' # "\x00" a string containing a single NUL byte 389*4947cdc7SCole Faust'\12' # "\n" octal 12 = decimal 10 390*4947cdc7SCole Faust'\101-\132' # "A-Z" 391*4947cdc7SCole Faust'\119' # "\t9" = "\11" + "9" 392*4947cdc7SCole Faust``` 393*4947cdc7SCole Faust 394*4947cdc7SCole Faust<b>Implementation note:</b> 395*4947cdc7SCole FaustThe Java implementation encodes strings using UTF-16, 396*4947cdc7SCole Faustso an octal escape encodes a single UTF-16 code unit. 397*4947cdc7SCole FaustOctal escapes for values above 127 are therefore not portable across implementations. 398*4947cdc7SCole FaustThere is little reason to use octal escapes in new code. 399*4947cdc7SCole Faust 400*4947cdc7SCole FaustA *hex escape* encodes a single byte using its hexadecimal value. 401*4947cdc7SCole FaustIt consists of `\x` followed by exactly two hexadecimal digits [0-9A-Fa-f]. 402*4947cdc7SCole Faust 403*4947cdc7SCole Faust```python 404*4947cdc7SCole Faust"\x00" # "\x00" a string containing a single NUL byte 405*4947cdc7SCole Faust"(\x20)" # "( )" ASCII 0x20 = 32 = space 406*4947cdc7SCole Faust 407*4947cdc7SCole Faustred, reset = "\x1b[31m", "\x1b[0m" # ANSI terminal control codes for color 408*4947cdc7SCole Faust"(" + red + "hello" + reset + ")" # "(hello)" with red text, if on a terminal 409*4947cdc7SCole Faust``` 410*4947cdc7SCole Faust 411*4947cdc7SCole Faust<b>Implementation note:</b> 412*4947cdc7SCole FaustThe Java implementation does not support hex escapes. 413*4947cdc7SCole Faust 414*4947cdc7SCole FaustAn ordinary string literal may not contain an unescaped newline, 415*4947cdc7SCole Faustbut a *multiline string literal* may spread over multiple source lines. 416*4947cdc7SCole FaustIt is denoted using three quotation marks at start and end. 417*4947cdc7SCole FaustWithin it, unescaped newlines and quotation marks (or even pairs of 418*4947cdc7SCole Faustquotation marks) have their literal meaning, but three quotation marks 419*4947cdc7SCole Faustend the literal. This makes it easy to quote large blocks of text with 420*4947cdc7SCole Faustfew escapes. 421*4947cdc7SCole Faust 422*4947cdc7SCole Faust``` 423*4947cdc7SCole Fausthaiku = ''' 424*4947cdc7SCole FaustYesterday it worked. 425*4947cdc7SCole FaustToday it is not working. 426*4947cdc7SCole FaustThat's computers. Sigh. 427*4947cdc7SCole Faust''' 428*4947cdc7SCole Faust``` 429*4947cdc7SCole Faust 430*4947cdc7SCole FaustRegardless of the platform's convention for text line endings---for 431*4947cdc7SCole Faustexample, a linefeed (\n) on UNIX, or a carriage return followed by a 432*4947cdc7SCole Faustlinefeed (\r\n) on Microsoft Windows---an unescaped line ending in a 433*4947cdc7SCole Faustmultiline string literal always denotes a line feed (\n). 434*4947cdc7SCole Faust 435*4947cdc7SCole FaustStarlark also supports *raw string literals*, which look like an 436*4947cdc7SCole Faustordinary single- or double-quotation preceded by `r`. Within a raw 437*4947cdc7SCole Fauststring literal, there is no special processing of backslash escapes, 438*4947cdc7SCole Faustother than an escaped quotation mark (which denotes a literal 439*4947cdc7SCole Faustquotation mark), or an escaped newline (which denotes a backslash 440*4947cdc7SCole Faustfollowed by a newline). This form of quotation is typically used when 441*4947cdc7SCole Faustwriting strings that contain many quotation marks or backslashes (such 442*4947cdc7SCole Faustas regular expressions or shell commands) to reduce the burden of 443*4947cdc7SCole Faustescaping: 444*4947cdc7SCole Faust 445*4947cdc7SCole Faust```python 446*4947cdc7SCole Faust"a\nb" # "a\nb" = 'a' + '\n' + 'b' 447*4947cdc7SCole Faustr"a\nb" # "a\\nb" = 'a' + '\\' + 'n' + 'b' 448*4947cdc7SCole Faust 449*4947cdc7SCole Faust"a\ 450*4947cdc7SCole Faustb" # "ab" 451*4947cdc7SCole Faustr"a\ 452*4947cdc7SCole Faustb" # "a\\\nb" 453*4947cdc7SCole Faust``` 454*4947cdc7SCole Faust 455*4947cdc7SCole FaustIt is an error for a backslash to appear within a string literal other 456*4947cdc7SCole Faustthan as part of one of the escapes described above. 457*4947cdc7SCole Faust 458*4947cdc7SCole FaustTODO: define indent, outdent, semicolon, newline, eof 459*4947cdc7SCole Faust 460*4947cdc7SCole Faust## Data types 461*4947cdc7SCole Faust 462*4947cdc7SCole FaustThese are the main data types built in to the interpreter: 463*4947cdc7SCole Faust 464*4947cdc7SCole Faust```python 465*4947cdc7SCole FaustNoneType # the type of None 466*4947cdc7SCole Faustbool # True or False 467*4947cdc7SCole Faustint # a signed integer of arbitrary magnitude 468*4947cdc7SCole Faustfloat # an IEEE 754 double-precision floating point number 469*4947cdc7SCole Fauststring # a byte string 470*4947cdc7SCole Faustlist # a modifiable sequence of values 471*4947cdc7SCole Fausttuple # an unmodifiable sequence of values 472*4947cdc7SCole Faustdict # a mapping from values to values 473*4947cdc7SCole Faustset # a set of values 474*4947cdc7SCole Faustfunction # a function implemented in Starlark 475*4947cdc7SCole Faustbuiltin_function_or_method # a function or method implemented by the interpreter or host application 476*4947cdc7SCole Faust``` 477*4947cdc7SCole Faust 478*4947cdc7SCole FaustSome functions, such as the iteration methods of `string`, or the 479*4947cdc7SCole Faust`range` function, return instances of special-purpose types that don't 480*4947cdc7SCole Faustappear in this list. 481*4947cdc7SCole FaustAdditional data types may be defined by the host application into 482*4947cdc7SCole Faustwhich the interpreter is embedded, and those data types may 483*4947cdc7SCole Faustparticipate in basic operations of the language such as arithmetic, 484*4947cdc7SCole Faustcomparison, indexing, and function calls. 485*4947cdc7SCole Faust 486*4947cdc7SCole Faust<!-- We needn't mention the stringIterable type here. --> 487*4947cdc7SCole Faust 488*4947cdc7SCole FaustSome operations can be applied to any Starlark value. For example, 489*4947cdc7SCole Faustevery value has a type string that can be obtained with the expression 490*4947cdc7SCole Faust`type(x)`, and any value may be converted to a string using the 491*4947cdc7SCole Faustexpression `str(x)`, or to a Boolean truth value using the expression 492*4947cdc7SCole Faust`bool(x)`. Other operations apply only to certain types. For 493*4947cdc7SCole Faustexample, the indexing operation `a[i]` works only with strings, lists, 494*4947cdc7SCole Faustand tuples, and any application-defined types that are _indexable_. 495*4947cdc7SCole FaustThe [_value concepts_](#value-concepts) section explains the groupings of 496*4947cdc7SCole Fausttypes by the operators they support. 497*4947cdc7SCole Faust 498*4947cdc7SCole Faust 499*4947cdc7SCole Faust### None 500*4947cdc7SCole Faust 501*4947cdc7SCole Faust`None` is a distinguished value used to indicate the absence of any other value. 502*4947cdc7SCole FaustFor example, the result of a call to a function that contains no return statement is `None`. 503*4947cdc7SCole Faust 504*4947cdc7SCole Faust`None` is equal only to itself. Its [type](#type) is `"NoneType"`. 505*4947cdc7SCole FaustThe truth value of `None` is `False`. 506*4947cdc7SCole Faust 507*4947cdc7SCole Faust 508*4947cdc7SCole Faust### Booleans 509*4947cdc7SCole Faust 510*4947cdc7SCole FaustThere are two Boolean values, `True` and `False`, representing the 511*4947cdc7SCole Fausttruth or falsehood of a predicate. The [type](#type) of a Boolean is `"bool"`. 512*4947cdc7SCole Faust 513*4947cdc7SCole FaustBoolean values are typically used as conditions in `if`-statements, 514*4947cdc7SCole Faustalthough any Starlark value used as a condition is implicitly 515*4947cdc7SCole Faustinterpreted as a Boolean. 516*4947cdc7SCole FaustFor example, the values `None`, `0`, `0.0`, and the empty sequences 517*4947cdc7SCole Faust`""`, `()`, `[]`, and `{}` have a truth value of `False`, whereas non-zero 518*4947cdc7SCole Faustnumbers and non-empty sequences have a truth value of `True`. 519*4947cdc7SCole FaustApplication-defined types determine their own truth value. 520*4947cdc7SCole FaustAny value may be explicitly converted to a Boolean using the built-in `bool` 521*4947cdc7SCole Faustfunction. 522*4947cdc7SCole Faust 523*4947cdc7SCole Faust```python 524*4947cdc7SCole Faust1 + 1 == 2 # True 525*4947cdc7SCole Faust2 + 2 == 5 # False 526*4947cdc7SCole Faust 527*4947cdc7SCole Faustif 1 + 1: 528*4947cdc7SCole Faust print("True") 529*4947cdc7SCole Faustelse: 530*4947cdc7SCole Faust print("False") 531*4947cdc7SCole Faust``` 532*4947cdc7SCole Faust 533*4947cdc7SCole Faust### Integers 534*4947cdc7SCole Faust 535*4947cdc7SCole FaustThe Starlark integer type represents integers. Its [type](#type) is `"int"`. 536*4947cdc7SCole Faust 537*4947cdc7SCole FaustIntegers may be positive or negative, and arbitrarily large. 538*4947cdc7SCole FaustInteger arithmetic is exact. 539*4947cdc7SCole FaustIntegers are totally ordered; comparisons follow mathematical 540*4947cdc7SCole Fausttradition. 541*4947cdc7SCole Faust 542*4947cdc7SCole FaustThe `+` and `-` operators perform addition and subtraction, respectively. 543*4947cdc7SCole FaustThe `*` operator performs multiplication. 544*4947cdc7SCole Faust 545*4947cdc7SCole FaustThe `//` and `%` operations on integers compute floored division and 546*4947cdc7SCole Faustremainder of floored division, respectively. 547*4947cdc7SCole FaustIf the signs of the operands differ, the sign of the remainder `x % y` 548*4947cdc7SCole Faustmatches that of the divisor, `y`. 549*4947cdc7SCole FaustFor all finite x and y (y ≠ 0), `(x // y) * y + (x % y) == x`. 550*4947cdc7SCole FaustThe `/` operator implements real division, and 551*4947cdc7SCole Faustyields a `float` result even when its operands are both of type `int`. 552*4947cdc7SCole Faust 553*4947cdc7SCole FaustIntegers, including negative values, may be interpreted as bit vectors. 554*4947cdc7SCole FaustThe `|`, `&`, and `^` operators implement bitwise OR, AND, and XOR, 555*4947cdc7SCole Faustrespectively. The unary `~` operator yields the bitwise inversion of its 556*4947cdc7SCole Faustinteger argument. The `<<` and `>>` operators shift the first argument 557*4947cdc7SCole Faustto the left or right by the number of bits given by the second argument. 558*4947cdc7SCole Faust 559*4947cdc7SCole FaustAny bool, number, or string may be interpreted as an integer by using 560*4947cdc7SCole Faustthe `int` built-in function. 561*4947cdc7SCole Faust 562*4947cdc7SCole FaustAn integer used in a Boolean context is considered true if it is 563*4947cdc7SCole Faustnon-zero. 564*4947cdc7SCole Faust 565*4947cdc7SCole Faust```python 566*4947cdc7SCole Faust100 // 5 * 9 + 32 # 212 567*4947cdc7SCole Faust3 // 2 # 1 568*4947cdc7SCole Faust3 / 2 # 1.5 569*4947cdc7SCole Faust111111111 * 111111111 # 12345678987654321 570*4947cdc7SCole Faust"0x%x" % (0x1234 & 0xf00f) # "0x1004" 571*4947cdc7SCole Faustint("ffff", 16) # 65535, 0xffff 572*4947cdc7SCole Faust``` 573*4947cdc7SCole Faust 574*4947cdc7SCole Faust### Floating-point numbers 575*4947cdc7SCole Faust 576*4947cdc7SCole FaustThe Starlark floating-point data type represents an IEEE 754 577*4947cdc7SCole Faustdouble-precision floating-point number. Its [type](#type) is `"float"`. 578*4947cdc7SCole Faust 579*4947cdc7SCole FaustArithmetic on floats using the `+`, `-`, `*`, `/`, `//`, and `%` 580*4947cdc7SCole Faust operators follows the IEE 754 standard. 581*4947cdc7SCole FaustHowever, computing the division or remainder of division by zero is a dynamic error. 582*4947cdc7SCole Faust 583*4947cdc7SCole FaustAn arithmetic operation applied to a mixture of `float` and `int` 584*4947cdc7SCole Faustoperands works as if the `int` operand is first converted to a 585*4947cdc7SCole Faust`float`. For example, `3.141 + 1` is equivalent to `3.141 + 586*4947cdc7SCole Faustfloat(1)`. 587*4947cdc7SCole FaustThere are two floating-point division operators: 588*4947cdc7SCole Faust`x / y ` yields the floating-point quotient of `x` and `y`, 589*4947cdc7SCole Faustwhereas `x // y` yields `floor(x / y)`, that is, the largest 590*4947cdc7SCole Faustinteger value not greater than `x / y`. 591*4947cdc7SCole FaustAlthough the resulting number is integral, it is represented as a 592*4947cdc7SCole Faust`float` if either operand is a `float`. 593*4947cdc7SCole Faust 594*4947cdc7SCole FaustThe `%` operation computes the remainder of floored division. 595*4947cdc7SCole FaustAs with the corresponding operation on integers, 596*4947cdc7SCole Faustif the signs of the operands differ, the sign of the remainder `x % y` 597*4947cdc7SCole Faustmatches that of the divisor, `y`. 598*4947cdc7SCole Faust 599*4947cdc7SCole FaustThe infinite float values `+Inf` and `-Inf` represent numbers 600*4947cdc7SCole Faustgreater/less than all finite float values. 601*4947cdc7SCole Faust 602*4947cdc7SCole FaustThe non-finite `NaN` value represents the result of dubious operations 603*4947cdc7SCole Faustsuch as `Inf/Inf`. A NaN value compares neither less than, nor 604*4947cdc7SCole Faustgreater than, nor equal to any value, including itself. 605*4947cdc7SCole Faust 606*4947cdc7SCole FaustAll floats other than NaN are totally ordered, so they may be compared 607*4947cdc7SCole Faustusing operators such as `==` and `<`. 608*4947cdc7SCole Faust 609*4947cdc7SCole FaustAny bool, number, or string may be interpreted as a floating-point 610*4947cdc7SCole Faustnumber by using the `float` built-in function. 611*4947cdc7SCole Faust 612*4947cdc7SCole FaustA float used in a Boolean context is considered true if it is 613*4947cdc7SCole Faustnon-zero. 614*4947cdc7SCole Faust 615*4947cdc7SCole Faust```python 616*4947cdc7SCole Faust1.23e45 * 1.23e45 # 1.5129e+90 617*4947cdc7SCole Faust1.111111111111111 * 1.111111111111111 # 1.23457 618*4947cdc7SCole Faust3.0 / 2 # 1.5 619*4947cdc7SCole Faust3 / 2.0 # 1.5 620*4947cdc7SCole Faustfloat(3) / 2 # 1.5 621*4947cdc7SCole Faust3.0 // 2.0 # 1 622*4947cdc7SCole Faust``` 623*4947cdc7SCole Faust 624*4947cdc7SCole Faust### Strings 625*4947cdc7SCole Faust 626*4947cdc7SCole FaustA string represents an immutable sequence of bytes. 627*4947cdc7SCole FaustThe [type](#type) of a string is `"string"`. 628*4947cdc7SCole Faust 629*4947cdc7SCole FaustStrings can represent arbitrary binary data, including zero bytes, but 630*4947cdc7SCole Faustmost strings contain text, encoded by convention using UTF-8. 631*4947cdc7SCole Faust 632*4947cdc7SCole FaustThe built-in `len` function returns the number of bytes in a string. 633*4947cdc7SCole Faust 634*4947cdc7SCole FaustStrings may be concatenated with the `+` operator. 635*4947cdc7SCole Faust 636*4947cdc7SCole FaustThe substring expression `s[i:j]` returns the substring of `s` from 637*4947cdc7SCole Faustindex `i` up to index `j`. The index expression `s[i]` returns the 638*4947cdc7SCole Faust1-byte substring `s[i:i+1]`. 639*4947cdc7SCole Faust 640*4947cdc7SCole FaustStrings are hashable, and thus may be used as keys in a dictionary. 641*4947cdc7SCole Faust 642*4947cdc7SCole FaustStrings are totally ordered lexicographically, so strings may be 643*4947cdc7SCole Faustcompared using operators such as `==` and `<`. 644*4947cdc7SCole Faust 645*4947cdc7SCole FaustStrings are _not_ iterable sequences, so they cannot be used as the operand of 646*4947cdc7SCole Fausta `for`-loop, list comprehension, or any other operation than requires 647*4947cdc7SCole Faustan iterable sequence. 648*4947cdc7SCole FaustTo obtain a view of a string as an iterable sequence of numeric byte 649*4947cdc7SCole Faustvalues, 1-byte substrings, numeric Unicode code points, or 1-code 650*4947cdc7SCole Faustpoint substrings, you must explicitly call one of its four methods: 651*4947cdc7SCole Faust`elems`, `elem_ords`, `codepoints`, or `codepoint_ords`. 652*4947cdc7SCole Faust 653*4947cdc7SCole FaustAny value may formatted as a string using the `str` or `repr` built-in 654*4947cdc7SCole Faustfunctions, the `str % tuple` operator, or the `str.format` method. 655*4947cdc7SCole Faust 656*4947cdc7SCole FaustA string used in a Boolean context is considered true if it is 657*4947cdc7SCole Faustnon-empty. 658*4947cdc7SCole Faust 659*4947cdc7SCole FaustStrings have several built-in methods: 660*4947cdc7SCole Faust 661*4947cdc7SCole Faust* [`capitalize`](#string·capitalize) 662*4947cdc7SCole Faust* [`codepoint_ords`](#string·codepoint_ords) 663*4947cdc7SCole Faust* [`codepoints`](#string·codepoints) 664*4947cdc7SCole Faust* [`count`](#string·count) 665*4947cdc7SCole Faust* [`elem_ords`](#string·elem_ords) 666*4947cdc7SCole Faust* [`elems`](#string·elems) 667*4947cdc7SCole Faust* [`endswith`](#string·endswith) 668*4947cdc7SCole Faust* [`find`](#string·find) 669*4947cdc7SCole Faust* [`format`](#string·format) 670*4947cdc7SCole Faust* [`index`](#string·index) 671*4947cdc7SCole Faust* [`isalnum`](#string·isalnum) 672*4947cdc7SCole Faust* [`isalpha`](#string·isalpha) 673*4947cdc7SCole Faust* [`isdigit`](#string·isdigit) 674*4947cdc7SCole Faust* [`islower`](#string·islower) 675*4947cdc7SCole Faust* [`isspace`](#string·isspace) 676*4947cdc7SCole Faust* [`istitle`](#string·istitle) 677*4947cdc7SCole Faust* [`isupper`](#string·isupper) 678*4947cdc7SCole Faust* [`join`](#string·join) 679*4947cdc7SCole Faust* [`lower`](#string·lower) 680*4947cdc7SCole Faust* [`lstrip`](#string·lstrip) 681*4947cdc7SCole Faust* [`partition`](#string·partition) 682*4947cdc7SCole Faust* [`replace`](#string·replace) 683*4947cdc7SCole Faust* [`rfind`](#string·rfind) 684*4947cdc7SCole Faust* [`rindex`](#string·rindex) 685*4947cdc7SCole Faust* [`rpartition`](#string·rpartition) 686*4947cdc7SCole Faust* [`rsplit`](#string·rsplit) 687*4947cdc7SCole Faust* [`rstrip`](#string·rstrip) 688*4947cdc7SCole Faust* [`split`](#string·split) 689*4947cdc7SCole Faust* [`splitlines`](#string·splitlines) 690*4947cdc7SCole Faust* [`startswith`](#string·startswith) 691*4947cdc7SCole Faust* [`strip`](#string·strip) 692*4947cdc7SCole Faust* [`title`](#string·title) 693*4947cdc7SCole Faust* [`upper`](#string·upper) 694*4947cdc7SCole Faust 695*4947cdc7SCole Faust<b>Implementation note:</b> 696*4947cdc7SCole FaustThe type of a string element varies across implementations. 697*4947cdc7SCole FaustThere is agreement that byte strings, with text conventionally encoded 698*4947cdc7SCole Faustusing UTF-8, is the ideal choice, but the Java implementation treats 699*4947cdc7SCole Fauststrings as sequences of UTF-16 codes and changing it appears 700*4947cdc7SCole Faustintractible; see Google Issue b/36360490. 701*4947cdc7SCole Faust 702*4947cdc7SCole Faust<b>Implementation note:</b> 703*4947cdc7SCole FaustThe Java implementation does not consistently treat strings as 704*4947cdc7SCole Faustiterable; see `testdata/string.star` in the test suite and Google Issue 705*4947cdc7SCole Faustb/34385336 for further details. 706*4947cdc7SCole Faust 707*4947cdc7SCole Faust### Lists 708*4947cdc7SCole Faust 709*4947cdc7SCole FaustA list is a mutable sequence of values. 710*4947cdc7SCole FaustThe [type](#type) of a list is `"list"`. 711*4947cdc7SCole Faust 712*4947cdc7SCole FaustLists are indexable sequences: the elements of a list may be iterated 713*4947cdc7SCole Faustover by `for`-loops, list comprehensions, and various built-in 714*4947cdc7SCole Faustfunctions. 715*4947cdc7SCole Faust 716*4947cdc7SCole FaustList may be constructed using bracketed list notation: 717*4947cdc7SCole Faust 718*4947cdc7SCole Faust```python 719*4947cdc7SCole Faust[] # an empty list 720*4947cdc7SCole Faust[1] # a 1-element list 721*4947cdc7SCole Faust[1, 2] # a 2-element list 722*4947cdc7SCole Faust``` 723*4947cdc7SCole Faust 724*4947cdc7SCole FaustLists can also be constructed from any iterable sequence by using the 725*4947cdc7SCole Faustbuilt-in `list` function. 726*4947cdc7SCole Faust 727*4947cdc7SCole FaustThe built-in `len` function applied to a list returns the number of elements. 728*4947cdc7SCole FaustThe index expression `list[i]` returns the element at index i, 729*4947cdc7SCole Faustand the slice expression `list[i:j]` returns a new list consisting of 730*4947cdc7SCole Faustthe elements at indices from i to j. 731*4947cdc7SCole Faust 732*4947cdc7SCole FaustList elements may be added using the `append` or `extend` methods, 733*4947cdc7SCole Faustremoved using the `remove` method, or reordered by assignments such as 734*4947cdc7SCole Faust`list[i] = list[j]`. 735*4947cdc7SCole Faust 736*4947cdc7SCole FaustThe concatenation operation `x + y` yields a new list containing all 737*4947cdc7SCole Faustthe elements of the two lists x and y. 738*4947cdc7SCole Faust 739*4947cdc7SCole FaustFor most types, `x += y` is equivalent to `x = x + y`, except that it 740*4947cdc7SCole Faustevaluates `x` only once, that is, it allocates a new list to hold 741*4947cdc7SCole Faustthe concatenation of `x` and `y`. 742*4947cdc7SCole FaustHowever, if `x` refers to a list, the statement does not allocate a 743*4947cdc7SCole Faustnew list but instead mutates the original list in place, similar to 744*4947cdc7SCole Faust`x.extend(y)`. 745*4947cdc7SCole Faust 746*4947cdc7SCole FaustLists are not hashable, so may not be used in the keys of a dictionary. 747*4947cdc7SCole Faust 748*4947cdc7SCole FaustA list used in a Boolean context is considered true if it is 749*4947cdc7SCole Faustnon-empty. 750*4947cdc7SCole Faust 751*4947cdc7SCole FaustA [_list comprehension_](#comprehensions) creates a new list whose elements are the 752*4947cdc7SCole Faustresult of some expression applied to each element of another sequence. 753*4947cdc7SCole Faust 754*4947cdc7SCole Faust```python 755*4947cdc7SCole Faust[x*x for x in [1, 2, 3, 4]] # [1, 4, 9, 16] 756*4947cdc7SCole Faust``` 757*4947cdc7SCole Faust 758*4947cdc7SCole FaustA list value has these methods: 759*4947cdc7SCole Faust 760*4947cdc7SCole Faust* [`append`](#list·append) 761*4947cdc7SCole Faust* [`clear`](#list·clear) 762*4947cdc7SCole Faust* [`extend`](#list·extend) 763*4947cdc7SCole Faust* [`index`](#list·index) 764*4947cdc7SCole Faust* [`insert`](#list·insert) 765*4947cdc7SCole Faust* [`pop`](#list·pop) 766*4947cdc7SCole Faust* [`remove`](#list·remove) 767*4947cdc7SCole Faust 768*4947cdc7SCole Faust### Tuples 769*4947cdc7SCole Faust 770*4947cdc7SCole FaustA tuple is an immutable sequence of values. 771*4947cdc7SCole FaustThe [type](#type) of a tuple is `"tuple"`. 772*4947cdc7SCole Faust 773*4947cdc7SCole FaustTuples are constructed using parenthesized list notation: 774*4947cdc7SCole Faust 775*4947cdc7SCole Faust```python 776*4947cdc7SCole Faust() # the empty tuple 777*4947cdc7SCole Faust(1,) # a 1-tuple 778*4947cdc7SCole Faust(1, 2) # a 2-tuple ("pair") 779*4947cdc7SCole Faust(1, 2, 3) # a 3-tuple 780*4947cdc7SCole Faust``` 781*4947cdc7SCole Faust 782*4947cdc7SCole FaustObserve that for the 1-tuple, the trailing comma is necessary to 783*4947cdc7SCole Faustdistinguish it from the parenthesized expression `(1)`. 784*4947cdc7SCole Faust1-tuples are seldom used. 785*4947cdc7SCole Faust 786*4947cdc7SCole FaustStarlark, unlike Python, does not permit a trailing comma to appear in 787*4947cdc7SCole Faustan unparenthesized tuple expression: 788*4947cdc7SCole Faust 789*4947cdc7SCole Faust```python 790*4947cdc7SCole Faustfor k, v, in dict.items(): pass # syntax error at 'in' 791*4947cdc7SCole Faust_ = [(v, k) for k, v, in dict.items()] # syntax error at 'in' 792*4947cdc7SCole Faustf = lambda a, b, : None # syntax error at ':' 793*4947cdc7SCole Faust 794*4947cdc7SCole Faustsorted(3, 1, 4, 1,) # ok 795*4947cdc7SCole Faust[1, 2, 3, ] # ok 796*4947cdc7SCole Faust{1: 2, 3:4, } # ok 797*4947cdc7SCole Faust``` 798*4947cdc7SCole Faust 799*4947cdc7SCole FaustAny iterable sequence may be converted to a tuple by using the 800*4947cdc7SCole Faustbuilt-in `tuple` function. 801*4947cdc7SCole Faust 802*4947cdc7SCole FaustLike lists, tuples are indexed sequences, so they may be indexed and 803*4947cdc7SCole Faustsliced. The index expression `tuple[i]` returns the tuple element at 804*4947cdc7SCole Faustindex i, and the slice expression `tuple[i:j]` returns a sub-sequence 805*4947cdc7SCole Faustof a tuple. 806*4947cdc7SCole Faust 807*4947cdc7SCole FaustTuples are iterable sequences, so they may be used as the operand of a 808*4947cdc7SCole Faust`for`-loop, a list comprehension, or various built-in functions. 809*4947cdc7SCole Faust 810*4947cdc7SCole FaustUnlike lists, tuples cannot be modified. 811*4947cdc7SCole FaustHowever, the mutable elements of a tuple may be modified. 812*4947cdc7SCole Faust 813*4947cdc7SCole FaustTuples are hashable (assuming their elements are hashable), 814*4947cdc7SCole Faustso they may be used as keys of a dictionary. 815*4947cdc7SCole Faust 816*4947cdc7SCole FaustTuples may be concatenated using the `+` operator. 817*4947cdc7SCole Faust 818*4947cdc7SCole FaustA tuple used in a Boolean context is considered true if it is 819*4947cdc7SCole Faustnon-empty. 820*4947cdc7SCole Faust 821*4947cdc7SCole Faust 822*4947cdc7SCole Faust### Dictionaries 823*4947cdc7SCole Faust 824*4947cdc7SCole FaustA dictionary is a mutable mapping from keys to values. 825*4947cdc7SCole FaustThe [type](#type) of a dictionary is `"dict"`. 826*4947cdc7SCole Faust 827*4947cdc7SCole FaustDictionaries provide constant-time operations to insert an element, to 828*4947cdc7SCole Faustlook up the value for a key, or to remove an element. Dictionaries 829*4947cdc7SCole Faustare implemented using hash tables, so keys must be hashable. Hashable 830*4947cdc7SCole Faustvalues include `None`, Booleans, numbers, and strings, and tuples 831*4947cdc7SCole Faustcomposed from hashable values. Most mutable values, such as lists, 832*4947cdc7SCole Faustdictionaries, and sets, are not hashable, even when frozen. 833*4947cdc7SCole FaustAttempting to use a non-hashable value as a key in a dictionary 834*4947cdc7SCole Faustresults in a dynamic error. 835*4947cdc7SCole Faust 836*4947cdc7SCole FaustA [dictionary expression](#dictionary-expressions) specifies a 837*4947cdc7SCole Faustdictionary as a set of key/value pairs enclosed in braces: 838*4947cdc7SCole Faust 839*4947cdc7SCole Faust```python 840*4947cdc7SCole Faustcoins = { 841*4947cdc7SCole Faust "penny": 1, 842*4947cdc7SCole Faust "nickel": 5, 843*4947cdc7SCole Faust "dime": 10, 844*4947cdc7SCole Faust "quarter": 25, 845*4947cdc7SCole Faust} 846*4947cdc7SCole Faust``` 847*4947cdc7SCole Faust 848*4947cdc7SCole FaustThe expression `d[k]`, where `d` is a dictionary and `k` is a key, 849*4947cdc7SCole Faustretrieves the value associated with the key. If the dictionary 850*4947cdc7SCole Faustcontains no such item, the operation fails: 851*4947cdc7SCole Faust 852*4947cdc7SCole Faust```python 853*4947cdc7SCole Faustcoins["penny"] # 1 854*4947cdc7SCole Faustcoins["dime"] # 10 855*4947cdc7SCole Faustcoins["silver dollar"] # error: key not found 856*4947cdc7SCole Faust``` 857*4947cdc7SCole Faust 858*4947cdc7SCole FaustThe number of items in a dictionary `d` is given by `len(d)`. 859*4947cdc7SCole FaustA key/value item may be added to a dictionary, or updated if the key 860*4947cdc7SCole Faustis already present, by using `d[k]` on the left side of an assignment: 861*4947cdc7SCole Faust 862*4947cdc7SCole Faust```python 863*4947cdc7SCole Faustlen(coins) # 4 864*4947cdc7SCole Faustcoins["shilling"] = 20 865*4947cdc7SCole Faustlen(coins) # 5, item was inserted 866*4947cdc7SCole Faustcoins["shilling"] = 5 867*4947cdc7SCole Faustlen(coins) # 5, existing item was updated 868*4947cdc7SCole Faust``` 869*4947cdc7SCole Faust 870*4947cdc7SCole FaustA dictionary can also be constructed using a [dictionary 871*4947cdc7SCole Faustcomprehension](#comprehension), which evaluates a pair of expressions, 872*4947cdc7SCole Faustthe _key_ and the _value_, for every element of another iterable such 873*4947cdc7SCole Faustas a list. This example builds a mapping from each word to its length 874*4947cdc7SCole Faustin bytes: 875*4947cdc7SCole Faust 876*4947cdc7SCole Faust```python 877*4947cdc7SCole Faustwords = ["able", "baker", "charlie"] 878*4947cdc7SCole Faust{x: len(x) for x in words} # {"charlie": 7, "baker": 5, "able": 4} 879*4947cdc7SCole Faust``` 880*4947cdc7SCole Faust 881*4947cdc7SCole FaustDictionaries are iterable sequences, so they may be used as the 882*4947cdc7SCole Faustoperand of a `for`-loop, a list comprehension, or various built-in 883*4947cdc7SCole Faustfunctions. 884*4947cdc7SCole FaustIteration yields the dictionary's keys in the order in which they were 885*4947cdc7SCole Faustinserted; updating the value associated with an existing key does not 886*4947cdc7SCole Faustaffect the iteration order. 887*4947cdc7SCole Faust 888*4947cdc7SCole Faust```python 889*4947cdc7SCole Faustx = dict([("a", 1), ("b", 2)]) # {"a": 1, "b": 2} 890*4947cdc7SCole Faustx.update([("a", 3), ("c", 4)]) # {"a": 3, "b": 2, "c": 4} 891*4947cdc7SCole Faust``` 892*4947cdc7SCole Faust 893*4947cdc7SCole Faust```python 894*4947cdc7SCole Faustfor name in coins: 895*4947cdc7SCole Faust print(name, coins[name]) # prints "quarter 25", "dime 10", ... 896*4947cdc7SCole Faust``` 897*4947cdc7SCole Faust 898*4947cdc7SCole FaustLike all mutable values in Starlark, a dictionary can be frozen, and 899*4947cdc7SCole Faustonce frozen, all subsequent operations that attempt to update it will 900*4947cdc7SCole Faustfail. 901*4947cdc7SCole Faust 902*4947cdc7SCole FaustA dictionary used in a Boolean context is considered true if it is 903*4947cdc7SCole Faustnon-empty. 904*4947cdc7SCole Faust 905*4947cdc7SCole FaustDictionaries may be compared for equality using `==` and `!=`. Two 906*4947cdc7SCole Faustdictionaries compare equal if they contain the same number of items 907*4947cdc7SCole Faustand each key/value item (k, v) found in one dictionary is also present 908*4947cdc7SCole Faustin the other. Dictionaries are not ordered; it is an error to compare 909*4947cdc7SCole Fausttwo dictionaries with `<`. 910*4947cdc7SCole Faust 911*4947cdc7SCole Faust 912*4947cdc7SCole FaustA dictionary value has these methods: 913*4947cdc7SCole Faust 914*4947cdc7SCole Faust* [`clear`](#dict·clear) 915*4947cdc7SCole Faust* [`get`](#dict·get) 916*4947cdc7SCole Faust* [`items`](#dict·items) 917*4947cdc7SCole Faust* [`keys`](#dict·keys) 918*4947cdc7SCole Faust* [`pop`](#dict·pop) 919*4947cdc7SCole Faust* [`popitem`](#dict·popitem) 920*4947cdc7SCole Faust* [`setdefault`](#dict·setdefault) 921*4947cdc7SCole Faust* [`update`](#dict·update) 922*4947cdc7SCole Faust* [`values`](#dict·values) 923*4947cdc7SCole Faust 924*4947cdc7SCole Faust### Sets 925*4947cdc7SCole Faust 926*4947cdc7SCole FaustA set is a mutable set of values. 927*4947cdc7SCole FaustThe [type](#type) of a set is `"set"`. 928*4947cdc7SCole Faust 929*4947cdc7SCole FaustLike dictionaries, sets are implemented using hash tables, so the 930*4947cdc7SCole Faustelements of a set must be hashable. 931*4947cdc7SCole Faust 932*4947cdc7SCole FaustSets may be compared for equality or inequality using `==` and `!=`. 933*4947cdc7SCole FaustTwo sets compare equal if they contain the same elements. 934*4947cdc7SCole Faust 935*4947cdc7SCole FaustSets are iterable sequences, so they may be used as the operand of a 936*4947cdc7SCole Faust`for`-loop, a list comprehension, or various built-in functions. 937*4947cdc7SCole FaustIteration yields the set's elements in the order in which they were 938*4947cdc7SCole Faustinserted. 939*4947cdc7SCole Faust 940*4947cdc7SCole FaustThe binary `|` and `&` operators compute union and intersection when 941*4947cdc7SCole Faustapplied to sets. The right operand of the `|` operator may be any 942*4947cdc7SCole Faustiterable value. The binary `in` operator performs a set membership 943*4947cdc7SCole Fausttest when its right operand is a set. 944*4947cdc7SCole Faust 945*4947cdc7SCole FaustThe binary `^` operator performs symmetric difference of two sets. 946*4947cdc7SCole Faust 947*4947cdc7SCole FaustSets are instantiated by calling the built-in `set` function, which 948*4947cdc7SCole Faustreturns a set containing all the elements of its optional argument, 949*4947cdc7SCole Faustwhich must be an iterable sequence. Sets have no literal syntax. 950*4947cdc7SCole Faust 951*4947cdc7SCole FaustThe only method of a set is `union`, which is equivalent to the `|` operator. 952*4947cdc7SCole Faust 953*4947cdc7SCole FaustA set used in a Boolean context is considered true if it is non-empty. 954*4947cdc7SCole Faust 955*4947cdc7SCole Faust<b>Implementation note:</b> 956*4947cdc7SCole FaustThe Go implementation of Starlark requires the `-set` flag to 957*4947cdc7SCole Faustenable support for sets. 958*4947cdc7SCole FaustThe Java implementation does not support sets. 959*4947cdc7SCole Faust 960*4947cdc7SCole Faust 961*4947cdc7SCole Faust### Functions 962*4947cdc7SCole Faust 963*4947cdc7SCole FaustA function value represents a function defined in Starlark. 964*4947cdc7SCole FaustIts [type](#type) is `"function"`. 965*4947cdc7SCole FaustA function value used in a Boolean context is always considered true. 966*4947cdc7SCole Faust 967*4947cdc7SCole FaustFunctions defined by a [`def` statement](#function-definitions) are named; 968*4947cdc7SCole Faustfunctions defined by a [`lambda` expression](#lambda-expressions) are anonymous. 969*4947cdc7SCole Faust 970*4947cdc7SCole FaustFunction definitions may be nested, and an inner function may refer to a local variable of an outer function. 971*4947cdc7SCole Faust 972*4947cdc7SCole FaustA function definition defines zero or more named parameters. 973*4947cdc7SCole FaustStarlark has a rich mechanism for passing arguments to functions. 974*4947cdc7SCole Faust 975*4947cdc7SCole Faust<!-- TODO break up this explanation into caller-side and callee-side 976*4947cdc7SCole Faust parts, and put the former under function calls and the latter 977*4947cdc7SCole Faust under function definitions. Also try to convey that the Callable 978*4947cdc7SCole Faust interface sees the flattened-out args and kwargs and that's what 979*4947cdc7SCole Faust built-ins get. 980*4947cdc7SCole Faust--> 981*4947cdc7SCole Faust 982*4947cdc7SCole FaustThe example below shows a definition and call of a function of two 983*4947cdc7SCole Faustrequired parameters, `x` and `y`. 984*4947cdc7SCole Faust 985*4947cdc7SCole Faust```python 986*4947cdc7SCole Faustdef idiv(x, y): 987*4947cdc7SCole Faust return x // y 988*4947cdc7SCole Faust 989*4947cdc7SCole Faustidiv(6, 3) # 2 990*4947cdc7SCole Faust``` 991*4947cdc7SCole Faust 992*4947cdc7SCole FaustA call may provide arguments to function parameters either by 993*4947cdc7SCole Faustposition, as in the example above, or by name, as in first two calls 994*4947cdc7SCole Faustbelow, or by a mixture of the two forms, as in the third call below. 995*4947cdc7SCole FaustAll the positional arguments must precede all the named arguments. 996*4947cdc7SCole FaustNamed arguments may improve clarity, especially in functions of 997*4947cdc7SCole Faustseveral parameters. 998*4947cdc7SCole Faust 999*4947cdc7SCole Faust```python 1000*4947cdc7SCole Faustidiv(x=6, y=3) # 2 1001*4947cdc7SCole Faustidiv(y=3, x=6) # 2 1002*4947cdc7SCole Faust 1003*4947cdc7SCole Faustidiv(6, y=3) # 2 1004*4947cdc7SCole Faust``` 1005*4947cdc7SCole Faust 1006*4947cdc7SCole Faust<b>Optional parameters:</b> A parameter declaration may specify a 1007*4947cdc7SCole Faustdefault value using `name=value` syntax; such a parameter is 1008*4947cdc7SCole Faust_optional_. The default value expression is evaluated during 1009*4947cdc7SCole Faustexecution of the `def` statement or evaluation of the `lambda` 1010*4947cdc7SCole Faustexpression, and the default value forms part of the function value. 1011*4947cdc7SCole FaustAll optional parameters must follow all non-optional parameters. 1012*4947cdc7SCole FaustA function call may omit arguments for any suffix of the optional 1013*4947cdc7SCole Faustparameters; the effective values of those arguments are supplied by 1014*4947cdc7SCole Faustthe function's parameter defaults. 1015*4947cdc7SCole Faust 1016*4947cdc7SCole Faust```python 1017*4947cdc7SCole Faustdef f(x, y=3): 1018*4947cdc7SCole Faust return x, y 1019*4947cdc7SCole Faust 1020*4947cdc7SCole Faustf(1, 2) # (1, 2) 1021*4947cdc7SCole Faustf(1) # (1, 3) 1022*4947cdc7SCole Faust``` 1023*4947cdc7SCole Faust 1024*4947cdc7SCole FaustIf a function parameter's default value is a mutable expression, 1025*4947cdc7SCole Faustmodifications to the value during one call may be observed by 1026*4947cdc7SCole Faustsubsequent calls. 1027*4947cdc7SCole FaustBeware of this when using lists or dicts as default values. 1028*4947cdc7SCole FaustIf the function becomes frozen, its parameters' default values become 1029*4947cdc7SCole Faustfrozen too. 1030*4947cdc7SCole Faust 1031*4947cdc7SCole Faust```python 1032*4947cdc7SCole Faust# module a.star 1033*4947cdc7SCole Faustdef f(x, list=[]): 1034*4947cdc7SCole Faust list.append(x) 1035*4947cdc7SCole Faust return list 1036*4947cdc7SCole Faust 1037*4947cdc7SCole Faustf(4, [1,2,3]) # [1, 2, 3, 4] 1038*4947cdc7SCole Faustf(1) # [1] 1039*4947cdc7SCole Faustf(2) # [1, 2], not [2]! 1040*4947cdc7SCole Faust 1041*4947cdc7SCole Faust# module b.star 1042*4947cdc7SCole Faustload("a.star", "f") 1043*4947cdc7SCole Faustf(3) # error: cannot append to frozen list 1044*4947cdc7SCole Faust``` 1045*4947cdc7SCole Faust 1046*4947cdc7SCole Faust<b>Variadic functions:</b> Some functions allow callers to provide an 1047*4947cdc7SCole Faustarbitrary number of arguments. 1048*4947cdc7SCole FaustAfter all required and optional parameters, a function definition may 1049*4947cdc7SCole Faustspecify a _variadic arguments_ or _varargs_ parameter, indicated by a 1050*4947cdc7SCole Fauststar preceding the parameter name: `*args`. 1051*4947cdc7SCole FaustAny surplus positional arguments provided by the caller are formed 1052*4947cdc7SCole Faustinto a tuple and assigned to the `args` parameter. 1053*4947cdc7SCole Faust 1054*4947cdc7SCole Faust```python 1055*4947cdc7SCole Faustdef f(x, y, *args): 1056*4947cdc7SCole Faust return x, y, args 1057*4947cdc7SCole Faust 1058*4947cdc7SCole Faustf(1, 2) # (1, 2, ()) 1059*4947cdc7SCole Faustf(1, 2, 3, 4) # (1, 2, (3, 4)) 1060*4947cdc7SCole Faust``` 1061*4947cdc7SCole Faust 1062*4947cdc7SCole Faust<b>Keyword-variadic functions:</b> Some functions allow callers to 1063*4947cdc7SCole Faustprovide an arbitrary sequence of `name=value` keyword arguments. 1064*4947cdc7SCole FaustA function definition may include a final _keyword arguments_ or 1065*4947cdc7SCole Faust_kwargs_ parameter, indicated by a double-star preceding the parameter 1066*4947cdc7SCole Faustname: `**kwargs`. 1067*4947cdc7SCole FaustAny surplus named arguments that do not correspond to named parameters 1068*4947cdc7SCole Faustare collected in a new dictionary and assigned to the `kwargs` parameter: 1069*4947cdc7SCole Faust 1070*4947cdc7SCole Faust```python 1071*4947cdc7SCole Faustdef f(x, y, **kwargs): 1072*4947cdc7SCole Faust return x, y, kwargs 1073*4947cdc7SCole Faust 1074*4947cdc7SCole Faustf(1, 2) # (1, 2, {}) 1075*4947cdc7SCole Faustf(x=2, y=1) # (2, 1, {}) 1076*4947cdc7SCole Faustf(x=2, y=1, z=3) # (2, 1, {"z": 3}) 1077*4947cdc7SCole Faust``` 1078*4947cdc7SCole Faust 1079*4947cdc7SCole FaustIt is a static error if any two parameters of a function have the same name. 1080*4947cdc7SCole Faust 1081*4947cdc7SCole FaustJust as a function definition may accept an arbitrary number of 1082*4947cdc7SCole Faustpositional or named arguments, a function call may provide an 1083*4947cdc7SCole Faustarbitrary number of positional or named arguments supplied by a 1084*4947cdc7SCole Faustlist or dictionary: 1085*4947cdc7SCole Faust 1086*4947cdc7SCole Faust```python 1087*4947cdc7SCole Faustdef f(a, b, c=5): 1088*4947cdc7SCole Faust return a * b + c 1089*4947cdc7SCole Faust 1090*4947cdc7SCole Faustf(*[2, 3]) # 11 1091*4947cdc7SCole Faustf(*[2, 3, 7]) # 13 1092*4947cdc7SCole Faustf(*[2]) # error: f takes at least 2 arguments (1 given) 1093*4947cdc7SCole Faust 1094*4947cdc7SCole Faustf(**dict(b=3, a=2)) # 11 1095*4947cdc7SCole Faustf(**dict(c=7, a=2, b=3)) # 13 1096*4947cdc7SCole Faustf(**dict(a=2)) # error: f takes at least 2 arguments (1 given) 1097*4947cdc7SCole Faustf(**dict(d=4)) # error: f got unexpected keyword argument "d" 1098*4947cdc7SCole Faust``` 1099*4947cdc7SCole Faust 1100*4947cdc7SCole FaustOnce the parameters have been successfully bound to the arguments 1101*4947cdc7SCole Faustsupplied by the call, the sequence of statements that comprise the 1102*4947cdc7SCole Faustfunction body is executed. 1103*4947cdc7SCole Faust 1104*4947cdc7SCole FaustIt is a static error if a function call has two named arguments of the 1105*4947cdc7SCole Faustsame name, such as `f(x=1, x=2)`. A call that provides a `**kwargs` 1106*4947cdc7SCole Faustargument may yet have two values for the same name, such as 1107*4947cdc7SCole Faust`f(x=1, **dict(x=2))`. This results in a dynamic error. 1108*4947cdc7SCole Faust 1109*4947cdc7SCole FaustFunction arguments are evaluated in the order they appear in the call. 1110*4947cdc7SCole Faust<!-- see https://github.com/bazelbuild/starlark/issues/13 --> 1111*4947cdc7SCole Faust 1112*4947cdc7SCole FaustUnlike Python, Starlark does not allow more than one `*args` argument in a 1113*4947cdc7SCole Faustcall, and if a `*args` argument is present it must appear after all 1114*4947cdc7SCole Faustpositional and named arguments. 1115*4947cdc7SCole Faust 1116*4947cdc7SCole FaustThe final argument to a function call may be followed by a trailing comma. 1117*4947cdc7SCole Faust 1118*4947cdc7SCole FaustA function call completes normally after the execution of either a 1119*4947cdc7SCole Faust`return` statement, or of the last statement in the function body. 1120*4947cdc7SCole FaustThe result of the function call is the value of the return statement's 1121*4947cdc7SCole Faustoperand, or `None` if the return statement had no operand or if the 1122*4947cdc7SCole Faustfunction completeted without executing a return statement. 1123*4947cdc7SCole Faust 1124*4947cdc7SCole Faust```python 1125*4947cdc7SCole Faustdef f(x): 1126*4947cdc7SCole Faust if x == 0: 1127*4947cdc7SCole Faust return 1128*4947cdc7SCole Faust if x < 0: 1129*4947cdc7SCole Faust return -x 1130*4947cdc7SCole Faust print(x) 1131*4947cdc7SCole Faust 1132*4947cdc7SCole Faustf(1) # returns None after printing "1" 1133*4947cdc7SCole Faustf(0) # returns None without printing 1134*4947cdc7SCole Faustf(-1) # returns 1 without printing 1135*4947cdc7SCole Faust``` 1136*4947cdc7SCole Faust 1137*4947cdc7SCole Faust<b>Implementation note:</b> 1138*4947cdc7SCole FaustThe Go implementation of Starlark requires the `-recursion` 1139*4947cdc7SCole Faustflag to allow recursive functions. 1140*4947cdc7SCole Faust 1141*4947cdc7SCole Faust 1142*4947cdc7SCole FaustIf the `-recursion` flag is not specified it is a dynamic error for a 1143*4947cdc7SCole Faustfunction to call itself or another function value with the same 1144*4947cdc7SCole Faustdeclaration. 1145*4947cdc7SCole Faust 1146*4947cdc7SCole Faust```python 1147*4947cdc7SCole Faustdef fib(x): 1148*4947cdc7SCole Faust if x < 2: 1149*4947cdc7SCole Faust return x 1150*4947cdc7SCole Faust return fib(x-2) + fib(x-1) # dynamic error: function fib called recursively 1151*4947cdc7SCole Faust 1152*4947cdc7SCole Faustfib(5) 1153*4947cdc7SCole Faust``` 1154*4947cdc7SCole Faust 1155*4947cdc7SCole FaustThis rule, combined with the invariant that all loops are iterations 1156*4947cdc7SCole Faustover finite sequences, implies that Starlark programs can not be 1157*4947cdc7SCole FaustTuring complete unless the `-recursion` flag is specified. 1158*4947cdc7SCole Faust 1159*4947cdc7SCole Faust<!-- This rule is supposed to deter people from abusing Starlark for 1160*4947cdc7SCole Faust inappropriate uses, especially in the build system. 1161*4947cdc7SCole Faust It may work for that purpose, but it doesn't stop Starlark programs 1162*4947cdc7SCole Faust from consuming too much time or space. Perhaps it should be a 1163*4947cdc7SCole Faust dialect option. 1164*4947cdc7SCole Faust--> 1165*4947cdc7SCole Faust 1166*4947cdc7SCole Faust 1167*4947cdc7SCole Faust 1168*4947cdc7SCole Faust### Built-in functions 1169*4947cdc7SCole Faust 1170*4947cdc7SCole FaustA built-in function is a function or method implemented in Go by the interpreter 1171*4947cdc7SCole Faustor the application into which the interpreter is embedded. 1172*4947cdc7SCole Faust 1173*4947cdc7SCole FaustThe [type](#type) of a built-in function is `"builtin_function_or_method"`. 1174*4947cdc7SCole Faust 1175*4947cdc7SCole FaustA built-in function value used in a Boolean context is always considered true. 1176*4947cdc7SCole Faust 1177*4947cdc7SCole FaustMany built-in functions are predeclared in the environment 1178*4947cdc7SCole Faust(see [Name Resolution](#name-resolution)). 1179*4947cdc7SCole FaustSome built-in functions such as `len` are _universal_, that is, 1180*4947cdc7SCole Faustavailable to all Starlark programs. 1181*4947cdc7SCole FaustThe host application may predeclare additional built-in functions 1182*4947cdc7SCole Faustin the environment of a specific module. 1183*4947cdc7SCole Faust 1184*4947cdc7SCole FaustExcept where noted, built-in functions accept only positional arguments. 1185*4947cdc7SCole FaustThe parameter names serve merely as documentation. 1186*4947cdc7SCole Faust 1187*4947cdc7SCole FaustMost built-in functions that have a Boolean parameter require its 1188*4947cdc7SCole Faustargument to be `True` or `False`. Unlike `if` statements, other values 1189*4947cdc7SCole Faustare not implicitly converted to their truth value and instead cause a 1190*4947cdc7SCole Faustdynamic error. 1191*4947cdc7SCole Faust 1192*4947cdc7SCole Faust 1193*4947cdc7SCole Faust## Name binding and variables 1194*4947cdc7SCole Faust 1195*4947cdc7SCole FaustAfter a Starlark file is parsed, but before its execution begins, the 1196*4947cdc7SCole FaustStarlark interpreter checks statically that the program is well formed. 1197*4947cdc7SCole FaustFor example, `break` and `continue` statements may appear only within 1198*4947cdc7SCole Fausta loop; a `return` statement may appear only within a 1199*4947cdc7SCole Faustfunction; and `load` statements may appear only outside any function. 1200*4947cdc7SCole Faust 1201*4947cdc7SCole Faust_Name resolution_ is the static checking process that 1202*4947cdc7SCole Faustresolves names to variable bindings. 1203*4947cdc7SCole FaustDuring execution, names refer to variables. Statically, names denote 1204*4947cdc7SCole Faustplaces in the code where variables are created; these places are 1205*4947cdc7SCole Faustcalled _bindings_. A name may denote different bindings at different 1206*4947cdc7SCole Faustplaces in the program. The region of text in which a particular name 1207*4947cdc7SCole Faustrefers to the same binding is called that binding's _scope_. 1208*4947cdc7SCole Faust 1209*4947cdc7SCole FaustFour Starlark constructs bind names, as illustrated in the example below: 1210*4947cdc7SCole Faust`load` statements (`a` and `b`), 1211*4947cdc7SCole Faust`def` statements (`c`), 1212*4947cdc7SCole Faustfunction parameters (`d`), 1213*4947cdc7SCole Faustand assignments (`e`, `h`, including the augmented assignment `e += 1`). 1214*4947cdc7SCole FaustVariables may be assigned or re-assigned explicitly (`e`, `h`), or implicitly, as 1215*4947cdc7SCole Faustin a `for`-loop (`f`) or comprehension (`g`, `i`). 1216*4947cdc7SCole Faust 1217*4947cdc7SCole Faust```python 1218*4947cdc7SCole Faustload("lib.star", "a", b="B") 1219*4947cdc7SCole Faust 1220*4947cdc7SCole Faustdef c(d): 1221*4947cdc7SCole Faust e = 0 1222*4947cdc7SCole Faust for f in d: 1223*4947cdc7SCole Faust print([True for g in f]) 1224*4947cdc7SCole Faust e += 1 1225*4947cdc7SCole Faust 1226*4947cdc7SCole Fausth = [2*i for i in a] 1227*4947cdc7SCole Faust``` 1228*4947cdc7SCole Faust 1229*4947cdc7SCole FaustThe environment of a Starlark program is structured as a tree of 1230*4947cdc7SCole Faust_lexical blocks_, each of which may contain name bindings. 1231*4947cdc7SCole FaustThe tree of blocks is parallel to the syntax tree. 1232*4947cdc7SCole FaustBlocks are of five kinds. 1233*4947cdc7SCole Faust 1234*4947cdc7SCole Faust<!-- Avoid the term "built-in" block since that's also a type. --> 1235*4947cdc7SCole FaustAt the root of the tree is the _predeclared_ block, 1236*4947cdc7SCole Faustwhich binds several names implicitly. 1237*4947cdc7SCole FaustThe set of predeclared names includes the universal 1238*4947cdc7SCole Faustconstant values `None`, `True`, and `False`, and 1239*4947cdc7SCole Faustvarious built-in functions such as `len` and `list`; 1240*4947cdc7SCole Faustthese functions are immutable and stateless. 1241*4947cdc7SCole FaustAn application may pre-declare additional names 1242*4947cdc7SCole Faustto provide domain-specific functions to that file, for example. 1243*4947cdc7SCole FaustThese additional functions may have side effects on the application. 1244*4947cdc7SCole FaustStarlark programs cannot change the set of predeclared bindings 1245*4947cdc7SCole Faustor assign new values to them. 1246*4947cdc7SCole Faust 1247*4947cdc7SCole FaustNested beneath the predeclared block is the _module_ block, 1248*4947cdc7SCole Faustwhich contains the bindings of the current module. 1249*4947cdc7SCole FaustBindings in the module block (such as `c`, and `h` in the 1250*4947cdc7SCole Faustexample) are called _global_ and may be visible to other modules. 1251*4947cdc7SCole FaustThe module block is empty at the start of the file 1252*4947cdc7SCole Faustand is populated by top-level binding statements. 1253*4947cdc7SCole Faust 1254*4947cdc7SCole FaustNested beneath the module block is the _file_ block, 1255*4947cdc7SCole Faustwhich contains bindings local to the current file. 1256*4947cdc7SCole FaustNames in this block (such as `a` and `b` in the example) 1257*4947cdc7SCole Faustare bound only by `load` statements. 1258*4947cdc7SCole FaustThe sets of names bound in the file block and in the module block do not overlap: 1259*4947cdc7SCole Faustit is an error for a load statement to bind the name of a global, 1260*4947cdc7SCole Faustor for a top-level statement to bind a name bound by a load statement. 1261*4947cdc7SCole Faust 1262*4947cdc7SCole FaustA file block contains a _function_ block for each top-level 1263*4947cdc7SCole Faustfunction, and a _comprehension_ block for each top-level comprehension. 1264*4947cdc7SCole FaustBindings in either of these kinds of block, 1265*4947cdc7SCole Faustand in the file block itself, are called _local_. 1266*4947cdc7SCole Faust(In the example, the bindings for `e`, `f`, `g`, and `i` are all local.) 1267*4947cdc7SCole FaustAdditional functions and comprehensions, and their blocks, may be 1268*4947cdc7SCole Faustnested in any order, to any depth. 1269*4947cdc7SCole Faust 1270*4947cdc7SCole FaustIf name is bound anywhere within a block, all uses of the name within 1271*4947cdc7SCole Faustthe block are treated as references to that binding, 1272*4947cdc7SCole Fausteven if the use appears before the binding. 1273*4947cdc7SCole FaustThis is true even at the top level, unlike Python. 1274*4947cdc7SCole FaustThe binding of `y` on the last line of the example below makes `y` 1275*4947cdc7SCole Faustlocal to the function `hello`, so the use of `y` in the print 1276*4947cdc7SCole Fauststatement also refers to the local `y`, even though it appears 1277*4947cdc7SCole Faustearlier. 1278*4947cdc7SCole Faust 1279*4947cdc7SCole Faust```python 1280*4947cdc7SCole Fausty = "goodbye" 1281*4947cdc7SCole Faust 1282*4947cdc7SCole Faustdef hello(): 1283*4947cdc7SCole Faust for x in (1, 2): 1284*4947cdc7SCole Faust if x == 2: 1285*4947cdc7SCole Faust print(y) # prints "hello" 1286*4947cdc7SCole Faust if x == 1: 1287*4947cdc7SCole Faust y = "hello" 1288*4947cdc7SCole Faust``` 1289*4947cdc7SCole FaustIt is a dynamic error to evaluate a reference to a local variable 1290*4947cdc7SCole Faustbefore it has been bound: 1291*4947cdc7SCole Faust 1292*4947cdc7SCole Faust```python 1293*4947cdc7SCole Faustdef f(): 1294*4947cdc7SCole Faust print(x) # dynamic error: local variable x referenced before assignment 1295*4947cdc7SCole Faust x = "hello" 1296*4947cdc7SCole Faust``` 1297*4947cdc7SCole Faust 1298*4947cdc7SCole FaustThe same is true for global variables: 1299*4947cdc7SCole Faust 1300*4947cdc7SCole Faust```python 1301*4947cdc7SCole Faustprint(x) # dynamic error: global variable x referenced before assignment 1302*4947cdc7SCole Faustx = "hello" 1303*4947cdc7SCole Faust``` 1304*4947cdc7SCole Faust 1305*4947cdc7SCole FaustThe same is also true for nested loops in comprehensions. 1306*4947cdc7SCole FaustIn the (unnatural) examples below, the scope of the variables `x`, `y`, 1307*4947cdc7SCole Faustand `z` is the entire compehension block, except the operand of the first 1308*4947cdc7SCole Faustloop (`[]` or `[1]`), which is resolved in the enclosing environment. 1309*4947cdc7SCole FaustThe second loop may thus refer to variables defined by the third (`z`), 1310*4947cdc7SCole Fausteven though such references would fail if actually executed. 1311*4947cdc7SCole Faust 1312*4947cdc7SCole Faust``` 1313*4947cdc7SCole Faust[1//0 for x in [] for y in z for z in ()] # [] (no error) 1314*4947cdc7SCole Faust[1//0 for x in [1] for y in z for z in ()] # dynamic error: local variable z referenced before assignment 1315*4947cdc7SCole Faust``` 1316*4947cdc7SCole Faust 1317*4947cdc7SCole Faust 1318*4947cdc7SCole Faust<!-- This is similar to Python[23]. Presumed rational: it resembles 1319*4947cdc7SCole Faust the desugaring to nested loop statements, in which the scope 1320*4947cdc7SCole Faust of all three variables is the entire enclosing function, 1321*4947cdc7SCole Faust including the portion before the bindings. 1322*4947cdc7SCole Faust 1323*4947cdc7SCole Faust def f(): 1324*4947cdc7SCole Faust ... 1325*4947cdc7SCole Faust for x in []: 1326*4947cdc7SCole Faust for y in z: 1327*4947cdc7SCole Faust for z in (): 1328*4947cdc7SCole Faust 1//0 1329*4947cdc7SCole Faust--> 1330*4947cdc7SCole Faust 1331*4947cdc7SCole FaustIt is a static error to refer to a name that has no binding at all. 1332*4947cdc7SCole Faust``` 1333*4947cdc7SCole Faustdef f(): 1334*4947cdc7SCole Faust if False: 1335*4947cdc7SCole Faust g() # static error: undefined: g 1336*4947cdc7SCole Faust``` 1337*4947cdc7SCole Faust(This behavior differs from Python, which treats such references as global, 1338*4947cdc7SCole Faustand thus does not report an error until the expression is evaluated.) 1339*4947cdc7SCole Faust 1340*4947cdc7SCole Faust<!-- Consequently, the REPL, which consumes one compound statement at a time, 1341*4947cdc7SCole Faust cannot resolve forward references such as 1342*4947cdc7SCole Faust def f(): return K 1343*4947cdc7SCole Faust K = 1 1344*4947cdc7SCole Faust because the first chunk has an unresolved reference to K. 1345*4947cdc7SCole Faust--> 1346*4947cdc7SCole Faust 1347*4947cdc7SCole FaustIt is a static error to bind a global variable already explicitly bound in the file: 1348*4947cdc7SCole Faust 1349*4947cdc7SCole Faust```python 1350*4947cdc7SCole Faustx = 1 1351*4947cdc7SCole Faustx = 2 # static error: cannot reassign global x declared on line 1 1352*4947cdc7SCole Faust``` 1353*4947cdc7SCole Faust 1354*4947cdc7SCole Faust<!-- The above rule, and the rule that forbids if-statements and loops at 1355*4947cdc7SCole Faust top level, exist to ensure that there is exactly one statement 1356*4947cdc7SCole Faust that binds each global variable, which makes cross-referenced 1357*4947cdc7SCole Faust documentation more useful, the designers assure me, but 1358*4947cdc7SCole Faust I am skeptical that it's worth the trouble. --> 1359*4947cdc7SCole Faust 1360*4947cdc7SCole FaustIf a name was pre-bound by the application, the Starlark program may 1361*4947cdc7SCole Faustexplicitly bind it, but only once. 1362*4947cdc7SCole Faust 1363*4947cdc7SCole FaustAn augmented assignment statement such as `x += y` is considered both a 1364*4947cdc7SCole Faustreference to `x` and a binding use of `x`, so it may not be used at 1365*4947cdc7SCole Fausttop level. 1366*4947cdc7SCole Faust 1367*4947cdc7SCole Faust<b>Implementation note:</b> 1368*4947cdc7SCole FaustThe Go implementation of Starlark permits augmented assignments to appear 1369*4947cdc7SCole Faustat top level if the `-globalreassign` flag is enabled. 1370*4947cdc7SCole Faust 1371*4947cdc7SCole FaustA function may refer to variables defined in an enclosing function. 1372*4947cdc7SCole FaustIn this example, the inner function `f` refers to a variable `x` 1373*4947cdc7SCole Faustthat is local to the outer function `squarer`. 1374*4947cdc7SCole Faust`x` is a _free variable_ of `f`. 1375*4947cdc7SCole FaustThe function value (`f`) created by a `def` statement holds a 1376*4947cdc7SCole Faustreference to each of its free variables so it may use 1377*4947cdc7SCole Faustthem even after the enclosing function has returned. 1378*4947cdc7SCole Faust 1379*4947cdc7SCole Faust```python 1380*4947cdc7SCole Faustdef squarer(): 1381*4947cdc7SCole Faust x = [0] 1382*4947cdc7SCole Faust def f(): 1383*4947cdc7SCole Faust x[0] += 1 1384*4947cdc7SCole Faust return x[0]*x[0] 1385*4947cdc7SCole Faust return f 1386*4947cdc7SCole Faust 1387*4947cdc7SCole Faustsq = squarer() 1388*4947cdc7SCole Faustprint(sq(), sq(), sq(), sq()) # "1 4 9 16" 1389*4947cdc7SCole Faust``` 1390*4947cdc7SCole Faust 1391*4947cdc7SCole FaustAn inner function cannot assign to a variable bound in an enclosing 1392*4947cdc7SCole Faustfunction, because the assignment would bind the variable in the 1393*4947cdc7SCole Faustinner function. 1394*4947cdc7SCole FaustIn the example below, the `x += 1` statement binds `x` within `f`, 1395*4947cdc7SCole Fausthiding the outer `x`. 1396*4947cdc7SCole FaustExecution fails because the inner `x` has not been assigned before the 1397*4947cdc7SCole Faustattempt to increment it. 1398*4947cdc7SCole Faust 1399*4947cdc7SCole Faust```python 1400*4947cdc7SCole Faustdef squarer(): 1401*4947cdc7SCole Faust x = 0 1402*4947cdc7SCole Faust def f(): 1403*4947cdc7SCole Faust x += 1 # dynamic error: local variable x referenced before assignment 1404*4947cdc7SCole Faust return x*x 1405*4947cdc7SCole Faust return f 1406*4947cdc7SCole Faust 1407*4947cdc7SCole Faustsq = squarer() 1408*4947cdc7SCole Faust``` 1409*4947cdc7SCole Faust 1410*4947cdc7SCole Faust(Starlark has no equivalent of Python's `nonlocal` or `global` 1411*4947cdc7SCole Faustdeclarations, but as the first version of `squarer` showed, this 1412*4947cdc7SCole Faustomission can be worked around by using a list of a single element.) 1413*4947cdc7SCole Faust 1414*4947cdc7SCole Faust 1415*4947cdc7SCole FaustA name appearing after a dot, such as `split` in 1416*4947cdc7SCole Faust`get_filename().split('/')`, is not resolved statically. 1417*4947cdc7SCole FaustThe [dot expression](#dot-expressions) `.split` is a dynamic operation 1418*4947cdc7SCole Fauston the value returned by `get_filename()`. 1419*4947cdc7SCole Faust 1420*4947cdc7SCole Faust 1421*4947cdc7SCole Faust## Value concepts 1422*4947cdc7SCole Faust 1423*4947cdc7SCole FaustStarlark has eleven core [data types](#data-types). An application 1424*4947cdc7SCole Faustthat embeds the Starlark intepreter may define additional types that 1425*4947cdc7SCole Faustbehave like Starlark values. All values, whether core or 1426*4947cdc7SCole Faustapplication-defined, implement a few basic behaviors: 1427*4947cdc7SCole Faust 1428*4947cdc7SCole Faust```text 1429*4947cdc7SCole Fauststr(x) -- return a string representation of x 1430*4947cdc7SCole Fausttype(x) -- return a string describing the type of x 1431*4947cdc7SCole Faustbool(x) -- convert x to a Boolean truth value 1432*4947cdc7SCole Faust``` 1433*4947cdc7SCole Faust 1434*4947cdc7SCole Faust### Identity and mutation 1435*4947cdc7SCole Faust 1436*4947cdc7SCole FaustStarlark is an imperative language: programs consist of sequences of 1437*4947cdc7SCole Fauststatements executed for their side effects. 1438*4947cdc7SCole FaustFor example, an assignment statement updates the value held by a 1439*4947cdc7SCole Faustvariable, and calls to some built-in functions such as `print` change 1440*4947cdc7SCole Faustthe state of the application that embeds the interpreter. 1441*4947cdc7SCole Faust 1442*4947cdc7SCole FaustValues of some data types, such as `NoneType`, `bool`, `int`, `float`, and 1443*4947cdc7SCole Faust`string`, are _immutable_; they can never change. 1444*4947cdc7SCole FaustImmutable values have no notion of _identity_: it is impossible for a 1445*4947cdc7SCole FaustStarlark program to tell whether two integers, for instance, are 1446*4947cdc7SCole Faustrepresented by the same object; it can tell only whether they are 1447*4947cdc7SCole Faustequal. 1448*4947cdc7SCole Faust 1449*4947cdc7SCole FaustValues of other data types, such as `list`, `dict`, and `set`, are 1450*4947cdc7SCole Faust_mutable_: they may be modified by a statement such as `a[i] = 0` or 1451*4947cdc7SCole Faust`items.clear()`. Although `tuple` and `function` values are not 1452*4947cdc7SCole Faustdirectly mutable, they may refer to mutable values indirectly, so for 1453*4947cdc7SCole Faustthis reason we consider them mutable too. Starlark values of these 1454*4947cdc7SCole Fausttypes are actually _references_ to variables. 1455*4947cdc7SCole Faust 1456*4947cdc7SCole FaustCopying a reference to a variable, using an assignment statement for 1457*4947cdc7SCole Faustinstance, creates an _alias_ for the variable, and the effects of 1458*4947cdc7SCole Faustoperations applied to the variable through one alias are visible 1459*4947cdc7SCole Faustthrough all others. 1460*4947cdc7SCole Faust 1461*4947cdc7SCole Faust```python 1462*4947cdc7SCole Faustx = [] # x refers to a new empty list variable 1463*4947cdc7SCole Fausty = x # y becomes an alias for x 1464*4947cdc7SCole Faustx.append(1) # changes the variable referred to by x 1465*4947cdc7SCole Faustprint(y) # "[1]"; y observes the mutation 1466*4947cdc7SCole Faust``` 1467*4947cdc7SCole Faust 1468*4947cdc7SCole FaustStarlark uses _call-by-value_ parameter passing: in a function call, 1469*4947cdc7SCole Faustargument values are assigned to function parameters as if by 1470*4947cdc7SCole Faustassignment statements. If the values are references, the caller and 1471*4947cdc7SCole Faustcallee may refer to the same variables, so if the called function 1472*4947cdc7SCole Faustchanges the variable referred to by a parameter, the effect may also 1473*4947cdc7SCole Faustbe observed by the caller: 1474*4947cdc7SCole Faust 1475*4947cdc7SCole Faust```python 1476*4947cdc7SCole Faustdef f(y): 1477*4947cdc7SCole Faust y.append(1) # changes the variable referred to by x 1478*4947cdc7SCole Faust 1479*4947cdc7SCole Faustx = [] # x refers to a new empty list variable 1480*4947cdc7SCole Faustf(x) # f's parameter y becomes an alias for x 1481*4947cdc7SCole Faustprint(x) # "[1]"; x observes the mutation 1482*4947cdc7SCole Faust``` 1483*4947cdc7SCole Faust 1484*4947cdc7SCole Faust 1485*4947cdc7SCole FaustAs in all imperative languages, understanding _aliasing_, the 1486*4947cdc7SCole Faustrelationship between reference values and the variables to which they 1487*4947cdc7SCole Faustrefer, is crucial to writing correct programs. 1488*4947cdc7SCole Faust 1489*4947cdc7SCole Faust### Freezing a value 1490*4947cdc7SCole Faust 1491*4947cdc7SCole FaustStarlark has a feature unusual among imperative programming languages: 1492*4947cdc7SCole Fausta mutable value may be _frozen_ so that all subsequent attempts to 1493*4947cdc7SCole Faustmutate it fail with a dynamic error; the value, and all other values 1494*4947cdc7SCole Faustreachable from it, become _immutable_. 1495*4947cdc7SCole Faust 1496*4947cdc7SCole FaustImmediately after execution of a Starlark module, all values in its 1497*4947cdc7SCole Fausttop-level environment are frozen. Because all the global variables of 1498*4947cdc7SCole Faustan initialized Starlark module are immutable, the module may be published to 1499*4947cdc7SCole Faustand used by other threads in a parallel program without the need for 1500*4947cdc7SCole Faustlocks. For example, the Bazel build system loads and executes BUILD 1501*4947cdc7SCole Faustand .bzl files in parallel, and two modules being executed 1502*4947cdc7SCole Faustconcurrently may freely access variables or call functions from a 1503*4947cdc7SCole Faustthird without the possibility of a race condition. 1504*4947cdc7SCole Faust 1505*4947cdc7SCole Faust### Hashing 1506*4947cdc7SCole Faust 1507*4947cdc7SCole FaustThe `dict` and `set` data types are implemented using hash tables, so 1508*4947cdc7SCole Faustonly _hashable_ values are suitable as keys of a `dict` or elements of 1509*4947cdc7SCole Fausta `set`. Attempting to use a non-hashable value as the key in a hash 1510*4947cdc7SCole Fausttable results in a dynamic error. 1511*4947cdc7SCole Faust 1512*4947cdc7SCole FaustThe hash of a value is an unspecified integer chosen so that two equal 1513*4947cdc7SCole Faustvalues have the same hash, in other words, `x == y => hash(x) == hash(y)`. 1514*4947cdc7SCole FaustA hashable value has the same hash throughout its lifetime. 1515*4947cdc7SCole Faust 1516*4947cdc7SCole FaustValues of the types `NoneType`, `bool`, `int`, `float`, and `string`, 1517*4947cdc7SCole Faustwhich are all immutable, are hashable. 1518*4947cdc7SCole Faust 1519*4947cdc7SCole FaustValues of mutable types such as `list`, `dict`, and `set` are not 1520*4947cdc7SCole Fausthashable. These values remain unhashable even if they have become 1521*4947cdc7SCole Faustimmutable due to _freezing_. 1522*4947cdc7SCole Faust 1523*4947cdc7SCole FaustA `tuple` value is hashable only if all its elements are hashable. 1524*4947cdc7SCole FaustThus `("localhost", 80)` is hashable but `([127, 0, 0, 1], 80)` is not. 1525*4947cdc7SCole Faust 1526*4947cdc7SCole FaustValues of the types `function` and `builtin_function_or_method` are also hashable. 1527*4947cdc7SCole FaustAlthough functions are not necessarily immutable, as they may be 1528*4947cdc7SCole Faustclosures that refer to mutable variables, instances of these types 1529*4947cdc7SCole Faustare compared by reference identity (see [Comparisons](#comparisons)), 1530*4947cdc7SCole Faustso their hash values are derived from their identity. 1531*4947cdc7SCole Faust 1532*4947cdc7SCole Faust 1533*4947cdc7SCole Faust### Sequence types 1534*4947cdc7SCole Faust 1535*4947cdc7SCole FaustMany Starlark data types represent a _sequence_ of values: lists, 1536*4947cdc7SCole Fausttuples, and sets are sequences of arbitrary values, and in many 1537*4947cdc7SCole Faustcontexts dictionaries act like a sequence of their keys. 1538*4947cdc7SCole Faust 1539*4947cdc7SCole FaustWe can classify different kinds of sequence types based on the 1540*4947cdc7SCole Faustoperations they support. 1541*4947cdc7SCole FaustEach is listed below using the name of its corresponding interface in 1542*4947cdc7SCole Faustthe interpreter's Go API. 1543*4947cdc7SCole Faust 1544*4947cdc7SCole Faust* `Iterable`: an _iterable_ value lets us process each of its elements in a fixed order. 1545*4947cdc7SCole Faust Examples: `dict`, `set`, `list`, `tuple`, but not `string`. 1546*4947cdc7SCole Faust* `Sequence`: a _sequence of known length_ lets us know how many elements it 1547*4947cdc7SCole Faust contains without processing them. 1548*4947cdc7SCole Faust Examples: `dict`, `set`, `list`, `tuple`, but not `string`. 1549*4947cdc7SCole Faust* `Indexable`: an _indexed_ type has a fixed length and provides efficient 1550*4947cdc7SCole Faust random access to its elements, which are identified by integer indices. 1551*4947cdc7SCole Faust Examples: `string`, `tuple`, and `list`. 1552*4947cdc7SCole Faust* `SetIndexable`: a _settable indexed type_ additionally allows us to modify the 1553*4947cdc7SCole Faust element at a given integer index. Example: `list`. 1554*4947cdc7SCole Faust* `Mapping`: a mapping is an association of keys to values. Example: `dict`. 1555*4947cdc7SCole Faust 1556*4947cdc7SCole FaustAlthough all of Starlark's core data types for sequences implement at 1557*4947cdc7SCole Faustleast the `Sequence` contract, it's possible for an application 1558*4947cdc7SCole Faustthat embeds the Starlark interpreter to define additional data types 1559*4947cdc7SCole Faustrepresenting sequences of unknown length that implement only the `Iterable` contract. 1560*4947cdc7SCole Faust 1561*4947cdc7SCole FaustStrings are not iterable, though they do support the `len(s)` and 1562*4947cdc7SCole Faust`s[i]` operations. Starlark deviates from Python here to avoid a common 1563*4947cdc7SCole Faustpitfall in which a string is used by mistake where a list containing a 1564*4947cdc7SCole Faustsingle string was intended, resulting in its interpretation as a sequence 1565*4947cdc7SCole Faustof bytes. 1566*4947cdc7SCole Faust 1567*4947cdc7SCole FaustMost Starlark operators and built-in functions that need a sequence 1568*4947cdc7SCole Faustof values will accept any iterable. 1569*4947cdc7SCole Faust 1570*4947cdc7SCole FaustIt is a dynamic error to mutate a sequence such as a list, set, or 1571*4947cdc7SCole Faustdictionary while iterating over it. 1572*4947cdc7SCole Faust 1573*4947cdc7SCole Faust```python 1574*4947cdc7SCole Faustdef increment_values(dict): 1575*4947cdc7SCole Faust for k in dict: 1576*4947cdc7SCole Faust dict[k] += 1 # error: cannot insert into hash table during iteration 1577*4947cdc7SCole Faust 1578*4947cdc7SCole Faustdict = {"one": 1, "two": 2} 1579*4947cdc7SCole Faustincrement_values(dict) 1580*4947cdc7SCole Faust``` 1581*4947cdc7SCole Faust 1582*4947cdc7SCole Faust 1583*4947cdc7SCole Faust### Indexing 1584*4947cdc7SCole Faust 1585*4947cdc7SCole FaustMany Starlark operators and functions require an index operand `i`, 1586*4947cdc7SCole Faustsuch as `a[i]` or `list.insert(i, x)`. Others require two indices `i` 1587*4947cdc7SCole Faustand `j` that indicate the start and end of a sub-sequence, such as 1588*4947cdc7SCole Faust`a[i:j]`, `list.index(x, i, j)`, or `string.find(x, i, j)`. 1589*4947cdc7SCole FaustAll such operations follow similar conventions, described here. 1590*4947cdc7SCole Faust 1591*4947cdc7SCole FaustIndexing in Starlark is *zero-based*. The first element of a string 1592*4947cdc7SCole Faustor list has index 0, the next 1, and so on. The last element of a 1593*4947cdc7SCole Faustsequence of length `n` has index `n-1`. 1594*4947cdc7SCole Faust 1595*4947cdc7SCole Faust```python 1596*4947cdc7SCole Faust"hello"[0] # "h" 1597*4947cdc7SCole Faust"hello"[4] # "o" 1598*4947cdc7SCole Faust"hello"[5] # error: index out of range 1599*4947cdc7SCole Faust``` 1600*4947cdc7SCole Faust 1601*4947cdc7SCole FaustFor sub-sequence operations that require two indices, the first is 1602*4947cdc7SCole Faust_inclusive_ and the second _exclusive_. Thus `a[i:j]` indicates the 1603*4947cdc7SCole Faustsequence starting with element `i` up to but not including element 1604*4947cdc7SCole Faust`j`. The length of this sub-sequence is `j-i`. This convention is known 1605*4947cdc7SCole Faustas *half-open indexing*. 1606*4947cdc7SCole Faust 1607*4947cdc7SCole Faust```python 1608*4947cdc7SCole Faust"hello"[1:4] # "ell" 1609*4947cdc7SCole Faust``` 1610*4947cdc7SCole Faust 1611*4947cdc7SCole FaustEither or both of the index operands may be omitted. If omitted, the 1612*4947cdc7SCole Faustfirst is treated equivalent to 0 and the second is equivalent to the 1613*4947cdc7SCole Faustlength of the sequence: 1614*4947cdc7SCole Faust 1615*4947cdc7SCole Faust```python 1616*4947cdc7SCole Faust"hello"[1:] # "ello" 1617*4947cdc7SCole Faust"hello"[:4] # "hell" 1618*4947cdc7SCole Faust``` 1619*4947cdc7SCole Faust 1620*4947cdc7SCole FaustIt is permissible to supply a negative integer to an indexing 1621*4947cdc7SCole Faustoperation. The effective index is computed from the supplied value by 1622*4947cdc7SCole Faustthe following two-step procedure. First, if the value is negative, the 1623*4947cdc7SCole Faustlength of the sequence is added to it. This provides a convenient way 1624*4947cdc7SCole Faustto address the final elements of the sequence: 1625*4947cdc7SCole Faust 1626*4947cdc7SCole Faust```python 1627*4947cdc7SCole Faust"hello"[-1] # "o", like "hello"[4] 1628*4947cdc7SCole Faust"hello"[-3:-1] # "ll", like "hello"[2:4] 1629*4947cdc7SCole Faust``` 1630*4947cdc7SCole Faust 1631*4947cdc7SCole FaustSecond, for sub-sequence operations, if the value is still negative, it 1632*4947cdc7SCole Faustis replaced by zero, or if it is greater than the length `n` of the 1633*4947cdc7SCole Faustsequence, it is replaced by `n`. In effect, the index is "truncated" to 1634*4947cdc7SCole Faustthe nearest value in the range `[0:n]`. 1635*4947cdc7SCole Faust 1636*4947cdc7SCole Faust```python 1637*4947cdc7SCole Faust"hello"[-1000:+1000] # "hello" 1638*4947cdc7SCole Faust``` 1639*4947cdc7SCole Faust 1640*4947cdc7SCole FaustThis truncation step does not apply to indices of individual elements: 1641*4947cdc7SCole Faust 1642*4947cdc7SCole Faust```python 1643*4947cdc7SCole Faust"hello"[-6] # error: index out of range 1644*4947cdc7SCole Faust"hello"[-5] # "h" 1645*4947cdc7SCole Faust"hello"[4] # "o" 1646*4947cdc7SCole Faust"hello"[5] # error: index out of range 1647*4947cdc7SCole Faust``` 1648*4947cdc7SCole Faust 1649*4947cdc7SCole Faust 1650*4947cdc7SCole Faust## Expressions 1651*4947cdc7SCole Faust 1652*4947cdc7SCole FaustAn expression specifies the computation of a value. 1653*4947cdc7SCole Faust 1654*4947cdc7SCole FaustThe Starlark grammar defines several categories of expression. 1655*4947cdc7SCole FaustAn _operand_ is an expression consisting of a single token (such as an 1656*4947cdc7SCole Faustidentifier or a literal), or a bracketed expression. 1657*4947cdc7SCole FaustOperands are self-delimiting. 1658*4947cdc7SCole FaustAn operand may be followed by any number of dot, call, or slice 1659*4947cdc7SCole Faustsuffixes, to form a _primary_ expression. 1660*4947cdc7SCole FaustIn some places in the Starlark grammar where an expression is expected, 1661*4947cdc7SCole Faustit is legal to provide a comma-separated list of expressions denoting 1662*4947cdc7SCole Fausta tuple. 1663*4947cdc7SCole FaustThe grammar uses `Expression` where a multiple-component expression is allowed, 1664*4947cdc7SCole Faustand `Test` where it accepts an expression of only a single component. 1665*4947cdc7SCole Faust 1666*4947cdc7SCole Faust```grammar {.good} 1667*4947cdc7SCole FaustExpression = Test {',' Test} . 1668*4947cdc7SCole Faust 1669*4947cdc7SCole FaustTest = LambdaExpr | IfExpr | PrimaryExpr | UnaryExpr | BinaryExpr . 1670*4947cdc7SCole Faust 1671*4947cdc7SCole FaustPrimaryExpr = Operand 1672*4947cdc7SCole Faust | PrimaryExpr DotSuffix 1673*4947cdc7SCole Faust | PrimaryExpr CallSuffix 1674*4947cdc7SCole Faust | PrimaryExpr SliceSuffix 1675*4947cdc7SCole Faust . 1676*4947cdc7SCole Faust 1677*4947cdc7SCole FaustOperand = identifier 1678*4947cdc7SCole Faust | int | float | string 1679*4947cdc7SCole Faust | ListExpr | ListComp 1680*4947cdc7SCole Faust | DictExpr | DictComp 1681*4947cdc7SCole Faust | '(' [Expression] [,] ')' 1682*4947cdc7SCole Faust | ('-' | '+') PrimaryExpr 1683*4947cdc7SCole Faust . 1684*4947cdc7SCole Faust 1685*4947cdc7SCole FaustDotSuffix = '.' identifier . 1686*4947cdc7SCole FaustCallSuffix = '(' [Arguments [',']] ')' . 1687*4947cdc7SCole FaustSliceSuffix = '[' [Expression] [':' Test [':' Test]] ']' . 1688*4947cdc7SCole Faust``` 1689*4947cdc7SCole Faust 1690*4947cdc7SCole FaustTODO: resolve position of +x, -x, and 'not x' in grammar: Operand or UnaryExpr? 1691*4947cdc7SCole Faust 1692*4947cdc7SCole Faust### Identifiers 1693*4947cdc7SCole Faust 1694*4947cdc7SCole Faust```grammar {.good} {.good} 1695*4947cdc7SCole FaustPrimary = identifier 1696*4947cdc7SCole Faust``` 1697*4947cdc7SCole Faust 1698*4947cdc7SCole FaustAn identifier is a name that identifies a value. 1699*4947cdc7SCole Faust 1700*4947cdc7SCole FaustLookup of locals and globals may fail if not yet defined. 1701*4947cdc7SCole Faust 1702*4947cdc7SCole Faust### Literals 1703*4947cdc7SCole Faust 1704*4947cdc7SCole FaustStarlark supports literals of three different kinds: 1705*4947cdc7SCole Faust 1706*4947cdc7SCole Faust```grammar {.good} 1707*4947cdc7SCole FaustPrimary = int | float | string 1708*4947cdc7SCole Faust``` 1709*4947cdc7SCole Faust 1710*4947cdc7SCole FaustEvaluation of a literal yields a value of the given type (string, int, 1711*4947cdc7SCole Faustor float) with the given value. 1712*4947cdc7SCole FaustSee [Literals](#lexical-elements) for details. 1713*4947cdc7SCole Faust 1714*4947cdc7SCole Faust### Parenthesized expressions 1715*4947cdc7SCole Faust 1716*4947cdc7SCole Faust```grammar {.good} 1717*4947cdc7SCole FaustPrimary = '(' [Expression] ')' 1718*4947cdc7SCole Faust``` 1719*4947cdc7SCole Faust 1720*4947cdc7SCole FaustA single expression enclosed in parentheses yields the result of that expression. 1721*4947cdc7SCole FaustExplicit parentheses may be used for clarity, 1722*4947cdc7SCole Faustor to override the default association of subexpressions. 1723*4947cdc7SCole Faust 1724*4947cdc7SCole Faust```python 1725*4947cdc7SCole Faust1 + 2 * 3 + 4 # 11 1726*4947cdc7SCole Faust(1 + 2) * (3 + 4) # 21 1727*4947cdc7SCole Faust``` 1728*4947cdc7SCole Faust 1729*4947cdc7SCole FaustIf the parentheses are empty, or contain a single expression followed 1730*4947cdc7SCole Faustby a comma, or contain two or more expressions, the expression yields a tuple. 1731*4947cdc7SCole Faust 1732*4947cdc7SCole Faust```python 1733*4947cdc7SCole Faust() # (), the empty tuple 1734*4947cdc7SCole Faust(1,) # (1,), a tuple of length 1 1735*4947cdc7SCole Faust(1, 2) # (1, 2), a 2-tuple or pair 1736*4947cdc7SCole Faust(1, 2, 3) # (1, 2, 3), a 3-tuple or triple 1737*4947cdc7SCole Faust``` 1738*4947cdc7SCole Faust 1739*4947cdc7SCole FaustIn some contexts, such as a `return` or assignment statement or the 1740*4947cdc7SCole Faustoperand of a `for` statement, a tuple may be expressed without 1741*4947cdc7SCole Faustparentheses. 1742*4947cdc7SCole Faust 1743*4947cdc7SCole Faust```python 1744*4947cdc7SCole Faustx, y = 1, 2 1745*4947cdc7SCole Faust 1746*4947cdc7SCole Faustreturn 1, 2 1747*4947cdc7SCole Faust 1748*4947cdc7SCole Faustfor x in 1, 2: 1749*4947cdc7SCole Faust print(x) 1750*4947cdc7SCole Faust``` 1751*4947cdc7SCole Faust 1752*4947cdc7SCole FaustStarlark (like Python 3) does not accept an unparenthesized tuple 1753*4947cdc7SCole Faustexpression as the operand of a list comprehension: 1754*4947cdc7SCole Faust 1755*4947cdc7SCole Faust```python 1756*4947cdc7SCole Faust[2*x for x in 1, 2, 3] # parse error: unexpected ',' 1757*4947cdc7SCole Faust``` 1758*4947cdc7SCole Faust 1759*4947cdc7SCole Faust### Dictionary expressions 1760*4947cdc7SCole Faust 1761*4947cdc7SCole FaustA dictionary expression is a comma-separated list of colon-separated 1762*4947cdc7SCole Faustkey/value expression pairs, enclosed in curly brackets, and it yields 1763*4947cdc7SCole Fausta new dictionary object. 1764*4947cdc7SCole FaustAn optional comma may follow the final pair. 1765*4947cdc7SCole Faust 1766*4947cdc7SCole Faust```grammar {.good} 1767*4947cdc7SCole FaustDictExpr = '{' [Entries [',']] '}' . 1768*4947cdc7SCole FaustEntries = Entry {',' Entry} . 1769*4947cdc7SCole FaustEntry = Test ':' Test . 1770*4947cdc7SCole Faust``` 1771*4947cdc7SCole Faust 1772*4947cdc7SCole FaustExamples: 1773*4947cdc7SCole Faust 1774*4947cdc7SCole Faust 1775*4947cdc7SCole Faust```python 1776*4947cdc7SCole Faust{} 1777*4947cdc7SCole Faust{"one": 1} 1778*4947cdc7SCole Faust{"one": 1, "two": 2,} 1779*4947cdc7SCole Faust``` 1780*4947cdc7SCole Faust 1781*4947cdc7SCole FaustThe key and value expressions are evaluated in left-to-right order. 1782*4947cdc7SCole FaustEvaluation fails if the same key is used multiple times. 1783*4947cdc7SCole Faust 1784*4947cdc7SCole FaustOnly [hashable](#hashing) values may be used as the keys of a dictionary. 1785*4947cdc7SCole FaustThis includes all built-in types except dictionaries, sets, and lists; 1786*4947cdc7SCole Fausta tuple is hashable only if its elements are hashable. 1787*4947cdc7SCole Faust 1788*4947cdc7SCole Faust 1789*4947cdc7SCole Faust### List expressions 1790*4947cdc7SCole Faust 1791*4947cdc7SCole FaustA list expression is a comma-separated list of element expressions, 1792*4947cdc7SCole Faustenclosed in square brackets, and it yields a new list object. 1793*4947cdc7SCole FaustAn optional comma may follow the last element expression. 1794*4947cdc7SCole Faust 1795*4947cdc7SCole Faust```grammar {.good} 1796*4947cdc7SCole FaustListExpr = '[' [Expression [',']] ']' . 1797*4947cdc7SCole Faust``` 1798*4947cdc7SCole Faust 1799*4947cdc7SCole FaustElement expressions are evaluated in left-to-right order. 1800*4947cdc7SCole Faust 1801*4947cdc7SCole FaustExamples: 1802*4947cdc7SCole Faust 1803*4947cdc7SCole Faust```python 1804*4947cdc7SCole Faust[] # [], empty list 1805*4947cdc7SCole Faust[1] # [1], a 1-element list 1806*4947cdc7SCole Faust[1, 2, 3,] # [1, 2, 3], a 3-element list 1807*4947cdc7SCole Faust``` 1808*4947cdc7SCole Faust 1809*4947cdc7SCole Faust### Unary operators 1810*4947cdc7SCole Faust 1811*4947cdc7SCole FaustThere are three unary operators, all appearing before their operand: 1812*4947cdc7SCole Faust`+`, `-`, `~`, and `not`. 1813*4947cdc7SCole Faust 1814*4947cdc7SCole Faust```grammar {.good} 1815*4947cdc7SCole FaustUnaryExpr = '+' PrimaryExpr 1816*4947cdc7SCole Faust | '-' PrimaryExpr 1817*4947cdc7SCole Faust | '~' PrimaryExpr 1818*4947cdc7SCole Faust | 'not' Test 1819*4947cdc7SCole Faust . 1820*4947cdc7SCole Faust``` 1821*4947cdc7SCole Faust 1822*4947cdc7SCole Faust```text 1823*4947cdc7SCole Faust+ number unary positive (int, float) 1824*4947cdc7SCole Faust- number unary negation (int, float) 1825*4947cdc7SCole Faust~ number unary bitwise inversion (int) 1826*4947cdc7SCole Faustnot x logical negation (any type) 1827*4947cdc7SCole Faust``` 1828*4947cdc7SCole Faust 1829*4947cdc7SCole FaustThe `+` and `-` operators may be applied to any number 1830*4947cdc7SCole Faust(`int` or `float`) and return the number unchanged. 1831*4947cdc7SCole FaustUnary `+` is never necessary in a correct program, 1832*4947cdc7SCole Faustbut may serve as an assertion that its operand is a number, 1833*4947cdc7SCole Faustor as documentation. 1834*4947cdc7SCole Faust 1835*4947cdc7SCole Faust```python 1836*4947cdc7SCole Faustif x > 0: 1837*4947cdc7SCole Faust return +1 1838*4947cdc7SCole Faustelse if x < 0: 1839*4947cdc7SCole Faust return -1 1840*4947cdc7SCole Faustelse: 1841*4947cdc7SCole Faust return 0 1842*4947cdc7SCole Faust``` 1843*4947cdc7SCole Faust 1844*4947cdc7SCole FaustThe `not` operator returns the negation of the truth value of its 1845*4947cdc7SCole Faustoperand. 1846*4947cdc7SCole Faust 1847*4947cdc7SCole Faust```python 1848*4947cdc7SCole Faustnot True # False 1849*4947cdc7SCole Faustnot False # True 1850*4947cdc7SCole Faustnot [1, 2, 3] # False 1851*4947cdc7SCole Faustnot "" # True 1852*4947cdc7SCole Faustnot 0 # True 1853*4947cdc7SCole Faust``` 1854*4947cdc7SCole Faust 1855*4947cdc7SCole FaustThe `~` operator yields the bitwise inversion of its integer argument. 1856*4947cdc7SCole FaustThe bitwise inversion of x is defined as -(x+1). 1857*4947cdc7SCole Faust 1858*4947cdc7SCole Faust```python 1859*4947cdc7SCole Faust~1 # -2 1860*4947cdc7SCole Faust~-1 # 0 1861*4947cdc7SCole Faust~0 # -1 1862*4947cdc7SCole Faust``` 1863*4947cdc7SCole Faust 1864*4947cdc7SCole Faust 1865*4947cdc7SCole Faust### Binary operators 1866*4947cdc7SCole Faust 1867*4947cdc7SCole FaustStarlark has the following binary operators, arranged in order of increasing precedence: 1868*4947cdc7SCole Faust 1869*4947cdc7SCole Faust```text 1870*4947cdc7SCole Faustor 1871*4947cdc7SCole Faustand 1872*4947cdc7SCole Faust== != < > <= >= in not in 1873*4947cdc7SCole Faust| 1874*4947cdc7SCole Faust^ 1875*4947cdc7SCole Faust& 1876*4947cdc7SCole Faust<< >> 1877*4947cdc7SCole Faust- + 1878*4947cdc7SCole Faust* / // % 1879*4947cdc7SCole Faust``` 1880*4947cdc7SCole Faust 1881*4947cdc7SCole FaustComparison operators, `in`, and `not in` are non-associative, 1882*4947cdc7SCole Faustso the parser will not accept `0 <= i < n`. 1883*4947cdc7SCole FaustAll other binary operators of equal precedence associate to the left. 1884*4947cdc7SCole Faust 1885*4947cdc7SCole Faust```grammar {.good} 1886*4947cdc7SCole FaustBinaryExpr = Test {Binop Test} . 1887*4947cdc7SCole Faust 1888*4947cdc7SCole FaustBinop = 'or' 1889*4947cdc7SCole Faust | 'and' 1890*4947cdc7SCole Faust | '==' | '!=' | '<' | '>' | '<=' | '>=' | 'in' | 'not' 'in' 1891*4947cdc7SCole Faust | '|' 1892*4947cdc7SCole Faust | '^' 1893*4947cdc7SCole Faust | '&' 1894*4947cdc7SCole Faust | '-' | '+' 1895*4947cdc7SCole Faust | '*' | '%' | '/' | '//' 1896*4947cdc7SCole Faust | '<<' | '>>' 1897*4947cdc7SCole Faust . 1898*4947cdc7SCole Faust``` 1899*4947cdc7SCole Faust 1900*4947cdc7SCole Faust#### `or` and `and` 1901*4947cdc7SCole Faust 1902*4947cdc7SCole FaustThe `or` and `and` operators yield, respectively, the logical disjunction and 1903*4947cdc7SCole Faustconjunction of their arguments, which need not be Booleans. 1904*4947cdc7SCole FaustThe expression `x or y` yields the value of `x` if its truth value is `True`, 1905*4947cdc7SCole Faustor the value of `y` otherwise. 1906*4947cdc7SCole Faust 1907*4947cdc7SCole Faust```starlark 1908*4947cdc7SCole FaustFalse or False # False 1909*4947cdc7SCole FaustFalse or True # True 1910*4947cdc7SCole FaustTrue or False # True 1911*4947cdc7SCole FaustTrue or True # True 1912*4947cdc7SCole Faust 1913*4947cdc7SCole Faust0 or "hello" # "hello" 1914*4947cdc7SCole Faust1 or "hello" # 1 1915*4947cdc7SCole Faust``` 1916*4947cdc7SCole Faust 1917*4947cdc7SCole FaustSimilarly, `x and y` yields the value of `x` if its truth value is 1918*4947cdc7SCole Faust`False`, or the value of `y` otherwise. 1919*4947cdc7SCole Faust 1920*4947cdc7SCole Faust```starlark 1921*4947cdc7SCole FaustFalse and False # False 1922*4947cdc7SCole FaustFalse and True # False 1923*4947cdc7SCole FaustTrue and False # False 1924*4947cdc7SCole FaustTrue and True # True 1925*4947cdc7SCole Faust 1926*4947cdc7SCole Faust0 and "hello" # 0 1927*4947cdc7SCole Faust1 and "hello" # "hello" 1928*4947cdc7SCole Faust``` 1929*4947cdc7SCole Faust 1930*4947cdc7SCole FaustThese operators use "short circuit" evaluation, so the second 1931*4947cdc7SCole Faustexpression is not evaluated if the value of the first expression has 1932*4947cdc7SCole Faustalready determined the result, allowing constructions like these: 1933*4947cdc7SCole Faust 1934*4947cdc7SCole Faust```python 1935*4947cdc7SCole Faustlen(x) > 0 and x[0] == 1 # x[0] is not evaluated if x is empty 1936*4947cdc7SCole Faustx and x[0] == 1 1937*4947cdc7SCole Faustlen(x) == 0 or x[0] == "" 1938*4947cdc7SCole Faustnot x or not x[0] 1939*4947cdc7SCole Faust``` 1940*4947cdc7SCole Faust 1941*4947cdc7SCole Faust#### Comparisons 1942*4947cdc7SCole Faust 1943*4947cdc7SCole FaustThe `==` operator reports whether its operands are equal; the `!=` 1944*4947cdc7SCole Faustoperator is its negation. 1945*4947cdc7SCole Faust 1946*4947cdc7SCole FaustThe operators `<`, `>`, `<=`, and `>=` perform an ordered comparison 1947*4947cdc7SCole Faustof their operands. It is an error to apply these operators to 1948*4947cdc7SCole Faustoperands of unequal type, unless one of the operands is an `int` and 1949*4947cdc7SCole Faustthe other is a `float`. Of the built-in types, only the following 1950*4947cdc7SCole Faustsupport ordered comparison, using the ordering relation shown: 1951*4947cdc7SCole Faust 1952*4947cdc7SCole Faust```shell 1953*4947cdc7SCole FaustNoneType # None <= None 1954*4947cdc7SCole Faustbool # False < True 1955*4947cdc7SCole Faustint # mathematical 1956*4947cdc7SCole Faustfloat # as defined by IEEE 754 1957*4947cdc7SCole Fauststring # lexicographical 1958*4947cdc7SCole Fausttuple # lexicographical 1959*4947cdc7SCole Faustlist # lexicographical 1960*4947cdc7SCole Faust``` 1961*4947cdc7SCole Faust 1962*4947cdc7SCole FaustComparison of floating point values follows the IEEE 754 standard, 1963*4947cdc7SCole Faustwhich breaks several mathematical identities. For example, if `x` is 1964*4947cdc7SCole Fausta `NaN` value, the comparisons `x < y`, `x == y`, and `x > y` all 1965*4947cdc7SCole Faustyield false for all values of `y`. 1966*4947cdc7SCole Faust 1967*4947cdc7SCole FaustApplications may define additional types that support ordered 1968*4947cdc7SCole Faustcomparison. 1969*4947cdc7SCole Faust 1970*4947cdc7SCole FaustThe remaining built-in types support only equality comparisons. 1971*4947cdc7SCole FaustValues of type `dict` or `set` compare equal if their elements compare 1972*4947cdc7SCole Faustequal, and values of type `function` or `builtin_function_or_method` are equal only to 1973*4947cdc7SCole Faustthemselves. 1974*4947cdc7SCole Faust 1975*4947cdc7SCole Faust```shell 1976*4947cdc7SCole Faustdict # equal contents 1977*4947cdc7SCole Faustset # equal contents 1978*4947cdc7SCole Faustfunction # identity 1979*4947cdc7SCole Faustbuiltin_function_or_method # identity 1980*4947cdc7SCole Faust``` 1981*4947cdc7SCole Faust 1982*4947cdc7SCole Faust#### Arithmetic operations 1983*4947cdc7SCole Faust 1984*4947cdc7SCole FaustThe following table summarizes the binary arithmetic operations 1985*4947cdc7SCole Faustavailable for built-in types: 1986*4947cdc7SCole Faust 1987*4947cdc7SCole Faust```shell 1988*4947cdc7SCole FaustArithmetic (int or float; result has type float unless both operands have type int) 1989*4947cdc7SCole Faust number + number # addition 1990*4947cdc7SCole Faust number - number # subtraction 1991*4947cdc7SCole Faust number * number # multiplication 1992*4947cdc7SCole Faust number / number # real division (result is always a float) 1993*4947cdc7SCole Faust number // number # floored division 1994*4947cdc7SCole Faust number % number # remainder of floored division 1995*4947cdc7SCole Faust number ^ number # bitwise XOR 1996*4947cdc7SCole Faust number << number # bitwise left shift 1997*4947cdc7SCole Faust number >> number # bitwise right shift 1998*4947cdc7SCole Faust 1999*4947cdc7SCole FaustConcatenation 2000*4947cdc7SCole Faust string + string 2001*4947cdc7SCole Faust list + list 2002*4947cdc7SCole Faust tuple + tuple 2003*4947cdc7SCole Faust 2004*4947cdc7SCole FaustRepetition (string/list/tuple) 2005*4947cdc7SCole Faust int * sequence 2006*4947cdc7SCole Faust sequence * int 2007*4947cdc7SCole Faust 2008*4947cdc7SCole FaustString interpolation 2009*4947cdc7SCole Faust string % any # see String Interpolation 2010*4947cdc7SCole Faust 2011*4947cdc7SCole FaustSets 2012*4947cdc7SCole Faust int | int # bitwise union (OR) 2013*4947cdc7SCole Faust set | set # set union 2014*4947cdc7SCole Faust int & int # bitwise intersection (AND) 2015*4947cdc7SCole Faust set & set # set intersection 2016*4947cdc7SCole Faust set ^ set # set symmetric difference 2017*4947cdc7SCole Faust``` 2018*4947cdc7SCole Faust 2019*4947cdc7SCole FaustThe operands of the arithmetic operators `+`, `-`, `*`, `//`, and 2020*4947cdc7SCole Faust`%` must both be numbers (`int` or `float`) but need not have the same type. 2021*4947cdc7SCole FaustThe type of the result has type `int` only if both operands have that type. 2022*4947cdc7SCole FaustThe result of real division `/` always has type `float`. 2023*4947cdc7SCole Faust 2024*4947cdc7SCole FaustThe `+` operator may be applied to non-numeric operands of the same 2025*4947cdc7SCole Fausttype, such as two lists, two tuples, or two strings, in which case it 2026*4947cdc7SCole Faustcomputes the concatenation of the two operands and yields a new value of 2027*4947cdc7SCole Faustthe same type. 2028*4947cdc7SCole Faust 2029*4947cdc7SCole Faust```python 2030*4947cdc7SCole Faust"Hello, " + "world" # "Hello, world" 2031*4947cdc7SCole Faust(1, 2) + (3, 4) # (1, 2, 3, 4) 2032*4947cdc7SCole Faust[1, 2] + [3, 4] # [1, 2, 3, 4] 2033*4947cdc7SCole Faust``` 2034*4947cdc7SCole Faust 2035*4947cdc7SCole FaustThe `*` operator may be applied to an integer _n_ and a value of type 2036*4947cdc7SCole Faust`string`, `list`, or `tuple`, in which case it yields a new value 2037*4947cdc7SCole Faustof the same sequence type consisting of _n_ repetitions of the original sequence. 2038*4947cdc7SCole FaustThe order of the operands is immaterial. 2039*4947cdc7SCole FaustNegative values of _n_ behave like zero. 2040*4947cdc7SCole Faust 2041*4947cdc7SCole Faust```python 2042*4947cdc7SCole Faust'mur' * 2 # 'murmur' 2043*4947cdc7SCole Faust3 * range(3) # [0, 1, 2, 0, 1, 2, 0, 1, 2] 2044*4947cdc7SCole Faust``` 2045*4947cdc7SCole Faust 2046*4947cdc7SCole FaustApplications may define additional types that support any subset of 2047*4947cdc7SCole Faustthese operators. 2048*4947cdc7SCole Faust 2049*4947cdc7SCole FaustThe `&` operator requires two operands of the same type, either `int` or `set`. 2050*4947cdc7SCole FaustFor integers, it yields the bitwise intersection (AND) of its operands. 2051*4947cdc7SCole FaustFor sets, it yields a new set containing the intersection of the 2052*4947cdc7SCole Faustelements of the operand sets, preserving the element order of the left 2053*4947cdc7SCole Faustoperand. 2054*4947cdc7SCole Faust 2055*4947cdc7SCole FaustThe `|` operator likewise computes bitwise or set unions. 2056*4947cdc7SCole FaustThe result of `set | set` is a new set whose elements are the 2057*4947cdc7SCole Faustunion of the operands, preserving the order of the elements of the 2058*4947cdc7SCole Faustoperands, left before right. 2059*4947cdc7SCole Faust 2060*4947cdc7SCole FaustThe `^` operator accepts operands of either `int` or `set` type. 2061*4947cdc7SCole FaustFor integers, it yields the bitwise XOR (exclusive OR) of its operands. 2062*4947cdc7SCole FaustFor sets, it yields a new set containing elements of either first or second 2063*4947cdc7SCole Faustoperand but not both (symmetric difference). 2064*4947cdc7SCole Faust 2065*4947cdc7SCole FaustThe `<<` and `>>` operators require operands of `int` type both. They shift 2066*4947cdc7SCole Faustthe first operand to the left or right by the number of bits given by the 2067*4947cdc7SCole Faustsecond operand. It is a dynamic error if the second operand is negative. 2068*4947cdc7SCole FaustImplementations may impose a limit on the second operand of a left shift. 2069*4947cdc7SCole Faust 2070*4947cdc7SCole Faust```python 2071*4947cdc7SCole Faust0x12345678 & 0xFF # 0x00000078 2072*4947cdc7SCole Faust0x12345678 | 0xFF # 0x123456FF 2073*4947cdc7SCole Faust0b01011101 ^ 0b110101101 # 0b111110000 2074*4947cdc7SCole Faust0b01011101 >> 2 # 0b010111 2075*4947cdc7SCole Faust0b01011101 << 2 # 0b0101110100 2076*4947cdc7SCole Faust 2077*4947cdc7SCole Faustset([1, 2]) & set([2, 3]) # set([2]) 2078*4947cdc7SCole Faustset([1, 2]) | set([2, 3]) # set([1, 2, 3]) 2079*4947cdc7SCole Faustset([1, 2]) ^ set([2, 3]) # set([1, 3]) 2080*4947cdc7SCole Faust``` 2081*4947cdc7SCole Faust 2082*4947cdc7SCole Faust<b>Implementation note:</b> 2083*4947cdc7SCole FaustThe Go implementation of Starlark requires the `-set` flag to 2084*4947cdc7SCole Faustenable support for sets. 2085*4947cdc7SCole FaustThe Java implementation does not support sets. 2086*4947cdc7SCole Faust 2087*4947cdc7SCole Faust 2088*4947cdc7SCole Faust#### Membership tests 2089*4947cdc7SCole Faust 2090*4947cdc7SCole Faust```text 2091*4947cdc7SCole Faust any in sequence (list, tuple, dict, set, string) 2092*4947cdc7SCole Faust any not in sequence 2093*4947cdc7SCole Faust``` 2094*4947cdc7SCole Faust 2095*4947cdc7SCole FaustThe `in` operator reports whether its first operand is a member of its 2096*4947cdc7SCole Faustsecond operand, which must be a list, tuple, dict, set, or string. 2097*4947cdc7SCole FaustThe `not in` operator is its negation. 2098*4947cdc7SCole FaustBoth return a Boolean. 2099*4947cdc7SCole Faust 2100*4947cdc7SCole FaustThe meaning of membership varies by the type of the second operand: 2101*4947cdc7SCole Faustthe members of a list, tuple, or set are its elements; 2102*4947cdc7SCole Faustthe members of a dict are its keys; 2103*4947cdc7SCole Faustthe members of a string are all its substrings. 2104*4947cdc7SCole Faust 2105*4947cdc7SCole Faust```python 2106*4947cdc7SCole Faust1 in [1, 2, 3] # True 2107*4947cdc7SCole Faust4 in (1, 2, 3) # False 2108*4947cdc7SCole Faust4 not in set([1, 2, 3]) # True 2109*4947cdc7SCole Faust 2110*4947cdc7SCole Faustd = {"one": 1, "two": 2} 2111*4947cdc7SCole Faust"one" in d # True 2112*4947cdc7SCole Faust"three" in d # False 2113*4947cdc7SCole Faust1 in d # False 2114*4947cdc7SCole Faust[] in d # False 2115*4947cdc7SCole Faust 2116*4947cdc7SCole Faust"nasty" in "dynasty" # True 2117*4947cdc7SCole Faust"a" in "banana" # True 2118*4947cdc7SCole Faust"f" not in "way" # True 2119*4947cdc7SCole Faust``` 2120*4947cdc7SCole Faust 2121*4947cdc7SCole Faust#### String interpolation 2122*4947cdc7SCole Faust 2123*4947cdc7SCole FaustThe expression `format % args` performs _string interpolation_, a 2124*4947cdc7SCole Faustsimple form of template expansion. 2125*4947cdc7SCole FaustThe `format` string is interpreted as a sequence of literal portions 2126*4947cdc7SCole Faustand _conversions_. 2127*4947cdc7SCole FaustEach conversion, which starts with a `%` character, is replaced by its 2128*4947cdc7SCole Faustcorresponding value from `args`. 2129*4947cdc7SCole FaustThe characters following `%` in each conversion determine which 2130*4947cdc7SCole Faustargument it uses and how to convert it to a string. 2131*4947cdc7SCole Faust 2132*4947cdc7SCole FaustEach `%` character marks the start of a conversion specifier, unless 2133*4947cdc7SCole Faustit is immediately followed by another `%`, in which case both 2134*4947cdc7SCole Faustcharacters together denote a literal percent sign. 2135*4947cdc7SCole Faust 2136*4947cdc7SCole FaustIf the `"%"` is immediately followed by `"(key)"`, the parenthesized 2137*4947cdc7SCole Faustsubstring specifies the key of the `args` dictionary whose 2138*4947cdc7SCole Faustcorresponding value is the operand to convert. 2139*4947cdc7SCole FaustOtherwise, the conversion's operand is the next element of `args`, 2140*4947cdc7SCole Faustwhich must be a tuple with exactly one component per conversion, 2141*4947cdc7SCole Faustunless the format string contains only a single conversion, in which 2142*4947cdc7SCole Faustcase `args` itself is its operand. 2143*4947cdc7SCole Faust 2144*4947cdc7SCole FaustStarlark does not support the flag, width, and padding specifiers 2145*4947cdc7SCole Faustsupported by Python's `%` and other variants of C's `printf`. 2146*4947cdc7SCole Faust 2147*4947cdc7SCole FaustAfter the optional `(key)` comes a single letter indicating what 2148*4947cdc7SCole Faustoperand types are valid and how to convert the operand `x` to a string: 2149*4947cdc7SCole Faust 2150*4947cdc7SCole Faust```text 2151*4947cdc7SCole Faust% none literal percent sign 2152*4947cdc7SCole Fausts any as if by str(x) 2153*4947cdc7SCole Faustr any as if by repr(x) 2154*4947cdc7SCole Faustd number signed integer decimal 2155*4947cdc7SCole Fausti number signed integer decimal 2156*4947cdc7SCole Fausto number signed octal 2157*4947cdc7SCole Faustx number signed hexadecimal, lowercase 2158*4947cdc7SCole FaustX number signed hexadecimal, uppercase 2159*4947cdc7SCole Fauste number float exponential format, lowercase 2160*4947cdc7SCole FaustE number float exponential format, uppercase 2161*4947cdc7SCole Faustf number float decimal format, lowercase 2162*4947cdc7SCole FaustF number float decimal format, uppercase 2163*4947cdc7SCole Faustg number like %e for large exponents, %f otherwise 2164*4947cdc7SCole FaustG number like %E for large exponents, %F otherwise 2165*4947cdc7SCole Faustc string x (string must encode a single Unicode code point) 2166*4947cdc7SCole Faust int as if by chr(x) 2167*4947cdc7SCole Faust``` 2168*4947cdc7SCole Faust 2169*4947cdc7SCole FaustIt is an error if the argument does not have the type required by the 2170*4947cdc7SCole Faustconversion specifier. A Boolean argument is not considered a number. 2171*4947cdc7SCole Faust 2172*4947cdc7SCole FaustExamples: 2173*4947cdc7SCole Faust 2174*4947cdc7SCole Faust```python 2175*4947cdc7SCole Faust"Hello %s, your score is %d" % ("Bob", 75) # "Hello Bob, your score is 75" 2176*4947cdc7SCole Faust 2177*4947cdc7SCole Faust"%d %o %x %c" % (65, 65, 65, 65) # "65 101 41 A" (decimal, octal, hexadecimal, Unicode) 2178*4947cdc7SCole Faust 2179*4947cdc7SCole Faust"%(greeting)s, %(audience)s" % dict( # "Hello, world" 2180*4947cdc7SCole Faust greeting="Hello", 2181*4947cdc7SCole Faust audience="world", 2182*4947cdc7SCole Faust) 2183*4947cdc7SCole Faust 2184*4947cdc7SCole Faust"rate = %g%% APR" % 3.5 # "rate = 3.5% APR" 2185*4947cdc7SCole Faust``` 2186*4947cdc7SCole Faust 2187*4947cdc7SCole FaustOne subtlety: to use a tuple as the operand of a conversion in format 2188*4947cdc7SCole Fauststring containing only a single conversion, you must wrap the tuple in 2189*4947cdc7SCole Fausta singleton tuple: 2190*4947cdc7SCole Faust 2191*4947cdc7SCole Faust```python 2192*4947cdc7SCole Faust"coordinates=%s" % (40.741491, -74.003680) # error: too many arguments for format string 2193*4947cdc7SCole Faust"coordinates=%s" % ((40.741491, -74.003680),) # "coordinates=(40.741491, -74.003680)" 2194*4947cdc7SCole Faust``` 2195*4947cdc7SCole Faust 2196*4947cdc7SCole FaustTODO: specify `%e` and `%f` more precisely. 2197*4947cdc7SCole Faust 2198*4947cdc7SCole Faust### Conditional expressions 2199*4947cdc7SCole Faust 2200*4947cdc7SCole FaustA conditional expression has the form `a if cond else b`. 2201*4947cdc7SCole FaustIt first evaluates the condition `cond`. 2202*4947cdc7SCole FaustIf it's true, it evaluates `a` and yields its value; 2203*4947cdc7SCole Faustotherwise it yields the value of `b`. 2204*4947cdc7SCole Faust 2205*4947cdc7SCole Faust```grammar {.good} 2206*4947cdc7SCole FaustIfExpr = Test 'if' Test 'else' Test . 2207*4947cdc7SCole Faust``` 2208*4947cdc7SCole Faust 2209*4947cdc7SCole FaustExample: 2210*4947cdc7SCole Faust 2211*4947cdc7SCole Faust```python 2212*4947cdc7SCole Faust"yes" if enabled else "no" 2213*4947cdc7SCole Faust``` 2214*4947cdc7SCole Faust 2215*4947cdc7SCole Faust### Comprehensions 2216*4947cdc7SCole Faust 2217*4947cdc7SCole FaustA comprehension constructs new list or dictionary value by looping 2218*4947cdc7SCole Faustover one or more iterables and evaluating a _body_ expression that produces 2219*4947cdc7SCole Faustsuccessive elements of the result. 2220*4947cdc7SCole Faust 2221*4947cdc7SCole FaustA list comprehension consists of a single expression followed by one 2222*4947cdc7SCole Faustor more _clauses_, the first of which must be a `for` clause. 2223*4947cdc7SCole FaustEach `for` clause resembles a `for` statement, and specifies an 2224*4947cdc7SCole Faustiterable operand and a set of variables to be assigned by successive 2225*4947cdc7SCole Faustvalues of the iterable. 2226*4947cdc7SCole FaustAn `if` cause resembles an `if` statement, and specifies a condition 2227*4947cdc7SCole Faustthat must be met for the body expression to be evaluated. 2228*4947cdc7SCole FaustA sequence of `for` and `if` clauses acts like a nested sequence of 2229*4947cdc7SCole Faust`for` and `if` statements. 2230*4947cdc7SCole Faust 2231*4947cdc7SCole Faust```grammar {.good} 2232*4947cdc7SCole FaustListComp = '[' Test {CompClause} ']'. 2233*4947cdc7SCole FaustDictComp = '{' Entry {CompClause} '}' . 2234*4947cdc7SCole Faust 2235*4947cdc7SCole FaustCompClause = 'for' LoopVariables 'in' Test 2236*4947cdc7SCole Faust | 'if' Test . 2237*4947cdc7SCole Faust 2238*4947cdc7SCole FaustLoopVariables = PrimaryExpr {',' PrimaryExpr} . 2239*4947cdc7SCole Faust``` 2240*4947cdc7SCole Faust 2241*4947cdc7SCole FaustExamples: 2242*4947cdc7SCole Faust 2243*4947cdc7SCole Faust```python 2244*4947cdc7SCole Faust[x*x for x in range(5)] # [0, 1, 4, 9, 16] 2245*4947cdc7SCole Faust[x*x for x in range(5) if x%2 == 0] # [0, 4, 16] 2246*4947cdc7SCole Faust[(x, y) for x in range(5) 2247*4947cdc7SCole Faust if x%2 == 0 2248*4947cdc7SCole Faust for y in range(5) 2249*4947cdc7SCole Faust if y > x] # [(0, 1), (0, 2), (0, 3), (0, 4), (2, 3), (2, 4)] 2250*4947cdc7SCole Faust``` 2251*4947cdc7SCole Faust 2252*4947cdc7SCole FaustA dict comprehension resembles a list comprehension, but its body is a 2253*4947cdc7SCole Faustpair of expressions, `key: value`, separated by a colon, 2254*4947cdc7SCole Faustand its result is a dictionary containing the key/value pairs 2255*4947cdc7SCole Faustfor which the body expression was evaluated. 2256*4947cdc7SCole FaustEvaluation fails if the value of any key is unhashable. 2257*4947cdc7SCole Faust 2258*4947cdc7SCole FaustAs with a `for` loop, the loop variables may exploit compound 2259*4947cdc7SCole Faustassignment: 2260*4947cdc7SCole Faust 2261*4947cdc7SCole Faust```python 2262*4947cdc7SCole Faust[x*y+z for (x, y), z in [((2, 3), 5), (("o", 2), "!")]] # [11, 'oo!'] 2263*4947cdc7SCole Faust``` 2264*4947cdc7SCole Faust 2265*4947cdc7SCole FaustStarlark, following Python 3, does not accept an unparenthesized 2266*4947cdc7SCole Fausttuple or lambda expression as the operand of a `for` clause: 2267*4947cdc7SCole Faust 2268*4947cdc7SCole Faust```python 2269*4947cdc7SCole Faust[x*x for x in 1, 2, 3] # parse error: unexpected comma 2270*4947cdc7SCole Faust[x*x for x in lambda: 0] # parse error: unexpected lambda 2271*4947cdc7SCole Faust``` 2272*4947cdc7SCole Faust 2273*4947cdc7SCole FaustComprehensions in Starlark, again following Python 3, define a new lexical 2274*4947cdc7SCole Faustblock, so assignments to loop variables have no effect on variables of 2275*4947cdc7SCole Faustthe same name in an enclosing block: 2276*4947cdc7SCole Faust 2277*4947cdc7SCole Faust```python 2278*4947cdc7SCole Faustx = 1 2279*4947cdc7SCole Faust_ = [x for x in [2]] # new variable x is local to the comprehension 2280*4947cdc7SCole Faustprint(x) # 1 2281*4947cdc7SCole Faust``` 2282*4947cdc7SCole Faust 2283*4947cdc7SCole FaustThe operand of a comprehension's first clause (always a `for`) is 2284*4947cdc7SCole Faustresolved in the lexical block enclosing the comprehension. 2285*4947cdc7SCole FaustIn the examples below, identifiers referring to the outer variable 2286*4947cdc7SCole Faustnamed `x` have been distinguished by subscript. 2287*4947cdc7SCole Faust 2288*4947cdc7SCole Faust```python 2289*4947cdc7SCole Faustx₀ = (1, 2, 3) 2290*4947cdc7SCole Faust[x*x for x in x₀] # [1, 4, 9] 2291*4947cdc7SCole Faust[x*x for x in x₀ if x%2 == 0] # [4] 2292*4947cdc7SCole Faust``` 2293*4947cdc7SCole Faust 2294*4947cdc7SCole FaustAll subsequent `for` and `if` expressions are resolved within the 2295*4947cdc7SCole Faustcomprehension's lexical block, as in this rather obscure example: 2296*4947cdc7SCole Faust 2297*4947cdc7SCole Faust```python 2298*4947cdc7SCole Faustx₀ = ([1, 2], [3, 4], [5, 6]) 2299*4947cdc7SCole Faust[x*x for x in x₀ for x in x if x%2 == 0] # [4, 16, 36] 2300*4947cdc7SCole Faust``` 2301*4947cdc7SCole Faust 2302*4947cdc7SCole Faustwhich would be more clearly rewritten as: 2303*4947cdc7SCole Faust 2304*4947cdc7SCole Faust```python 2305*4947cdc7SCole Faustx = ([1, 2], [3, 4], [5, 6]) 2306*4947cdc7SCole Faust[z*z for y in x for z in y if z%2 == 0] # [4, 16, 36] 2307*4947cdc7SCole Faust``` 2308*4947cdc7SCole Faust 2309*4947cdc7SCole Faust 2310*4947cdc7SCole Faust### Function and method calls 2311*4947cdc7SCole Faust 2312*4947cdc7SCole Faust```grammar {.good} 2313*4947cdc7SCole FaustCallSuffix = '(' [Arguments [',']] ')' . 2314*4947cdc7SCole Faust 2315*4947cdc7SCole FaustArguments = Argument {',' Argument} . 2316*4947cdc7SCole FaustArgument = Test | identifier '=' Test | '*' Test | '**' Test . 2317*4947cdc7SCole Faust``` 2318*4947cdc7SCole Faust 2319*4947cdc7SCole FaustA value `f` of type `function` or `builtin_function_or_method` may be called using the expression `f(...)`. 2320*4947cdc7SCole FaustApplications may define additional types whose values may be called in the same way. 2321*4947cdc7SCole Faust 2322*4947cdc7SCole FaustA method call such as `filename.endswith(".star")` is the composition 2323*4947cdc7SCole Faustof two operations, `m = filename.endswith` and `m(".star")`. 2324*4947cdc7SCole FaustThe first, a dot operation, yields a _bound method_, a function value 2325*4947cdc7SCole Faustthat pairs a receiver value (the `filename` string) with a choice of 2326*4947cdc7SCole Faustmethod ([string·endswith](#string·endswith)). 2327*4947cdc7SCole Faust 2328*4947cdc7SCole FaustOnly built-in or application-defined types may have methods. 2329*4947cdc7SCole Faust 2330*4947cdc7SCole FaustSee [Functions](#functions) for an explanation of function parameter passing. 2331*4947cdc7SCole Faust 2332*4947cdc7SCole Faust### Dot expressions 2333*4947cdc7SCole Faust 2334*4947cdc7SCole FaustA dot expression `x.f` selects the attribute `f` (a field or method) 2335*4947cdc7SCole Faustof the value `x`. 2336*4947cdc7SCole Faust 2337*4947cdc7SCole FaustFields are possessed by none of the main Starlark [data types](#data-types), 2338*4947cdc7SCole Faustbut some application-defined types have them. 2339*4947cdc7SCole FaustMethods belong to the built-in types `string`, `list`, `dict`, and 2340*4947cdc7SCole Faust`set`, and to many application-defined types. 2341*4947cdc7SCole Faust 2342*4947cdc7SCole Faust```grammar {.good} 2343*4947cdc7SCole FaustDotSuffix = '.' identifier . 2344*4947cdc7SCole Faust``` 2345*4947cdc7SCole Faust 2346*4947cdc7SCole FaustA dot expression fails if the value does not have an attribute of the 2347*4947cdc7SCole Faustspecified name. 2348*4947cdc7SCole Faust 2349*4947cdc7SCole FaustUse the built-in function `hasattr(x, "f")` to ascertain whether a 2350*4947cdc7SCole Faustvalue has a specific attribute, or `dir(x)` to enumerate all its 2351*4947cdc7SCole Faustattributes. The `getattr(x, "f")` function can be used to select an 2352*4947cdc7SCole Faustattribute when the name `"f"` is not known statically. 2353*4947cdc7SCole Faust 2354*4947cdc7SCole FaustA dot expression that selects a method typically appears within a call 2355*4947cdc7SCole Faustexpression, as in these examples: 2356*4947cdc7SCole Faust 2357*4947cdc7SCole Faust```python 2358*4947cdc7SCole Faust["able", "baker", "charlie"].index("baker") # 1 2359*4947cdc7SCole Faust"banana".count("a") # 3 2360*4947cdc7SCole Faust"banana".reverse() # error: string has no .reverse field or method 2361*4947cdc7SCole Faust``` 2362*4947cdc7SCole Faust 2363*4947cdc7SCole FaustBut when not called immediately, the dot expression evaluates to a 2364*4947cdc7SCole Faust_bound method_, that is, a method coupled to a specific receiver 2365*4947cdc7SCole Faustvalue. A bound method can be called like an ordinary function, 2366*4947cdc7SCole Faustwithout a receiver argument: 2367*4947cdc7SCole Faust 2368*4947cdc7SCole Faust```python 2369*4947cdc7SCole Faustf = "banana".count 2370*4947cdc7SCole Faustf # <built-in method count of string value> 2371*4947cdc7SCole Faustf("a") # 3 2372*4947cdc7SCole Faustf("n") # 2 2373*4947cdc7SCole Faust``` 2374*4947cdc7SCole Faust 2375*4947cdc7SCole Faust### Index expressions 2376*4947cdc7SCole Faust 2377*4947cdc7SCole FaustAn index expression `a[i]` yields the `i`th element of an _indexable_ 2378*4947cdc7SCole Fausttype such as a string, tuple, or list. The index `i` must be an `int` 2379*4947cdc7SCole Faustvalue in the range -`n` ≤ `i` < `n`, where `n` is `len(a)`; any other 2380*4947cdc7SCole Faustindex results in an error. 2381*4947cdc7SCole Faust 2382*4947cdc7SCole Faust```grammar {.good} 2383*4947cdc7SCole FaustSliceSuffix = '[' [Expression] [':' Test [':' Test]] ']' . 2384*4947cdc7SCole Faust``` 2385*4947cdc7SCole Faust 2386*4947cdc7SCole FaustA valid negative index `i` behaves like the non-negative index `n+i`, 2387*4947cdc7SCole Faustallowing for convenient indexing relative to the end of the 2388*4947cdc7SCole Faustsequence. 2389*4947cdc7SCole Faust 2390*4947cdc7SCole Faust```python 2391*4947cdc7SCole Faust"abc"[0] # "a" 2392*4947cdc7SCole Faust"abc"[1] # "b" 2393*4947cdc7SCole Faust"abc"[-1] # "c" 2394*4947cdc7SCole Faust 2395*4947cdc7SCole Faust("zero", "one", "two")[0] # "zero" 2396*4947cdc7SCole Faust("zero", "one", "two")[1] # "one" 2397*4947cdc7SCole Faust("zero", "one", "two")[-1] # "two" 2398*4947cdc7SCole Faust``` 2399*4947cdc7SCole Faust 2400*4947cdc7SCole FaustAn index expression `d[key]` may also be applied to a dictionary `d`, 2401*4947cdc7SCole Faustto obtain the value associated with the specified key. It is an error 2402*4947cdc7SCole Faustif the dictionary contains no such key. 2403*4947cdc7SCole Faust 2404*4947cdc7SCole FaustAn index expression appearing on the left side of an assignment causes 2405*4947cdc7SCole Faustthe specified list or dictionary element to be updated: 2406*4947cdc7SCole Faust 2407*4947cdc7SCole Faust```starlark 2408*4947cdc7SCole Fausta = range(3) # a == [0, 1, 2] 2409*4947cdc7SCole Fausta[2] = 7 # a == [0, 1, 7] 2410*4947cdc7SCole Faust 2411*4947cdc7SCole Faustcoins["suzie b"] = 100 2412*4947cdc7SCole Faust``` 2413*4947cdc7SCole Faust 2414*4947cdc7SCole FaustIt is a dynamic error to attempt to update an element of an immutable 2415*4947cdc7SCole Fausttype, such as a tuple or string, or a frozen value of a mutable type. 2416*4947cdc7SCole Faust 2417*4947cdc7SCole Faust### Slice expressions 2418*4947cdc7SCole Faust 2419*4947cdc7SCole FaustA slice expression `a[start:stop:stride]` yields a new value containing a 2420*4947cdc7SCole Faustsub-sequence of `a`, which must be a string, tuple, or list. 2421*4947cdc7SCole Faust 2422*4947cdc7SCole Faust```grammar {.good} 2423*4947cdc7SCole FaustSliceSuffix = '[' [Expression] [':' Test [':' Test]] ']' . 2424*4947cdc7SCole Faust``` 2425*4947cdc7SCole Faust 2426*4947cdc7SCole FaustEach of the `start`, `stop`, and `stride` operands is optional; 2427*4947cdc7SCole Faustif present, and not `None`, each must be an integer. 2428*4947cdc7SCole FaustThe `stride` value defaults to 1. 2429*4947cdc7SCole FaustIf the stride is not specified, the colon preceding it may be omitted too. 2430*4947cdc7SCole FaustIt is an error to specify a stride of zero. 2431*4947cdc7SCole Faust 2432*4947cdc7SCole FaustConceptually, these operands specify a sequence of values `i` starting 2433*4947cdc7SCole Faustat `start` and successively adding `stride` until `i` reaches or 2434*4947cdc7SCole Faustpasses `stop`. The result consists of the concatenation of values of 2435*4947cdc7SCole Faust`a[i]` for which `i` is valid.` 2436*4947cdc7SCole Faust 2437*4947cdc7SCole FaustThe effective start and stop indices are computed from the three 2438*4947cdc7SCole Faustoperands as follows. Let `n` be the length of the sequence. 2439*4947cdc7SCole Faust 2440*4947cdc7SCole Faust<b>If the stride is positive:</b> 2441*4947cdc7SCole FaustIf the `start` operand was omitted, it defaults to -infinity. 2442*4947cdc7SCole FaustIf the `end` operand was omitted, it defaults to +infinity. 2443*4947cdc7SCole FaustFor either operand, if a negative value was supplied, `n` is added to it. 2444*4947cdc7SCole FaustThe `start` and `end` values are then "clamped" to the 2445*4947cdc7SCole Faustnearest value in the range 0 to `n`, inclusive. 2446*4947cdc7SCole Faust 2447*4947cdc7SCole Faust<b>If the stride is negative:</b> 2448*4947cdc7SCole FaustIf the `start` operand was omitted, it defaults to +infinity. 2449*4947cdc7SCole FaustIf the `end` operand was omitted, it defaults to -infinity. 2450*4947cdc7SCole FaustFor either operand, if a negative value was supplied, `n` is added to it. 2451*4947cdc7SCole FaustThe `start` and `end` values are then "clamped" to the 2452*4947cdc7SCole Faustnearest value in the range -1 to `n`-1, inclusive. 2453*4947cdc7SCole Faust 2454*4947cdc7SCole Faust```python 2455*4947cdc7SCole Faust"abc"[1:] # "bc" (remove first element) 2456*4947cdc7SCole Faust"abc"[:-1] # "ab" (remove last element) 2457*4947cdc7SCole Faust"abc"[1:-1] # "b" (remove first and last element) 2458*4947cdc7SCole Faust"banana"[1::2] # "aaa" (select alternate elements starting at index 1) 2459*4947cdc7SCole Faust"banana"[4::-2] # "nnb" (select alternate elements in reverse, starting at index 4) 2460*4947cdc7SCole Faust``` 2461*4947cdc7SCole Faust 2462*4947cdc7SCole FaustUnlike Python, Starlark does not allow a slice expression on the left 2463*4947cdc7SCole Faustside of an assignment. 2464*4947cdc7SCole Faust 2465*4947cdc7SCole FaustSlicing a tuple or string may be more efficient than slicing a list 2466*4947cdc7SCole Faustbecause tuples and strings are immutable, so the result of the 2467*4947cdc7SCole Faustoperation can share the underlying representation of the original 2468*4947cdc7SCole Faustoperand (when the stride is 1). By contrast, slicing a list requires 2469*4947cdc7SCole Faustthe creation of a new list and copying of the necessary elements. 2470*4947cdc7SCole Faust 2471*4947cdc7SCole Faust<!-- TODO tighten up this section --> 2472*4947cdc7SCole Faust 2473*4947cdc7SCole Faust### Lambda expressions 2474*4947cdc7SCole Faust 2475*4947cdc7SCole FaustA `lambda` expression yields a new function value. 2476*4947cdc7SCole Faust 2477*4947cdc7SCole Faust```grammar {.good} 2478*4947cdc7SCole FaustLambdaExpr = 'lambda' [Parameters] ':' Test . 2479*4947cdc7SCole Faust 2480*4947cdc7SCole FaustParameters = Parameter {',' Parameter} . 2481*4947cdc7SCole FaustParameter = identifier 2482*4947cdc7SCole Faust | identifier '=' Test 2483*4947cdc7SCole Faust | '*' 2484*4947cdc7SCole Faust | '*' identifier 2485*4947cdc7SCole Faust | '**' identifier 2486*4947cdc7SCole Faust . 2487*4947cdc7SCole Faust``` 2488*4947cdc7SCole Faust 2489*4947cdc7SCole FaustSyntactically, a lambda expression consists of the keyword `lambda`, 2490*4947cdc7SCole Faustfollowed by a parameter list like that of a `def` statement but 2491*4947cdc7SCole Faustunparenthesized, then a colon `:`, and a single expression, the 2492*4947cdc7SCole Faust_function body_. 2493*4947cdc7SCole Faust 2494*4947cdc7SCole FaustExample: 2495*4947cdc7SCole Faust 2496*4947cdc7SCole Faust```python 2497*4947cdc7SCole Faustdef map(f, list): 2498*4947cdc7SCole Faust return [f(x) for x in list] 2499*4947cdc7SCole Faust 2500*4947cdc7SCole Faustmap(lambda x: 2*x, range(3)) # [2, 4, 6] 2501*4947cdc7SCole Faust``` 2502*4947cdc7SCole Faust 2503*4947cdc7SCole FaustAs with functions created by a `def` statement, a lambda function 2504*4947cdc7SCole Faustcaptures the syntax of its body, the default values of any optional 2505*4947cdc7SCole Faustparameters, the value of each free variable appearing in its body, and 2506*4947cdc7SCole Faustthe global dictionary of the current module. 2507*4947cdc7SCole Faust 2508*4947cdc7SCole FaustThe name of a function created by a lambda expression is `"lambda"`. 2509*4947cdc7SCole Faust 2510*4947cdc7SCole FaustThe two statements below are essentially equivalent, but the 2511*4947cdc7SCole Faustfunction created by the `def` statement is named `twice` and the 2512*4947cdc7SCole Faustfunction created by the lambda expression is named `lambda`. 2513*4947cdc7SCole Faust 2514*4947cdc7SCole Faust```python 2515*4947cdc7SCole Faustdef twice(x): 2516*4947cdc7SCole Faust return x * 2 2517*4947cdc7SCole Faust 2518*4947cdc7SCole Fausttwice = lambda x: x * 2 2519*4947cdc7SCole Faust``` 2520*4947cdc7SCole Faust 2521*4947cdc7SCole Faust## Statements 2522*4947cdc7SCole Faust 2523*4947cdc7SCole Faust```grammar {.good} 2524*4947cdc7SCole FaustStatement = DefStmt | IfStmt | ForStmt | SimpleStmt . 2525*4947cdc7SCole FaustSimpleStmt = SmallStmt {';' SmallStmt} [';'] '\n' . 2526*4947cdc7SCole FaustSmallStmt = ReturnStmt 2527*4947cdc7SCole Faust | BreakStmt | ContinueStmt | PassStmt 2528*4947cdc7SCole Faust | AssignStmt 2529*4947cdc7SCole Faust | ExprStmt 2530*4947cdc7SCole Faust | LoadStmt 2531*4947cdc7SCole Faust . 2532*4947cdc7SCole Faust``` 2533*4947cdc7SCole Faust 2534*4947cdc7SCole Faust### Pass statements 2535*4947cdc7SCole Faust 2536*4947cdc7SCole FaustA `pass` statement does nothing. Use a `pass` statement when the 2537*4947cdc7SCole Faustsyntax requires a statement but no behavior is required, such as the 2538*4947cdc7SCole Faustbody of a function that does nothing. 2539*4947cdc7SCole Faust 2540*4947cdc7SCole Faust```grammar {.good} 2541*4947cdc7SCole FaustPassStmt = 'pass' . 2542*4947cdc7SCole Faust``` 2543*4947cdc7SCole Faust 2544*4947cdc7SCole FaustExample: 2545*4947cdc7SCole Faust 2546*4947cdc7SCole Faust```python 2547*4947cdc7SCole Faustdef noop(): 2548*4947cdc7SCole Faust pass 2549*4947cdc7SCole Faust 2550*4947cdc7SCole Faustdef list_to_dict(items): 2551*4947cdc7SCole Faust # Convert list of tuples to dict 2552*4947cdc7SCole Faust m = {} 2553*4947cdc7SCole Faust for k, m[k] in items: 2554*4947cdc7SCole Faust pass 2555*4947cdc7SCole Faust return m 2556*4947cdc7SCole Faust``` 2557*4947cdc7SCole Faust 2558*4947cdc7SCole Faust### Assignments 2559*4947cdc7SCole Faust 2560*4947cdc7SCole FaustAn assignment statement has the form `lhs = rhs`. It evaluates the 2561*4947cdc7SCole Faustexpression on the right-hand side then assigns its value (or values) to 2562*4947cdc7SCole Faustthe variable (or variables) on the left-hand side. 2563*4947cdc7SCole Faust 2564*4947cdc7SCole Faust```grammar {.good} 2565*4947cdc7SCole FaustAssignStmt = Expression '=' Expression . 2566*4947cdc7SCole Faust``` 2567*4947cdc7SCole Faust 2568*4947cdc7SCole FaustThe expression on the left-hand side is called a _target_. The 2569*4947cdc7SCole Faustsimplest target is the name of a variable, but a target may also have 2570*4947cdc7SCole Faustthe form of an index expression, to update the element of a list or 2571*4947cdc7SCole Faustdictionary, or a dot expression, to update the field of an object: 2572*4947cdc7SCole Faust 2573*4947cdc7SCole Faust```python 2574*4947cdc7SCole Faustk = 1 2575*4947cdc7SCole Fausta[i] = v 2576*4947cdc7SCole Faustm.f = "" 2577*4947cdc7SCole Faust``` 2578*4947cdc7SCole Faust 2579*4947cdc7SCole FaustCompound targets may consist of a comma-separated list of 2580*4947cdc7SCole Faustsubtargets, optionally surrounded by parentheses or square brackets, 2581*4947cdc7SCole Faustand targets may be nested arbitarily in this way. 2582*4947cdc7SCole FaustAn assignment to a compound target checks that the right-hand value is a 2583*4947cdc7SCole Faustsequence with the same number of elements as the target. 2584*4947cdc7SCole FaustEach element of the sequence is then assigned to the corresponding 2585*4947cdc7SCole Faustelement of the target, recursively applying the same logic. 2586*4947cdc7SCole Faust 2587*4947cdc7SCole Faust```python 2588*4947cdc7SCole Faustpi, e = 3.141, 2.718 2589*4947cdc7SCole Faust(x, y) = f() 2590*4947cdc7SCole Faust[zero, one, two] = range(3) 2591*4947cdc7SCole Faust 2592*4947cdc7SCole Faust[(a, b), (c, d)] = {"a": "b", "c": "d"}.items() 2593*4947cdc7SCole Fausta, b = {"a": 1, "b": 2} 2594*4947cdc7SCole Faust``` 2595*4947cdc7SCole Faust 2596*4947cdc7SCole FaustThe same process for assigning a value to a target expression is used 2597*4947cdc7SCole Faustin `for` loops and in comprehensions. 2598*4947cdc7SCole Faust 2599*4947cdc7SCole Faust 2600*4947cdc7SCole Faust### Augmented assignments 2601*4947cdc7SCole Faust 2602*4947cdc7SCole FaustAn augmented assignment, which has the form `lhs op= rhs` updates the 2603*4947cdc7SCole Faustvariable `lhs` by applying a binary arithmetic operator `op` (one of 2604*4947cdc7SCole Faust`+`, `-`, `*`, `/`, `//`, `%`, `&`, `|`, `^`, `<<`, `>>`) to the previous 2605*4947cdc7SCole Faustvalue of `lhs` and the value of `rhs`. 2606*4947cdc7SCole Faust 2607*4947cdc7SCole Faust```grammar {.good} 2608*4947cdc7SCole FaustAssignStmt = Expression ('+=' | '-=' | '*=' | '/=' | '//=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=') Expression . 2609*4947cdc7SCole Faust``` 2610*4947cdc7SCole Faust 2611*4947cdc7SCole FaustThe left-hand side must be a simple target: 2612*4947cdc7SCole Fausta name, an index expression, or a dot expression. 2613*4947cdc7SCole Faust 2614*4947cdc7SCole Faust```python 2615*4947cdc7SCole Faustx -= 1 2616*4947cdc7SCole Faustx.filename += ".star" 2617*4947cdc7SCole Fausta[index()] *= 2 2618*4947cdc7SCole Faust``` 2619*4947cdc7SCole Faust 2620*4947cdc7SCole FaustAny subexpressions in the target on the left-hand side are evaluated 2621*4947cdc7SCole Faustexactly once, before the evaluation of `rhs`. 2622*4947cdc7SCole FaustThe first two assignments above are thus equivalent to: 2623*4947cdc7SCole Faust 2624*4947cdc7SCole Faust```python 2625*4947cdc7SCole Faustx = x - 1 2626*4947cdc7SCole Faustx.filename = x.filename + ".star" 2627*4947cdc7SCole Faust``` 2628*4947cdc7SCole Faust 2629*4947cdc7SCole Faustand the third assignment is similar in effect to the following two 2630*4947cdc7SCole Fauststatements but does not declare a new temporary variable `i`: 2631*4947cdc7SCole Faust 2632*4947cdc7SCole Faust```python 2633*4947cdc7SCole Fausti = index() 2634*4947cdc7SCole Fausta[i] = a[i] * 2 2635*4947cdc7SCole Faust``` 2636*4947cdc7SCole Faust 2637*4947cdc7SCole Faust### Function definitions 2638*4947cdc7SCole Faust 2639*4947cdc7SCole FaustA `def` statement creates a named function and assigns it to a variable. 2640*4947cdc7SCole Faust 2641*4947cdc7SCole Faust```grammar {.good} 2642*4947cdc7SCole FaustDefStmt = 'def' identifier '(' [Parameters [',']] ')' ':' Suite . 2643*4947cdc7SCole Faust``` 2644*4947cdc7SCole Faust 2645*4947cdc7SCole FaustExample: 2646*4947cdc7SCole Faust 2647*4947cdc7SCole Faust```python 2648*4947cdc7SCole Faustdef twice(x): 2649*4947cdc7SCole Faust return x * 2 2650*4947cdc7SCole Faust 2651*4947cdc7SCole Fauststr(twice) # "<function twice>" 2652*4947cdc7SCole Fausttwice(2) # 4 2653*4947cdc7SCole Fausttwice("two") # "twotwo" 2654*4947cdc7SCole Faust``` 2655*4947cdc7SCole Faust 2656*4947cdc7SCole FaustThe function's name is preceded by the `def` keyword and followed by 2657*4947cdc7SCole Faustthe parameter list (which is enclosed in parentheses), a colon, and 2658*4947cdc7SCole Faustthen an indented block of statements which form the body of the function. 2659*4947cdc7SCole Faust 2660*4947cdc7SCole FaustThe parameter list is a comma-separated list whose elements are of 2661*4947cdc7SCole Faustseveral kinds. First come zero or more required parameters, which are 2662*4947cdc7SCole Faustsimple identifiers; all calls must provide an argument value for these parameters. 2663*4947cdc7SCole Faust 2664*4947cdc7SCole FaustThe required parameters are followed by zero or more optional 2665*4947cdc7SCole Faustparameters, of the form `name=expression`. The expression specifies 2666*4947cdc7SCole Faustthe default value for the parameter for use in calls that do not 2667*4947cdc7SCole Faustprovide an argument value for it. 2668*4947cdc7SCole Faust 2669*4947cdc7SCole FaustThe required parameters are optionally followed by a single parameter 2670*4947cdc7SCole Faustname preceded by a `*`. This is the called the _varargs_ parameter, 2671*4947cdc7SCole Faustand it accumulates surplus positional arguments specified by a call. 2672*4947cdc7SCole FaustIt is conventionally named `*args`. 2673*4947cdc7SCole Faust 2674*4947cdc7SCole FaustThe varargs parameter may be followed by zero or more 2675*4947cdc7SCole Faustparameters, again of the forms `name` or `name=expression`, 2676*4947cdc7SCole Faustbut these parameters differ from earlier ones in that they are 2677*4947cdc7SCole Faust_keyword-only_: if a call provides their values, it must do so as 2678*4947cdc7SCole Faustkeyword arguments, not positional ones. 2679*4947cdc7SCole Faust 2680*4947cdc7SCole Faust```python 2681*4947cdc7SCole Faustdef f(a, *, b=2, c): 2682*4947cdc7SCole Faust print(a, b, c) 2683*4947cdc7SCole Faust 2684*4947cdc7SCole Faustf(1) # error: function f missing 1 argument (c) 2685*4947cdc7SCole Faustf(1, 3) # error: function f accepts 1 positional argument (2 given) 2686*4947cdc7SCole Faustf(1, c=3) # "1 2 3" 2687*4947cdc7SCole Faust 2688*4947cdc7SCole Faustdef g(a, *args, b=2, c): 2689*4947cdc7SCole Faust print(a, b, c, args) 2690*4947cdc7SCole Faust 2691*4947cdc7SCole Faustg(1, 3) # error: function g missing 1 argument (c) 2692*4947cdc7SCole Faustg(1, 4, c=3) # "1 2 3 (4,)" 2693*4947cdc7SCole Faust 2694*4947cdc7SCole Faust``` 2695*4947cdc7SCole Faust 2696*4947cdc7SCole FaustA non-variadic function may also declare keyword-only parameters, 2697*4947cdc7SCole Faustby using a bare `*` in place of the `*args` parameter. 2698*4947cdc7SCole FaustThis form does not declare a parameter but marks the boundary 2699*4947cdc7SCole Faustbetween the earlier parameters and the keyword-only parameters. 2700*4947cdc7SCole FaustThis form must be followed by at least one optional parameter. 2701*4947cdc7SCole Faust 2702*4947cdc7SCole FaustFinally, there may be an optional parameter name preceded by `**`. 2703*4947cdc7SCole FaustThis is called the _keyword arguments_ parameter, and accumulates in a 2704*4947cdc7SCole Faustdictionary any surplus `name=value` arguments that do not match a 2705*4947cdc7SCole Faustprior parameter. It is conventionally named `**kwargs`. 2706*4947cdc7SCole Faust 2707*4947cdc7SCole FaustThe final parameter may be followed by a trailing comma. 2708*4947cdc7SCole Faust 2709*4947cdc7SCole FaustHere are some example parameter lists: 2710*4947cdc7SCole Faust 2711*4947cdc7SCole Faust```python 2712*4947cdc7SCole Faustdef f(): pass 2713*4947cdc7SCole Faustdef f(a, b, c): pass 2714*4947cdc7SCole Faustdef f(a, b, c=1): pass 2715*4947cdc7SCole Faustdef f(a, b, c=1, *args): pass 2716*4947cdc7SCole Faustdef f(a, b, c=1, *args, **kwargs): pass 2717*4947cdc7SCole Faustdef f(**kwargs): pass 2718*4947cdc7SCole Faustdef f(a, b, c=1, *, d=1): pass 2719*4947cdc7SCole Faust 2720*4947cdc7SCole Faustdef f( 2721*4947cdc7SCole Faust a, 2722*4947cdc7SCole Faust *args, 2723*4947cdc7SCole Faust **kwargs, 2724*4947cdc7SCole Faust) 2725*4947cdc7SCole Faust``` 2726*4947cdc7SCole Faust 2727*4947cdc7SCole FaustExecution of a `def` statement creates a new function object. The 2728*4947cdc7SCole Faustfunction object contains: the syntax of the function body; the default 2729*4947cdc7SCole Faustvalue for each optional parameter; the value of each free variable 2730*4947cdc7SCole Faustreferenced within the function body; and the global dictionary of the 2731*4947cdc7SCole Faustcurrent module. 2732*4947cdc7SCole Faust 2733*4947cdc7SCole Faust<!-- this is too implementation-oriented; it's not a spec. --> 2734*4947cdc7SCole Faust 2735*4947cdc7SCole Faust 2736*4947cdc7SCole Faust### Return statements 2737*4947cdc7SCole Faust 2738*4947cdc7SCole FaustA `return` statement ends the execution of a function and returns a 2739*4947cdc7SCole Faustvalue to the caller of the function. 2740*4947cdc7SCole Faust 2741*4947cdc7SCole Faust```grammar {.good} 2742*4947cdc7SCole FaustReturnStmt = 'return' [Expression] . 2743*4947cdc7SCole Faust``` 2744*4947cdc7SCole Faust 2745*4947cdc7SCole FaustA return statement may have zero, one, or more 2746*4947cdc7SCole Faustresult expressions separated by commas. 2747*4947cdc7SCole FaustWith no expressions, the function has the result `None`. 2748*4947cdc7SCole FaustWith a single expression, the function's result is the value of that expression. 2749*4947cdc7SCole FaustWith multiple expressions, the function's result is a tuple. 2750*4947cdc7SCole Faust 2751*4947cdc7SCole Faust```python 2752*4947cdc7SCole Faustreturn # returns None 2753*4947cdc7SCole Faustreturn 1 # returns 1 2754*4947cdc7SCole Faustreturn 1, 2 # returns (1, 2) 2755*4947cdc7SCole Faust``` 2756*4947cdc7SCole Faust 2757*4947cdc7SCole Faust### Expression statements 2758*4947cdc7SCole Faust 2759*4947cdc7SCole FaustAn expression statement evaluates an expression and discards its result. 2760*4947cdc7SCole Faust 2761*4947cdc7SCole Faust```grammar {.good} 2762*4947cdc7SCole FaustExprStmt = Expression . 2763*4947cdc7SCole Faust``` 2764*4947cdc7SCole Faust 2765*4947cdc7SCole FaustAny expression may be used as a statement, but an expression statement is 2766*4947cdc7SCole Faustmost often used to call a function for its side effects. 2767*4947cdc7SCole Faust 2768*4947cdc7SCole Faust```python 2769*4947cdc7SCole Faustlist.append(1) 2770*4947cdc7SCole Faust``` 2771*4947cdc7SCole Faust 2772*4947cdc7SCole Faust### If statements 2773*4947cdc7SCole Faust 2774*4947cdc7SCole FaustAn `if` statement evaluates an expression (the _condition_), then, if 2775*4947cdc7SCole Faustthe truth value of the condition is `True`, executes a list of 2776*4947cdc7SCole Fauststatements. 2777*4947cdc7SCole Faust 2778*4947cdc7SCole Faust```grammar {.good} 2779*4947cdc7SCole FaustIfStmt = 'if' Test ':' Suite {'elif' Test ':' Suite} ['else' ':' Suite] . 2780*4947cdc7SCole Faust``` 2781*4947cdc7SCole Faust 2782*4947cdc7SCole FaustExample: 2783*4947cdc7SCole Faust 2784*4947cdc7SCole Faust```python 2785*4947cdc7SCole Faustif score >= 100: 2786*4947cdc7SCole Faust print("You win!") 2787*4947cdc7SCole Faust return 2788*4947cdc7SCole Faust``` 2789*4947cdc7SCole Faust 2790*4947cdc7SCole FaustAn `if` statement may have an `else` block defining a second list of 2791*4947cdc7SCole Fauststatements to be executed if the condition is false. 2792*4947cdc7SCole Faust 2793*4947cdc7SCole Faust```python 2794*4947cdc7SCole Faustif score >= 100: 2795*4947cdc7SCole Faust print("You win!") 2796*4947cdc7SCole Faust return 2797*4947cdc7SCole Faustelse: 2798*4947cdc7SCole Faust print("Keep trying...") 2799*4947cdc7SCole Faust continue 2800*4947cdc7SCole Faust``` 2801*4947cdc7SCole Faust 2802*4947cdc7SCole FaustIt is common for the `else` block to contain another `if` statement. 2803*4947cdc7SCole FaustTo avoid increasing the nesting depth unnecessarily, the `else` and 2804*4947cdc7SCole Faustfollowing `if` may be combined as `elif`: 2805*4947cdc7SCole Faust 2806*4947cdc7SCole Faust```python 2807*4947cdc7SCole Faustif x > 0: 2808*4947cdc7SCole Faust result = +1 2809*4947cdc7SCole Faustelif x < 0: 2810*4947cdc7SCole Faust result = -1 2811*4947cdc7SCole Faustelse: 2812*4947cdc7SCole Faust result = 0 2813*4947cdc7SCole Faust``` 2814*4947cdc7SCole Faust 2815*4947cdc7SCole FaustAn `if` statement is permitted only within a function definition. 2816*4947cdc7SCole FaustAn `if` statement at top level results in a static error. 2817*4947cdc7SCole Faust 2818*4947cdc7SCole Faust<b>Implementation note:</b> 2819*4947cdc7SCole FaustThe Go implementation of Starlark permits `if`-statements to appear at top level 2820*4947cdc7SCole Faustif the `-globalreassign` flag is enabled. 2821*4947cdc7SCole Faust 2822*4947cdc7SCole Faust 2823*4947cdc7SCole Faust### While loops 2824*4947cdc7SCole Faust 2825*4947cdc7SCole FaustA `while` loop evaluates an expression (the _condition_) and if the truth 2826*4947cdc7SCole Faustvalue of the condition is `True`, it executes a list of statement and repeats 2827*4947cdc7SCole Faustthe process until the truth value of the condition becomes `False`. 2828*4947cdc7SCole Faust 2829*4947cdc7SCole Faust```grammar {.good} 2830*4947cdc7SCole FaustWhileStmt = 'while' Test ':' Suite . 2831*4947cdc7SCole Faust``` 2832*4947cdc7SCole Faust 2833*4947cdc7SCole FaustExample: 2834*4947cdc7SCole Faust 2835*4947cdc7SCole Faust```python 2836*4947cdc7SCole Faustwhile n > 0: 2837*4947cdc7SCole Faust r = r + n 2838*4947cdc7SCole Faust n = n - 1 2839*4947cdc7SCole Faust``` 2840*4947cdc7SCole Faust 2841*4947cdc7SCole FaustA `while` statement is permitted only within a function definition. 2842*4947cdc7SCole FaustA `while` statement at top level results in a static error. 2843*4947cdc7SCole Faust 2844*4947cdc7SCole Faust<b>Implementation note:</b> 2845*4947cdc7SCole FaustThe Go implementation of Starlark permits `while` loops only if the `-recursion` flag is enabled. 2846*4947cdc7SCole FaustA `while` statement is permitted at top level if the `-globalreassign` flag is enabled. 2847*4947cdc7SCole Faust 2848*4947cdc7SCole Faust 2849*4947cdc7SCole Faust### For loops 2850*4947cdc7SCole Faust 2851*4947cdc7SCole FaustA `for` loop evaluates its operand, which must be an iterable value. 2852*4947cdc7SCole FaustThen, for each element of the iterable's sequence, the loop assigns 2853*4947cdc7SCole Faustthe successive element values to one or more variables and executes a 2854*4947cdc7SCole Faustlist of statements, the _loop body_. 2855*4947cdc7SCole Faust 2856*4947cdc7SCole Faust```grammar {.good} 2857*4947cdc7SCole FaustForStmt = 'for' LoopVariables 'in' Expression ':' Suite . 2858*4947cdc7SCole Faust``` 2859*4947cdc7SCole Faust 2860*4947cdc7SCole FaustExample: 2861*4947cdc7SCole Faust 2862*4947cdc7SCole Faust```python 2863*4947cdc7SCole Faustfor x in range(10): 2864*4947cdc7SCole Faust print(10) 2865*4947cdc7SCole Faust``` 2866*4947cdc7SCole Faust 2867*4947cdc7SCole FaustThe assignment of each value to the loop variables follows the same 2868*4947cdc7SCole Faustrules as an ordinary assignment. In this example, two-element lists 2869*4947cdc7SCole Faustare repeatedly assigned to the pair of variables (a, i): 2870*4947cdc7SCole Faust 2871*4947cdc7SCole Faust```python 2872*4947cdc7SCole Faustfor a, i in [["a", 1], ["b", 2], ["c", 3]]: 2873*4947cdc7SCole Faust print(a, i) # prints "a 1", "b 2", "c 3" 2874*4947cdc7SCole Faust``` 2875*4947cdc7SCole Faust 2876*4947cdc7SCole FaustBecause Starlark loops always iterate over a finite sequence, they are 2877*4947cdc7SCole Faustguaranteed to terminate, unlike loops in most languages which can 2878*4947cdc7SCole Faustexecute an arbitrary and perhaps unbounded number of iterations. 2879*4947cdc7SCole Faust 2880*4947cdc7SCole FaustWithin the body of a `for` loop, `break` and `continue` statements may 2881*4947cdc7SCole Faustbe used to stop the execution of the loop or advance to the next 2882*4947cdc7SCole Faustiteration. 2883*4947cdc7SCole Faust 2884*4947cdc7SCole FaustIn Starlark, a `for` loop is permitted only within a function definition. 2885*4947cdc7SCole FaustA `for` loop at top level results in a static error. 2886*4947cdc7SCole Faust 2887*4947cdc7SCole Faust<b>Implementation note:</b> 2888*4947cdc7SCole FaustThe Go implementation of Starlark permits loops to appear at top level 2889*4947cdc7SCole Faustif the `-globalreassign` flag is enabled. 2890*4947cdc7SCole Faust 2891*4947cdc7SCole Faust 2892*4947cdc7SCole Faust### Break and Continue 2893*4947cdc7SCole Faust 2894*4947cdc7SCole FaustThe `break` and `continue` statements terminate the current iteration 2895*4947cdc7SCole Faustof a `for` loop. Whereas the `continue` statement resumes the loop at 2896*4947cdc7SCole Faustthe next iteration, a `break` statement terminates the entire loop. 2897*4947cdc7SCole Faust 2898*4947cdc7SCole Faust```grammar {.good} 2899*4947cdc7SCole FaustBreakStmt = 'break' . 2900*4947cdc7SCole FaustContinueStmt = 'continue' . 2901*4947cdc7SCole Faust``` 2902*4947cdc7SCole Faust 2903*4947cdc7SCole FaustExample: 2904*4947cdc7SCole Faust 2905*4947cdc7SCole Faust```python 2906*4947cdc7SCole Faustfor x in range(10): 2907*4947cdc7SCole Faust if x%2 == 1: 2908*4947cdc7SCole Faust continue # skip odd numbers 2909*4947cdc7SCole Faust if x > 7: 2910*4947cdc7SCole Faust break # stop at 8 2911*4947cdc7SCole Faust print(x) # prints "0", "2", "4", "6" 2912*4947cdc7SCole Faust``` 2913*4947cdc7SCole Faust 2914*4947cdc7SCole FaustBoth statements affect only the innermost lexically enclosing loop. 2915*4947cdc7SCole FaustIt is a static error to use a `break` or `continue` statement outside a 2916*4947cdc7SCole Faustloop. 2917*4947cdc7SCole Faust 2918*4947cdc7SCole Faust 2919*4947cdc7SCole Faust### Load statements 2920*4947cdc7SCole Faust 2921*4947cdc7SCole FaustThe `load` statement loads another Starlark module, extracts one or 2922*4947cdc7SCole Faustmore values from it, and binds them to names in the current module. 2923*4947cdc7SCole Faust 2924*4947cdc7SCole Faust<!-- 2925*4947cdc7SCole FaustThe awkwardness of load statements is a consequence of staying a 2926*4947cdc7SCole Fauststrict subset of Python syntax, which allows reuse of existing tools 2927*4947cdc7SCole Faustsuch as editor support. Python import statements are inadequate for 2928*4947cdc7SCole FaustStarlark because they don't allow arbitrary file names for module names. 2929*4947cdc7SCole Faust--> 2930*4947cdc7SCole Faust 2931*4947cdc7SCole FaustSyntactically, a load statement looks like a function call `load(...)`. 2932*4947cdc7SCole Faust 2933*4947cdc7SCole Faust```grammar {.good} 2934*4947cdc7SCole FaustLoadStmt = 'load' '(' string {',' [identifier '='] string} [','] ')' . 2935*4947cdc7SCole Faust``` 2936*4947cdc7SCole Faust 2937*4947cdc7SCole FaustA load statement requires at least two "arguments". 2938*4947cdc7SCole FaustThe first must be a literal string; it identifies the module to load. 2939*4947cdc7SCole FaustIts interpretation is determined by the application into which the 2940*4947cdc7SCole FaustStarlark interpreter is embedded, and is not specified here. 2941*4947cdc7SCole Faust 2942*4947cdc7SCole FaustDuring execution, the application determines what action to take for a 2943*4947cdc7SCole Faustload statement. 2944*4947cdc7SCole FaustA typical implementation locates and executes a Starlark file, 2945*4947cdc7SCole Faustpopulating a cache of files executed so far to avoid duplicate work, 2946*4947cdc7SCole Faustto obtain a module, which is a mapping from global names to values. 2947*4947cdc7SCole Faust 2948*4947cdc7SCole FaustThe remaining arguments are a mixture of literal strings, such as 2949*4947cdc7SCole Faust`"x"`, or named literal strings, such as `y="x"`. 2950*4947cdc7SCole Faust 2951*4947cdc7SCole FaustThe literal string (`"x"`), which must denote a valid identifier not 2952*4947cdc7SCole Fauststarting with `_`, specifies the name to extract from the loaded 2953*4947cdc7SCole Faustmodule. In effect, names starting with `_` are not exported. 2954*4947cdc7SCole FaustThe name (`y`) specifies the local name; 2955*4947cdc7SCole Faustif no name is given, the local name matches the quoted name. 2956*4947cdc7SCole Faust 2957*4947cdc7SCole Faust```python 2958*4947cdc7SCole Faustload("module.star", "x", "y", "z") # assigns x, y, and z 2959*4947cdc7SCole Faustload("module.star", "x", y2="y", "z") # assigns x, y2, and z 2960*4947cdc7SCole Faust``` 2961*4947cdc7SCole Faust 2962*4947cdc7SCole FaustA load statement may not be nested inside any other statement. 2963*4947cdc7SCole Faust 2964*4947cdc7SCole Faust 2965*4947cdc7SCole Faust## Module execution 2966*4947cdc7SCole Faust 2967*4947cdc7SCole FaustEach Starlark file defines a _module_, which is a mapping from the 2968*4947cdc7SCole Faustnames of global variables to their values. 2969*4947cdc7SCole FaustWhen a Starlark file is executed, whether directly by the application 2970*4947cdc7SCole Faustor indirectly through a `load` statement, a new Starlark thread is 2971*4947cdc7SCole Faustcreated, and this thread executes all the top-level statements in the 2972*4947cdc7SCole Faustfile. 2973*4947cdc7SCole FaustBecause if-statements and for-loops cannot appear outside of a function, 2974*4947cdc7SCole Faustcontrol flows from top to bottom. 2975*4947cdc7SCole Faust 2976*4947cdc7SCole FaustIf execution reaches the end of the file, module initialization is 2977*4947cdc7SCole Faustsuccessful. 2978*4947cdc7SCole FaustAt that point, the value of each of the module's global variables is 2979*4947cdc7SCole Faustfrozen, rendering subsequent mutation impossible. 2980*4947cdc7SCole FaustThe module is then ready for use by another Starlark thread, such as 2981*4947cdc7SCole Faustone executing a load statement. 2982*4947cdc7SCole FaustSuch threads may access values or call functions defined in the loaded 2983*4947cdc7SCole Faustmodule. 2984*4947cdc7SCole Faust 2985*4947cdc7SCole FaustA Starlark thread may carry state on behalf of the application into 2986*4947cdc7SCole Faustwhich it is embedded, and application-defined functions may behave 2987*4947cdc7SCole Faustdifferently depending on this thread state. 2988*4947cdc7SCole FaustBecause module initialization always occurs in a new thread, thread 2989*4947cdc7SCole Fauststate is never carried from a higher-level module into a lower-level 2990*4947cdc7SCole Faustone. 2991*4947cdc7SCole FaustThe initialization behavior of a module is thus independent of 2992*4947cdc7SCole Faustwhichever module triggered its initialization. 2993*4947cdc7SCole Faust 2994*4947cdc7SCole FaustIf a Starlark thread encounters an error, execution stops and the error 2995*4947cdc7SCole Faustis reported to the application, along with a backtrace showing the 2996*4947cdc7SCole Fauststack of active function calls at the time of the error. 2997*4947cdc7SCole FaustIf an error occurs during initialization of a Starlark module, any 2998*4947cdc7SCole Faustactive `load` statements waiting for initialization of the module also 2999*4947cdc7SCole Faustfail. 3000*4947cdc7SCole Faust 3001*4947cdc7SCole FaustStarlark provides no mechanism by which errors can be handled within 3002*4947cdc7SCole Faustthe language. 3003*4947cdc7SCole Faust 3004*4947cdc7SCole Faust 3005*4947cdc7SCole Faust## Built-in constants and functions 3006*4947cdc7SCole Faust 3007*4947cdc7SCole FaustThe outermost block of the Starlark environment is known as the "predeclared" block. 3008*4947cdc7SCole FaustIt defines a number of fundamental values and functions needed by all Starlark programs, 3009*4947cdc7SCole Faustsuch as `None`, `True`, `False`, and `len`, and possibly additional 3010*4947cdc7SCole Faustapplication-specific names. 3011*4947cdc7SCole Faust 3012*4947cdc7SCole FaustThese names are not reserved words so Starlark programs are free to 3013*4947cdc7SCole Faustredefine them in a smaller block such as a function body or even at 3014*4947cdc7SCole Faustthe top level of a module. However, doing so may be confusing to the 3015*4947cdc7SCole Faustreader. Nonetheless, this rule permits names to be added to the 3016*4947cdc7SCole Faustpredeclared block in later versions of the language (or 3017*4947cdc7SCole Faustapplication-specific dialect) without breaking existing programs. 3018*4947cdc7SCole Faust 3019*4947cdc7SCole Faust 3020*4947cdc7SCole Faust### None 3021*4947cdc7SCole Faust 3022*4947cdc7SCole Faust`None` is the distinguished value of the type `NoneType`. 3023*4947cdc7SCole Faust 3024*4947cdc7SCole Faust### True and False 3025*4947cdc7SCole Faust 3026*4947cdc7SCole Faust`True` and `False` are the two values of type `bool`. 3027*4947cdc7SCole Faust 3028*4947cdc7SCole Faust### any 3029*4947cdc7SCole Faust 3030*4947cdc7SCole Faust`any(x)` returns `True` if any element of the iterable sequence x has a truth value of true. 3031*4947cdc7SCole FaustIf the iterable is empty, it returns `False`. 3032*4947cdc7SCole Faust 3033*4947cdc7SCole Faust### all 3034*4947cdc7SCole Faust 3035*4947cdc7SCole Faust`all(x)` returns `False` if any element of the iterable sequence x has a truth value of false. 3036*4947cdc7SCole FaustIf the iterable is empty, it returns `True`. 3037*4947cdc7SCole Faust 3038*4947cdc7SCole Faust### bool 3039*4947cdc7SCole Faust 3040*4947cdc7SCole Faust`bool(x)` interprets `x` as a Boolean value---`True` or `False`. 3041*4947cdc7SCole FaustWith no argument, `bool()` returns `False`. 3042*4947cdc7SCole Faust 3043*4947cdc7SCole Faust 3044*4947cdc7SCole Faust### chr 3045*4947cdc7SCole Faust 3046*4947cdc7SCole Faust`chr(i)` returns a string that encodes the single Unicode code point 3047*4947cdc7SCole Faustwhose value is specified by the integer `i`. `chr` fails unless 0 ≤ 3048*4947cdc7SCole Faust`i` ≤ 0x10FFFF. 3049*4947cdc7SCole Faust 3050*4947cdc7SCole FaustExample: 3051*4947cdc7SCole Faust 3052*4947cdc7SCole Faust```python 3053*4947cdc7SCole Faustchr(65) # "A", 3054*4947cdc7SCole Faustchr(1049) # "Й", CYRILLIC CAPITAL LETTER SHORT I 3055*4947cdc7SCole Faustchr(0x1F63F) # "", CRYING CAT FACE 3056*4947cdc7SCole Faust``` 3057*4947cdc7SCole Faust 3058*4947cdc7SCole FaustSee also: `ord`. 3059*4947cdc7SCole Faust 3060*4947cdc7SCole Faust<b>Implementation note:</b> `chr` is not provided by the Java implementation. 3061*4947cdc7SCole Faust 3062*4947cdc7SCole Faust### dict 3063*4947cdc7SCole Faust 3064*4947cdc7SCole Faust`dict` creates a dictionary. It accepts up to one positional 3065*4947cdc7SCole Faustargument, which is interpreted as an iterable of two-element 3066*4947cdc7SCole Faustsequences (pairs), each specifying a key/value pair in 3067*4947cdc7SCole Faustthe resulting dictionary. 3068*4947cdc7SCole Faust 3069*4947cdc7SCole Faust`dict` also accepts any number of keyword arguments, each of which 3070*4947cdc7SCole Faustspecifies a key/value pair in the resulting dictionary; 3071*4947cdc7SCole Fausteach keyword is treated as a string. 3072*4947cdc7SCole Faust 3073*4947cdc7SCole Faust```python 3074*4947cdc7SCole Faustdict() # {}, empty dictionary 3075*4947cdc7SCole Faustdict([(1, 2), (3, 4)]) # {1: 2, 3: 4} 3076*4947cdc7SCole Faustdict([(1, 2), ["a", "b"]]) # {1: 2, "a": "b"} 3077*4947cdc7SCole Faustdict(one=1, two=2) # {"one": 1, "two", 1} 3078*4947cdc7SCole Faustdict([(1, 2)], x=3) # {1: 2, "x": 3} 3079*4947cdc7SCole Faust``` 3080*4947cdc7SCole Faust 3081*4947cdc7SCole FaustWith no arguments, `dict()` returns a new empty dictionary. 3082*4947cdc7SCole Faust 3083*4947cdc7SCole Faust`dict(x)` where x is a dictionary returns a new copy of x. 3084*4947cdc7SCole Faust 3085*4947cdc7SCole Faust### dir 3086*4947cdc7SCole Faust 3087*4947cdc7SCole Faust`dir(x)` returns a new sorted list of the names of the attributes (fields and methods) of its operand. 3088*4947cdc7SCole FaustThe attributes of a value `x` are the names `f` such that `x.f` is a valid expression. 3089*4947cdc7SCole Faust 3090*4947cdc7SCole FaustFor example, 3091*4947cdc7SCole Faust 3092*4947cdc7SCole Faust```python 3093*4947cdc7SCole Faustdir("hello") # ['capitalize', 'count', ...], the methods of a string 3094*4947cdc7SCole Faust``` 3095*4947cdc7SCole Faust 3096*4947cdc7SCole FaustSeveral types known to the interpreter, such as list, string, and dict, have methods, but none have fields. 3097*4947cdc7SCole FaustHowever, an application may define types with fields that may be read or set by statements such as these: 3098*4947cdc7SCole Faust 3099*4947cdc7SCole Faust```text 3100*4947cdc7SCole Fausty = x.f 3101*4947cdc7SCole Faustx.f = y 3102*4947cdc7SCole Faust``` 3103*4947cdc7SCole Faust 3104*4947cdc7SCole Faust### enumerate 3105*4947cdc7SCole Faust 3106*4947cdc7SCole Faust`enumerate(x)` returns a list of (index, value) pairs, each containing 3107*4947cdc7SCole Faustsuccessive values of the iterable sequence xand the index of the value 3108*4947cdc7SCole Faustwithin the sequence. 3109*4947cdc7SCole Faust 3110*4947cdc7SCole FaustThe optional second parameter, `start`, specifies an integer value to 3111*4947cdc7SCole Faustadd to each index. 3112*4947cdc7SCole Faust 3113*4947cdc7SCole Faust```python 3114*4947cdc7SCole Faustenumerate(["zero", "one", "two"]) # [(0, "zero"), (1, "one"), (2, "two")] 3115*4947cdc7SCole Faustenumerate(["one", "two"], 1) # [(1, "one"), (2, "two")] 3116*4947cdc7SCole Faust``` 3117*4947cdc7SCole Faust 3118*4947cdc7SCole Faust### fail 3119*4947cdc7SCole Faust 3120*4947cdc7SCole FaustThe `fail(*args, sep=" ")` function causes execution to fail 3121*4947cdc7SCole Faustwith the specified error message. 3122*4947cdc7SCole FaustLike `print`, arguments are formatted as if by `str(x)` and 3123*4947cdc7SCole Faustseparated by a space, unless an alternative separator is 3124*4947cdc7SCole Faustspecified by a `sep` named argument. 3125*4947cdc7SCole Faust 3126*4947cdc7SCole Faust```python 3127*4947cdc7SCole Faustfail("oops") # "fail: oops" 3128*4947cdc7SCole Faustfail("oops", 1, False, sep='/') # "fail: oops/1/False" 3129*4947cdc7SCole Faust``` 3130*4947cdc7SCole Faust 3131*4947cdc7SCole Faust### float 3132*4947cdc7SCole Faust 3133*4947cdc7SCole Faust`float(x)` interprets its argument as a floating-point number. 3134*4947cdc7SCole Faust 3135*4947cdc7SCole FaustIf x is a `float`, the result is x. 3136*4947cdc7SCole Faustif x is an `int`, the result is the nearest floating point value to x. 3137*4947cdc7SCole FaustIf x is a string, the string is interpreted as a floating-point literal. 3138*4947cdc7SCole FaustWith no arguments, `float()` returns `0.0`. 3139*4947cdc7SCole Faust 3140*4947cdc7SCole Faust 3141*4947cdc7SCole Faust### getattr 3142*4947cdc7SCole Faust 3143*4947cdc7SCole Faust`getattr(x, name)` returns the value of the attribute (field or method) of x named `name`. 3144*4947cdc7SCole FaustIt is a dynamic error if x has no such attribute. 3145*4947cdc7SCole Faust 3146*4947cdc7SCole Faust`getattr(x, "f")` is equivalent to `x.f`. 3147*4947cdc7SCole Faust 3148*4947cdc7SCole Faust```python 3149*4947cdc7SCole Faustgetattr("banana", "split")("a") # ["b", "n", "n", ""], equivalent to "banana".split("a") 3150*4947cdc7SCole Faust``` 3151*4947cdc7SCole Faust 3152*4947cdc7SCole FaustThe three-argument form `getattr(x, name, default)` returns the 3153*4947cdc7SCole Faustprovided `default` value instead of failing. 3154*4947cdc7SCole Faust 3155*4947cdc7SCole Faust### hasattr 3156*4947cdc7SCole Faust 3157*4947cdc7SCole Faust`hasattr(x, name)` reports whether x has an attribute (field or method) named `name`. 3158*4947cdc7SCole Faust 3159*4947cdc7SCole Faust### hash 3160*4947cdc7SCole Faust 3161*4947cdc7SCole Faust`hash(x)` returns an integer hash of a string x 3162*4947cdc7SCole Faustsuch that two equal strings have the same hash. 3163*4947cdc7SCole FaustIn other words `x == y` implies `hash(x) == hash(y)`. 3164*4947cdc7SCole Faust 3165*4947cdc7SCole FaustIn the interests of reproducibility of Starlark program behavior over time and 3166*4947cdc7SCole Faustacross implementations, the specific hash function is the same as that implemented by 3167*4947cdc7SCole Faust[java.lang.String.hashCode](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#hashCode), 3168*4947cdc7SCole Fausta simple polynomial accumulator over the UTF-16 transcoding of the string: 3169*4947cdc7SCole Faust ``` 3170*4947cdc7SCole Fausts[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 3171*4947cdc7SCole Faust``` 3172*4947cdc7SCole Faust 3173*4947cdc7SCole Faust`hash` fails if given a non-string operand, 3174*4947cdc7SCole Fausteven if the value is hashable and thus suitable as the key of dictionary. 3175*4947cdc7SCole Faust 3176*4947cdc7SCole Faust### int 3177*4947cdc7SCole Faust 3178*4947cdc7SCole Faust`int(x[, base])` interprets its argument as an integer. 3179*4947cdc7SCole Faust 3180*4947cdc7SCole FaustIf x is an `int`, the result is x. 3181*4947cdc7SCole FaustIf x is a `float`, the result is the integer value nearest to x, 3182*4947cdc7SCole Fausttruncating towards zero; it is an error if x is not finite (`NaN`, 3183*4947cdc7SCole Faust`+Inf`, `-Inf`). 3184*4947cdc7SCole FaustIf x is a `bool`, the result is 0 for `False` or 1 for `True`. 3185*4947cdc7SCole Faust 3186*4947cdc7SCole FaustIf x is a string, it is interpreted as a sequence of digits in the 3187*4947cdc7SCole Faustspecified base, decimal by default. 3188*4947cdc7SCole FaustIf `base` is zero, x is interpreted like an integer literal, the base 3189*4947cdc7SCole Faustbeing inferred from an optional base prefix such as `0b`, `0o`, or 3190*4947cdc7SCole Faust`0x` preceding the first digit. 3191*4947cdc7SCole FaustWhen the `base` is provided explictly, a matching base prefix is 3192*4947cdc7SCole Faustalso permitted, and has no effect. 3193*4947cdc7SCole FaustIrrespective of base, the string may start with an optional `+` or `-` 3194*4947cdc7SCole Faustsign indicating the sign of the result. 3195*4947cdc7SCole Faust 3196*4947cdc7SCole Faust```python 3197*4947cdc7SCole Faustint("11") # 11 3198*4947cdc7SCole Faustint("11", 0) # 11 3199*4947cdc7SCole Faustint("11", 10) # 11 3200*4947cdc7SCole Faustint("11", 2) # 3 3201*4947cdc7SCole Faustint("11", 8) # 9 3202*4947cdc7SCole Faustint("11", 16) # 17 3203*4947cdc7SCole Faust 3204*4947cdc7SCole Faustint("0x11", 0) # 17 3205*4947cdc7SCole Faustint("0x11", 16) # 17 3206*4947cdc7SCole Faustint("0b1", 16) # 177 (0xb1) 3207*4947cdc7SCole Faustint("0b1", 2) # 1 3208*4947cdc7SCole Faustint("0b1", 0) # 1 3209*4947cdc7SCole Faust 3210*4947cdc7SCole Faustint("0x11") # error: invalid literal with base 10 3211*4947cdc7SCole Faust``` 3212*4947cdc7SCole Faust 3213*4947cdc7SCole Faust### len 3214*4947cdc7SCole Faust 3215*4947cdc7SCole Faust`len(x)` returns the number of elements in its argument. 3216*4947cdc7SCole Faust 3217*4947cdc7SCole FaustIt is a dynamic error if its argument is not a sequence. 3218*4947cdc7SCole Faust 3219*4947cdc7SCole Faust### list 3220*4947cdc7SCole Faust 3221*4947cdc7SCole Faust`list` constructs a list. 3222*4947cdc7SCole Faust 3223*4947cdc7SCole Faust`list(x)` returns a new list containing the elements of the 3224*4947cdc7SCole Faustiterable sequence x. 3225*4947cdc7SCole Faust 3226*4947cdc7SCole FaustWith no argument, `list()` returns a new empty list. 3227*4947cdc7SCole Faust 3228*4947cdc7SCole Faust### max 3229*4947cdc7SCole Faust 3230*4947cdc7SCole Faust`max(x)` returns the greatest element in the iterable sequence x. 3231*4947cdc7SCole Faust 3232*4947cdc7SCole FaustIt is an error if any element does not support ordered comparison, 3233*4947cdc7SCole Faustor if the sequence is empty. 3234*4947cdc7SCole Faust 3235*4947cdc7SCole FaustThe optional named parameter `key` specifies a function to be applied 3236*4947cdc7SCole Faustto each element prior to comparison. 3237*4947cdc7SCole Faust 3238*4947cdc7SCole Faust```python 3239*4947cdc7SCole Faustmax([3, 1, 4, 1, 5, 9]) # 9 3240*4947cdc7SCole Faustmax("two", "three", "four") # "two", the lexicographically greatest 3241*4947cdc7SCole Faustmax("two", "three", "four", key=len) # "three", the longest 3242*4947cdc7SCole Faust``` 3243*4947cdc7SCole Faust 3244*4947cdc7SCole Faust### min 3245*4947cdc7SCole Faust 3246*4947cdc7SCole Faust`min(x)` returns the least element in the iterable sequence x. 3247*4947cdc7SCole Faust 3248*4947cdc7SCole FaustIt is an error if any element does not support ordered comparison, 3249*4947cdc7SCole Faustor if the sequence is empty. 3250*4947cdc7SCole Faust 3251*4947cdc7SCole Faust```python 3252*4947cdc7SCole Faustmin([3, 1, 4, 1, 5, 9]) # 1 3253*4947cdc7SCole Faustmin("two", "three", "four") # "four", the lexicographically least 3254*4947cdc7SCole Faustmin("two", "three", "four", key=len) # "two", the shortest 3255*4947cdc7SCole Faust``` 3256*4947cdc7SCole Faust 3257*4947cdc7SCole Faust 3258*4947cdc7SCole Faust### ord 3259*4947cdc7SCole Faust 3260*4947cdc7SCole Faust`ord(s)` returns the integer value of the sole Unicode code point encoded by the string `s`. 3261*4947cdc7SCole Faust 3262*4947cdc7SCole FaustIf `s` does not encode exactly one Unicode code point, `ord` fails. 3263*4947cdc7SCole FaustEach invalid code within the string is treated as if it encodes the 3264*4947cdc7SCole FaustUnicode replacement character, U+FFFD. 3265*4947cdc7SCole Faust 3266*4947cdc7SCole FaustExample: 3267*4947cdc7SCole Faust 3268*4947cdc7SCole Faust```python 3269*4947cdc7SCole Faustord("A") # 65 3270*4947cdc7SCole Faustord("Й") # 1049 3271*4947cdc7SCole Faustord("") # 0x1F63F 3272*4947cdc7SCole Faustord("Й"[1:]) # 0xFFFD (Unicode replacement character) 3273*4947cdc7SCole Faust``` 3274*4947cdc7SCole Faust 3275*4947cdc7SCole FaustSee also: `chr`. 3276*4947cdc7SCole Faust 3277*4947cdc7SCole Faust<b>Implementation note:</b> `ord` is not provided by the Java implementation. 3278*4947cdc7SCole Faust 3279*4947cdc7SCole Faust### print 3280*4947cdc7SCole Faust 3281*4947cdc7SCole Faust`print(*args, sep=" ")` prints its arguments, followed by a newline. 3282*4947cdc7SCole FaustArguments are formatted as if by `str(x)` and separated with a space, 3283*4947cdc7SCole Faustunless an alternative separator is specified by a `sep` named argument. 3284*4947cdc7SCole Faust 3285*4947cdc7SCole FaustExample: 3286*4947cdc7SCole Faust 3287*4947cdc7SCole Faust```python 3288*4947cdc7SCole Faustprint(1, "hi") # "1 hi\n" 3289*4947cdc7SCole Faustprint("hello", "world") # "hello world\n" 3290*4947cdc7SCole Faustprint("hello", "world", sep=", ") # "hello, world\n" 3291*4947cdc7SCole Faust``` 3292*4947cdc7SCole Faust 3293*4947cdc7SCole FaustTypically the formatted string is printed to the standard error file, 3294*4947cdc7SCole Faustbut the exact behavior is a property of the Starlark thread and is 3295*4947cdc7SCole Faustdetermined by the host application. 3296*4947cdc7SCole Faust 3297*4947cdc7SCole Faust### range 3298*4947cdc7SCole Faust 3299*4947cdc7SCole Faust`range` returns an immutable sequence of integers defined by the specified interval and stride. 3300*4947cdc7SCole Faust 3301*4947cdc7SCole Faust```python 3302*4947cdc7SCole Faustrange(stop) # equivalent to range(0, stop) 3303*4947cdc7SCole Faustrange(start, stop) # equivalent to range(start, stop, 1) 3304*4947cdc7SCole Faustrange(start, stop, step) 3305*4947cdc7SCole Faust``` 3306*4947cdc7SCole Faust 3307*4947cdc7SCole Faust`range` requires between one and three integer arguments. 3308*4947cdc7SCole FaustWith one argument, `range(stop)` returns the ascending sequence of non-negative integers less than `stop`. 3309*4947cdc7SCole FaustWith two arguments, `range(start, stop)` returns only integers not less than `start`. 3310*4947cdc7SCole Faust 3311*4947cdc7SCole FaustWith three arguments, `range(start, stop, step)` returns integers 3312*4947cdc7SCole Faustformed by successively adding `step` to `start` until the value meets or passes `stop`. 3313*4947cdc7SCole FaustA call to `range` fails if the value of `step` is zero. 3314*4947cdc7SCole Faust 3315*4947cdc7SCole FaustA call to `range` does not materialize the entire sequence, but 3316*4947cdc7SCole Faustreturns a fixed-size value of type `"range"` that represents the 3317*4947cdc7SCole Faustparameters that define the sequence. 3318*4947cdc7SCole FaustThe `range` value is iterable and may be indexed efficiently. 3319*4947cdc7SCole Faust 3320*4947cdc7SCole Faust```python 3321*4947cdc7SCole Faustlist(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3322*4947cdc7SCole Faustlist(range(3, 10)) # [3, 4, 5, 6, 7, 8, 9] 3323*4947cdc7SCole Faustlist(range(3, 10, 2)) # [3, 5, 7, 9] 3324*4947cdc7SCole Faustlist(range(10, 3, -2)) # [10, 8, 6, 4] 3325*4947cdc7SCole Faust``` 3326*4947cdc7SCole Faust 3327*4947cdc7SCole FaustThe `len` function applied to a `range` value returns its length. 3328*4947cdc7SCole FaustThe truth value of a `range` value is `True` if its length is non-zero. 3329*4947cdc7SCole Faust 3330*4947cdc7SCole FaustRange values are comparable: two `range` values compare equal if they 3331*4947cdc7SCole Faustdenote the same sequence of integers, even if they were created using 3332*4947cdc7SCole Faustdifferent parameters. 3333*4947cdc7SCole Faust 3334*4947cdc7SCole FaustRange values are not hashable. <!-- should they be? --> 3335*4947cdc7SCole Faust 3336*4947cdc7SCole FaustThe `str` function applied to a `range` value yields a string of the 3337*4947cdc7SCole Faustform `range(10)`, `range(1, 10)`, or `range(1, 10, 2)`. 3338*4947cdc7SCole Faust 3339*4947cdc7SCole FaustThe `x in y` operator, where `y` is a range, reports whether `x` is equal to 3340*4947cdc7SCole Faustsome member of the sequence `y`; the operation fails unless `x` is a 3341*4947cdc7SCole Faustnumber. 3342*4947cdc7SCole Faust 3343*4947cdc7SCole Faust### repr 3344*4947cdc7SCole Faust 3345*4947cdc7SCole Faust`repr(x)` formats its argument as a string. 3346*4947cdc7SCole Faust 3347*4947cdc7SCole FaustAll strings in the result are double-quoted. 3348*4947cdc7SCole Faust 3349*4947cdc7SCole Faust```python 3350*4947cdc7SCole Faustrepr(1) # '1' 3351*4947cdc7SCole Faustrepr("x") # '"x"' 3352*4947cdc7SCole Faustrepr([1, "x"]) # '[1, "x"]' 3353*4947cdc7SCole Faust``` 3354*4947cdc7SCole Faust 3355*4947cdc7SCole Faust### reversed 3356*4947cdc7SCole Faust 3357*4947cdc7SCole Faust`reversed(x)` returns a new list containing the elements of the iterable sequence x in reverse order. 3358*4947cdc7SCole Faust 3359*4947cdc7SCole Faust```python 3360*4947cdc7SCole Faustreversed(range(5)) # [4, 3, 2, 1, 0] 3361*4947cdc7SCole Faustreversed("stressed".codepoints()) # ["d", "e", "s", "s", "e", "r", "t", "s"] 3362*4947cdc7SCole Faustreversed({"one": 1, "two": 2}.keys()) # ["two", "one"] 3363*4947cdc7SCole Faust``` 3364*4947cdc7SCole Faust 3365*4947cdc7SCole Faust### set 3366*4947cdc7SCole Faust 3367*4947cdc7SCole Faust`set(x)` returns a new set containing the elements of the iterable x. 3368*4947cdc7SCole FaustWith no argument, `set()` returns a new empty set. 3369*4947cdc7SCole Faust 3370*4947cdc7SCole Faust```python 3371*4947cdc7SCole Faustset([3, 1, 4, 1, 5, 9]) # set([3, 1, 4, 5, 9]) 3372*4947cdc7SCole Faust``` 3373*4947cdc7SCole Faust 3374*4947cdc7SCole Faust<b>Implementation note:</b> 3375*4947cdc7SCole FaustSets are an optional feature of the Go implementation of Starlark, 3376*4947cdc7SCole Faustenabled by the `-set` flag. 3377*4947cdc7SCole Faust 3378*4947cdc7SCole Faust 3379*4947cdc7SCole Faust### sorted 3380*4947cdc7SCole Faust 3381*4947cdc7SCole Faust`sorted(x)` returns a new list containing the elements of the iterable sequence x, 3382*4947cdc7SCole Faustin sorted order. The sort algorithm is stable. 3383*4947cdc7SCole Faust 3384*4947cdc7SCole FaustThe optional named parameter `reverse`, if true, causes `sorted` to 3385*4947cdc7SCole Faustreturn results in reverse sorted order. 3386*4947cdc7SCole Faust 3387*4947cdc7SCole FaustThe optional named parameter `key` specifies a function of one 3388*4947cdc7SCole Faustargument to apply to obtain the value's sort key. 3389*4947cdc7SCole FaustThe default behavior is the identity function. 3390*4947cdc7SCole Faust 3391*4947cdc7SCole Faust```python 3392*4947cdc7SCole Faustsorted(set("harbors".codepoints())) # ['a', 'b', 'h', 'o', 'r', 's'] 3393*4947cdc7SCole Faustsorted([3, 1, 4, 1, 5, 9]) # [1, 1, 3, 4, 5, 9] 3394*4947cdc7SCole Faustsorted([3, 1, 4, 1, 5, 9], reverse=True) # [9, 5, 4, 3, 1, 1] 3395*4947cdc7SCole Faust 3396*4947cdc7SCole Faustsorted(["two", "three", "four"], key=len) # ["two", "four", "three"], shortest to longest 3397*4947cdc7SCole Faustsorted(["two", "three", "four"], key=len, reverse=True) # ["three", "four", "two"], longest to shortest 3398*4947cdc7SCole Faust``` 3399*4947cdc7SCole Faust 3400*4947cdc7SCole Faust 3401*4947cdc7SCole Faust### str 3402*4947cdc7SCole Faust 3403*4947cdc7SCole Faust`str(x)` formats its argument as a string. 3404*4947cdc7SCole Faust 3405*4947cdc7SCole FaustIf x is a string, the result is x (without quotation). 3406*4947cdc7SCole FaustAll other strings, such as elements of a list of strings, are double-quoted. 3407*4947cdc7SCole Faust 3408*4947cdc7SCole Faust```python 3409*4947cdc7SCole Fauststr(1) # '1' 3410*4947cdc7SCole Fauststr("x") # 'x' 3411*4947cdc7SCole Fauststr([1, "x"]) # '[1, "x"]' 3412*4947cdc7SCole Faust``` 3413*4947cdc7SCole Faust 3414*4947cdc7SCole Faust### tuple 3415*4947cdc7SCole Faust 3416*4947cdc7SCole Faust`tuple(x)` returns a tuple containing the elements of the iterable x. 3417*4947cdc7SCole Faust 3418*4947cdc7SCole FaustWith no arguments, `tuple()` returns the empty tuple. 3419*4947cdc7SCole Faust 3420*4947cdc7SCole Faust### type 3421*4947cdc7SCole Faust 3422*4947cdc7SCole Fausttype(x) returns a string describing the type of its operand. 3423*4947cdc7SCole Faust 3424*4947cdc7SCole Faust```python 3425*4947cdc7SCole Fausttype(None) # "NoneType" 3426*4947cdc7SCole Fausttype(0) # "int" 3427*4947cdc7SCole Fausttype(0.0) # "float" 3428*4947cdc7SCole Faust``` 3429*4947cdc7SCole Faust 3430*4947cdc7SCole Faust### zip 3431*4947cdc7SCole Faust 3432*4947cdc7SCole Faust`zip()` returns a new list of n-tuples formed from corresponding 3433*4947cdc7SCole Faustelements of each of the n iterable sequences provided as arguments to 3434*4947cdc7SCole Faust`zip`. That is, the first tuple contains the first element of each of 3435*4947cdc7SCole Faustthe sequences, the second element contains the second element of each 3436*4947cdc7SCole Faustof the sequences, and so on. The result list is only as long as the 3437*4947cdc7SCole Faustshortest of the input sequences. 3438*4947cdc7SCole Faust 3439*4947cdc7SCole Faust```python 3440*4947cdc7SCole Faustzip() # [] 3441*4947cdc7SCole Faustzip(range(5)) # [(0,), (1,), (2,), (3,), (4,)] 3442*4947cdc7SCole Faustzip(range(5), "abc") # [(0, "a"), (1, "b"), (2, "c")] 3443*4947cdc7SCole Faust``` 3444*4947cdc7SCole Faust 3445*4947cdc7SCole Faust## Built-in methods 3446*4947cdc7SCole Faust 3447*4947cdc7SCole FaustThis section lists the methods of built-in types. Methods are selected 3448*4947cdc7SCole Faustusing [dot expressions](#dot-expressions). 3449*4947cdc7SCole FaustFor example, strings have a `count` method that counts 3450*4947cdc7SCole Faustoccurrences of a substring; `"banana".count("a")` yields `3`. 3451*4947cdc7SCole Faust 3452*4947cdc7SCole FaustAs with built-in functions, built-in methods accept only positional 3453*4947cdc7SCole Faustarguments except where noted. 3454*4947cdc7SCole FaustThe parameter names serve merely as documentation. 3455*4947cdc7SCole Faust 3456*4947cdc7SCole Faust 3457*4947cdc7SCole Faust<a id='dict·clear'></a> 3458*4947cdc7SCole Faust### dict·clear 3459*4947cdc7SCole Faust 3460*4947cdc7SCole Faust`D.clear()` removes all the entries of dictionary D and returns `None`. 3461*4947cdc7SCole FaustIt fails if the dictionary is frozen or if there are active iterators. 3462*4947cdc7SCole Faust 3463*4947cdc7SCole Faust```python 3464*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3465*4947cdc7SCole Faustx.clear() # None 3466*4947cdc7SCole Faustprint(x) # {} 3467*4947cdc7SCole Faust``` 3468*4947cdc7SCole Faust 3469*4947cdc7SCole Faust<a id='dict·get'></a> 3470*4947cdc7SCole Faust### dict·get 3471*4947cdc7SCole Faust 3472*4947cdc7SCole Faust`D.get(key[, default])` returns the dictionary value corresponding to the given key. 3473*4947cdc7SCole FaustIf the dictionary contains no such value, `get` returns `None`, or the 3474*4947cdc7SCole Faustvalue of the optional `default` parameter if present. 3475*4947cdc7SCole Faust 3476*4947cdc7SCole Faust`get` fails if `key` is unhashable, or the dictionary is frozen or has active iterators. 3477*4947cdc7SCole Faust 3478*4947cdc7SCole Faust```python 3479*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3480*4947cdc7SCole Faustx.get("one") # 1 3481*4947cdc7SCole Faustx.get("three") # None 3482*4947cdc7SCole Faustx.get("three", 0) # 0 3483*4947cdc7SCole Faust``` 3484*4947cdc7SCole Faust 3485*4947cdc7SCole Faust<a id='dict·items'></a> 3486*4947cdc7SCole Faust### dict·items 3487*4947cdc7SCole Faust 3488*4947cdc7SCole Faust`D.items()` returns a new list of key/value pairs, one per element in 3489*4947cdc7SCole Faustdictionary D, in the same order as they would be returned by a `for` loop. 3490*4947cdc7SCole Faust 3491*4947cdc7SCole Faust```python 3492*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3493*4947cdc7SCole Faustx.items() # [("one", 1), ("two", 2)] 3494*4947cdc7SCole Faust``` 3495*4947cdc7SCole Faust 3496*4947cdc7SCole Faust<a id='dict·keys'></a> 3497*4947cdc7SCole Faust### dict·keys 3498*4947cdc7SCole Faust 3499*4947cdc7SCole Faust`D.keys()` returns a new list containing the keys of dictionary D, in the 3500*4947cdc7SCole Faustsame order as they would be returned by a `for` loop. 3501*4947cdc7SCole Faust 3502*4947cdc7SCole Faust```python 3503*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3504*4947cdc7SCole Faustx.keys() # ["one", "two"] 3505*4947cdc7SCole Faust``` 3506*4947cdc7SCole Faust 3507*4947cdc7SCole Faust<a id='dict·pop'></a> 3508*4947cdc7SCole Faust### dict·pop 3509*4947cdc7SCole Faust 3510*4947cdc7SCole Faust`D.pop(key[, default])` returns the value corresponding to the specified 3511*4947cdc7SCole Faustkey, and removes it from the dictionary. If the dictionary contains no 3512*4947cdc7SCole Faustsuch value, and the optional `default` parameter is present, `pop` 3513*4947cdc7SCole Faustreturns that value; otherwise, it fails. 3514*4947cdc7SCole Faust 3515*4947cdc7SCole Faust`pop` fails if `key` is unhashable, or the dictionary is frozen or has active iterators. 3516*4947cdc7SCole Faust 3517*4947cdc7SCole Faust```python 3518*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3519*4947cdc7SCole Faustx.pop("one") # 1 3520*4947cdc7SCole Faustx # {"two": 2} 3521*4947cdc7SCole Faustx.pop("three", 0) # 0 3522*4947cdc7SCole Faustx.pop("four") # error: missing key 3523*4947cdc7SCole Faust``` 3524*4947cdc7SCole Faust 3525*4947cdc7SCole Faust<a id='dict·popitem'></a> 3526*4947cdc7SCole Faust### dict·popitem 3527*4947cdc7SCole Faust 3528*4947cdc7SCole Faust`D.popitem()` returns the first key/value pair, removing it from the dictionary. 3529*4947cdc7SCole Faust 3530*4947cdc7SCole Faust`popitem` fails if the dictionary is empty, frozen, or has active iterators. 3531*4947cdc7SCole Faust 3532*4947cdc7SCole Faust```python 3533*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3534*4947cdc7SCole Faustx.popitem() # ("one", 1) 3535*4947cdc7SCole Faustx.popitem() # ("two", 2) 3536*4947cdc7SCole Faustx.popitem() # error: empty dict 3537*4947cdc7SCole Faust``` 3538*4947cdc7SCole Faust 3539*4947cdc7SCole Faust<a id='dict·setdefault'></a> 3540*4947cdc7SCole Faust### dict·setdefault 3541*4947cdc7SCole Faust 3542*4947cdc7SCole Faust`D.setdefault(key[, default])` returns the dictionary value corresponding to the given key. 3543*4947cdc7SCole FaustIf the dictionary contains no such value, `setdefault`, like `get`, 3544*4947cdc7SCole Faustreturns `None` or the value of the optional `default` parameter if 3545*4947cdc7SCole Faustpresent; `setdefault` additionally inserts the new key/value entry into the dictionary. 3546*4947cdc7SCole Faust 3547*4947cdc7SCole Faust`setdefault` fails if the key is unhashable, or if the dictionary is frozen or has active iterators. 3548*4947cdc7SCole Faust 3549*4947cdc7SCole Faust```python 3550*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3551*4947cdc7SCole Faustx.setdefault("one") # 1 3552*4947cdc7SCole Faustx.setdefault("three", 0) # 0 3553*4947cdc7SCole Faustx # {"one": 1, "two": 2, "three": 0} 3554*4947cdc7SCole Faustx.setdefault("four") # None 3555*4947cdc7SCole Faustx # {"one": 1, "two": 2, "three": None} 3556*4947cdc7SCole Faust``` 3557*4947cdc7SCole Faust 3558*4947cdc7SCole Faust<a id='dict·update'></a> 3559*4947cdc7SCole Faust### dict·update 3560*4947cdc7SCole Faust 3561*4947cdc7SCole Faust`D.update([pairs][, name=value[, ...])` makes a sequence of key/value 3562*4947cdc7SCole Faustinsertions into dictionary D, then returns `None.` 3563*4947cdc7SCole Faust 3564*4947cdc7SCole FaustIf the positional argument `pairs` is present, it must be `None`, 3565*4947cdc7SCole Faustanother `dict`, or some other iterable. 3566*4947cdc7SCole FaustIf it is another `dict`, then its key/value pairs are inserted into D. 3567*4947cdc7SCole FaustIf it is an iterable, it must provide a sequence of pairs (or other iterables of length 2), 3568*4947cdc7SCole Fausteach of which is treated as a key/value pair to be inserted into D. 3569*4947cdc7SCole Faust 3570*4947cdc7SCole FaustFor each `name=value` argument present, the name is converted to a 3571*4947cdc7SCole Fauststring and used as the key for an insertion into D, with its corresponding 3572*4947cdc7SCole Faustvalue being `value`. 3573*4947cdc7SCole Faust 3574*4947cdc7SCole Faust`update` fails if the dictionary is frozen or has active iterators. 3575*4947cdc7SCole Faust 3576*4947cdc7SCole Faust```python 3577*4947cdc7SCole Faustx = {} 3578*4947cdc7SCole Faustx.update([("a", 1), ("b", 2)], c=3) 3579*4947cdc7SCole Faustx.update({"d": 4}) 3580*4947cdc7SCole Faustx.update(e=5) 3581*4947cdc7SCole Faustx # {"a": 1, "b": "2", "c": 3, "d": 4, "e": 5} 3582*4947cdc7SCole Faust``` 3583*4947cdc7SCole Faust 3584*4947cdc7SCole Faust<a id='dict·values'></a> 3585*4947cdc7SCole Faust### dict·values 3586*4947cdc7SCole Faust 3587*4947cdc7SCole Faust`D.values()` returns a new list containing the dictionary's values, in the 3588*4947cdc7SCole Faustsame order as they would be returned by a `for` loop over the 3589*4947cdc7SCole Faustdictionary. 3590*4947cdc7SCole Faust 3591*4947cdc7SCole Faust```python 3592*4947cdc7SCole Faustx = {"one": 1, "two": 2} 3593*4947cdc7SCole Faustx.values() # [1, 2] 3594*4947cdc7SCole Faust``` 3595*4947cdc7SCole Faust 3596*4947cdc7SCole Faust<a id='list·append'></a> 3597*4947cdc7SCole Faust### list·append 3598*4947cdc7SCole Faust 3599*4947cdc7SCole Faust`L.append(x)` appends `x` to the list L, and returns `None`. 3600*4947cdc7SCole Faust 3601*4947cdc7SCole Faust`append` fails if the list is frozen or has active iterators. 3602*4947cdc7SCole Faust 3603*4947cdc7SCole Faust```python 3604*4947cdc7SCole Faustx = [] 3605*4947cdc7SCole Faustx.append(1) # None 3606*4947cdc7SCole Faustx.append(2) # None 3607*4947cdc7SCole Faustx.append(3) # None 3608*4947cdc7SCole Faustx # [1, 2, 3] 3609*4947cdc7SCole Faust``` 3610*4947cdc7SCole Faust 3611*4947cdc7SCole Faust<a id='list·clear'></a> 3612*4947cdc7SCole Faust### list·clear 3613*4947cdc7SCole Faust 3614*4947cdc7SCole Faust`L.clear()` removes all the elements of the list L and returns `None`. 3615*4947cdc7SCole FaustIt fails if the list is frozen or if there are active iterators. 3616*4947cdc7SCole Faust 3617*4947cdc7SCole Faust```python 3618*4947cdc7SCole Faustx = [1, 2, 3] 3619*4947cdc7SCole Faustx.clear() # None 3620*4947cdc7SCole Faustx # [] 3621*4947cdc7SCole Faust``` 3622*4947cdc7SCole Faust 3623*4947cdc7SCole Faust<a id='list·extend'></a> 3624*4947cdc7SCole Faust### list·extend 3625*4947cdc7SCole Faust 3626*4947cdc7SCole Faust`L.extend(x)` appends the elements of `x`, which must be iterable, to 3627*4947cdc7SCole Faustthe list L, and returns `None`. 3628*4947cdc7SCole Faust 3629*4947cdc7SCole Faust`extend` fails if `x` is not iterable, or if the list L is frozen or has active iterators. 3630*4947cdc7SCole Faust 3631*4947cdc7SCole Faust```python 3632*4947cdc7SCole Faustx = [] 3633*4947cdc7SCole Faustx.extend([1, 2, 3]) # None 3634*4947cdc7SCole Faustx.extend(["foo"]) # None 3635*4947cdc7SCole Faustx # [1, 2, 3, "foo"] 3636*4947cdc7SCole Faust``` 3637*4947cdc7SCole Faust 3638*4947cdc7SCole Faust<a id='list·index'></a> 3639*4947cdc7SCole Faust### list·index 3640*4947cdc7SCole Faust 3641*4947cdc7SCole Faust`L.index(x[, start[, end]])` finds `x` within the list L and returns its index. 3642*4947cdc7SCole Faust 3643*4947cdc7SCole FaustThe optional `start` and `end` parameters restrict the portion of 3644*4947cdc7SCole Faustlist L that is inspected. If provided and not `None`, they must be list 3645*4947cdc7SCole Faustindices of type `int`. If an index is negative, `len(L)` is effectively 3646*4947cdc7SCole Faustadded to it, then if the index is outside the range `[0:len(L)]`, the 3647*4947cdc7SCole Faustnearest value within that range is used; see [Indexing](#indexing). 3648*4947cdc7SCole Faust 3649*4947cdc7SCole Faust`index` fails if `x` is not found in L, or if `start` or `end` 3650*4947cdc7SCole Faustis not a valid index (`int` or `None`). 3651*4947cdc7SCole Faust 3652*4947cdc7SCole Faust```python 3653*4947cdc7SCole Faustx = list("banana".codepoints()) 3654*4947cdc7SCole Faustx.index("a") # 1 (bAnana) 3655*4947cdc7SCole Faustx.index("a", 2) # 3 (banAna) 3656*4947cdc7SCole Faustx.index("a", -2) # 5 (bananA) 3657*4947cdc7SCole Faust``` 3658*4947cdc7SCole Faust 3659*4947cdc7SCole Faust<a id='list·insert'></a> 3660*4947cdc7SCole Faust### list·insert 3661*4947cdc7SCole Faust 3662*4947cdc7SCole Faust`L.insert(i, x)` inserts the value `x` in the list L at index `i`, moving 3663*4947cdc7SCole Fausthigher-numbered elements along by one. It returns `None`. 3664*4947cdc7SCole Faust 3665*4947cdc7SCole FaustAs usual, the index `i` must be an `int`. If its value is negative, 3666*4947cdc7SCole Faustthe length of the list is added, then its value is clamped to the 3667*4947cdc7SCole Faustnearest value in the range `[0:len(L)]` to yield the effective index. 3668*4947cdc7SCole Faust 3669*4947cdc7SCole Faust`insert` fails if the list is frozen or has active iterators. 3670*4947cdc7SCole Faust 3671*4947cdc7SCole Faust```python 3672*4947cdc7SCole Faustx = ["b", "c", "e"] 3673*4947cdc7SCole Faustx.insert(0, "a") # None 3674*4947cdc7SCole Faustx.insert(-1, "d") # None 3675*4947cdc7SCole Faustx # ["a", "b", "c", "d", "e"] 3676*4947cdc7SCole Faust``` 3677*4947cdc7SCole Faust 3678*4947cdc7SCole Faust<a id='list·pop'></a> 3679*4947cdc7SCole Faust### list·pop 3680*4947cdc7SCole Faust 3681*4947cdc7SCole Faust`L.pop([index])` removes and returns the last element of the list L, or, 3682*4947cdc7SCole Faustif the optional index is provided, at that index. 3683*4947cdc7SCole Faust 3684*4947cdc7SCole Faust`pop` fails if the index is not valid for `L[i]`, 3685*4947cdc7SCole Faustor if the list is frozen or has active iterators. 3686*4947cdc7SCole Faust 3687*4947cdc7SCole Faust```python 3688*4947cdc7SCole Faustx = [1, 2, 3, 4, 5] 3689*4947cdc7SCole Faustx.pop() # 5 3690*4947cdc7SCole Faustx # [1, 2, 3, 4] 3691*4947cdc7SCole Faustx.pop(-2) # 3 3692*4947cdc7SCole Faustx # [1, 2, 4] 3693*4947cdc7SCole Faustx.pop(-3) # 1 3694*4947cdc7SCole Faustx # [2, 4] 3695*4947cdc7SCole Faustx.pop() # 4 3696*4947cdc7SCole Faustx # [2] 3697*4947cdc7SCole Faust``` 3698*4947cdc7SCole Faust 3699*4947cdc7SCole Faust<a id='list·remove'></a> 3700*4947cdc7SCole Faust### list·remove 3701*4947cdc7SCole Faust 3702*4947cdc7SCole Faust`L.remove(x)` removes the first occurrence of the value `x` from the list L, and returns `None`. 3703*4947cdc7SCole Faust 3704*4947cdc7SCole Faust`remove` fails if the list does not contain `x`, is frozen, or has active iterators. 3705*4947cdc7SCole Faust 3706*4947cdc7SCole Faust```python 3707*4947cdc7SCole Faustx = [1, 2, 3, 2] 3708*4947cdc7SCole Faustx.remove(2) # None (x == [1, 3, 2]) 3709*4947cdc7SCole Faustx.remove(2) # None (x == [1, 3]) 3710*4947cdc7SCole Faustx.remove(2) # error: element not found 3711*4947cdc7SCole Faust``` 3712*4947cdc7SCole Faust 3713*4947cdc7SCole Faust<a id='set·union'></a> 3714*4947cdc7SCole Faust### set·union 3715*4947cdc7SCole Faust 3716*4947cdc7SCole Faust`S.union(iterable)` returns a new set into which have been inserted 3717*4947cdc7SCole Faustall the elements of set S and all the elements of the argument, which 3718*4947cdc7SCole Faustmust be iterable. 3719*4947cdc7SCole Faust 3720*4947cdc7SCole Faust`union` fails if any element of the iterable is not hashable. 3721*4947cdc7SCole Faust 3722*4947cdc7SCole Faust```python 3723*4947cdc7SCole Faustx = set([1, 2]) 3724*4947cdc7SCole Fausty = set([2, 3]) 3725*4947cdc7SCole Faustx.union(y) # set([1, 2, 3]) 3726*4947cdc7SCole Faust``` 3727*4947cdc7SCole Faust 3728*4947cdc7SCole Faust<a id='string·elem_ords'></a> 3729*4947cdc7SCole Faust### string·elem_ords 3730*4947cdc7SCole Faust 3731*4947cdc7SCole Faust`S.elem_ords()` returns an iterable value containing the 3732*4947cdc7SCole Faustsequence of numeric bytes values in the string S. 3733*4947cdc7SCole Faust 3734*4947cdc7SCole FaustTo materialize the entire sequence of bytes, apply `list(...)` to the result. 3735*4947cdc7SCole Faust 3736*4947cdc7SCole FaustExample: 3737*4947cdc7SCole Faust 3738*4947cdc7SCole Faust```python 3739*4947cdc7SCole Faustlist("Hello, 世界".elem_ords()) # [72, 101, 108, 108, 111, 44, 32, 228, 184, 150, 231, 149, 140] 3740*4947cdc7SCole Faust``` 3741*4947cdc7SCole Faust 3742*4947cdc7SCole FaustSee also: `string·elems`. 3743*4947cdc7SCole Faust 3744*4947cdc7SCole Faust<b>Implementation note:</b> `elem_ords` is not provided by the Java implementation. 3745*4947cdc7SCole Faust 3746*4947cdc7SCole Faust<a id='string·capitalize'></a> 3747*4947cdc7SCole Faust### string·capitalize 3748*4947cdc7SCole Faust 3749*4947cdc7SCole Faust`S.capitalize()` returns a copy of string S with its first code point 3750*4947cdc7SCole Faustchanged to its title case and all subsequent letters changed to their 3751*4947cdc7SCole Faustlower case. 3752*4947cdc7SCole Faust 3753*4947cdc7SCole Faust```python 3754*4947cdc7SCole Faust"hello, world!".capitalize() # "Hello, world!" 3755*4947cdc7SCole Faust"hElLo, wOrLd!".capitalize() # "Hello, world!" 3756*4947cdc7SCole Faust"¿Por qué?".capitalize() # "¿por qué?" 3757*4947cdc7SCole Faust``` 3758*4947cdc7SCole Faust 3759*4947cdc7SCole Faust<a id='string·codepoint_ords'></a> 3760*4947cdc7SCole Faust### string·codepoint_ords 3761*4947cdc7SCole Faust 3762*4947cdc7SCole Faust`S.codepoint_ords()` returns an iterable value containing the 3763*4947cdc7SCole Faustsequence of integer Unicode code points encoded by the string S. 3764*4947cdc7SCole FaustEach invalid code within the string is treated as if it encodes the 3765*4947cdc7SCole FaustUnicode replacement character, U+FFFD. 3766*4947cdc7SCole Faust 3767*4947cdc7SCole FaustBy returning an iterable, not a list, the cost of decoding the string 3768*4947cdc7SCole Faustis deferred until actually needed; apply `list(...)` to the result to 3769*4947cdc7SCole Faustmaterialize the entire sequence. 3770*4947cdc7SCole Faust 3771*4947cdc7SCole FaustExample: 3772*4947cdc7SCole Faust 3773*4947cdc7SCole Faust```python 3774*4947cdc7SCole Faustlist("Hello, 世界".codepoint_ords()) # [72, 101, 108, 108, 111, 44, 32, 19990, 30028] 3775*4947cdc7SCole Faust 3776*4947cdc7SCole Faustfor cp in "Hello, 世界".codepoint_ords(): 3777*4947cdc7SCole Faust print(chr(cp)) # prints 'H', 'e', 'l', 'l', 'o', ',', ' ', '世', '界' 3778*4947cdc7SCole Faust``` 3779*4947cdc7SCole Faust 3780*4947cdc7SCole FaustSee also: `string·codepoints`. 3781*4947cdc7SCole Faust 3782*4947cdc7SCole Faust<b>Implementation note:</b> `codepoint_ords` is not provided by the Java implementation. 3783*4947cdc7SCole Faust 3784*4947cdc7SCole Faust<a id='string·count'></a> 3785*4947cdc7SCole Faust### string·count 3786*4947cdc7SCole Faust 3787*4947cdc7SCole Faust`S.count(sub[, start[, end]])` returns the number of occcurences of 3788*4947cdc7SCole Faust`sub` within the string S, or, if the optional substring indices 3789*4947cdc7SCole Faust`start` and `end` are provided, within the designated substring of S. 3790*4947cdc7SCole FaustThey are interpreted according to Starlark's [indexing conventions](#indexing). 3791*4947cdc7SCole Faust 3792*4947cdc7SCole Faust```python 3793*4947cdc7SCole Faust"hello, world!".count("o") # 2 3794*4947cdc7SCole Faust"hello, world!".count("o", 7, 12) # 1 (in "world") 3795*4947cdc7SCole Faust``` 3796*4947cdc7SCole Faust 3797*4947cdc7SCole Faust<a id='string·endswith'></a> 3798*4947cdc7SCole Faust### string·endswith 3799*4947cdc7SCole Faust 3800*4947cdc7SCole Faust`S.endswith(suffix[, start[, end]])` reports whether the string 3801*4947cdc7SCole Faust`S[start:end]` has the specified suffix. 3802*4947cdc7SCole Faust 3803*4947cdc7SCole Faust```python 3804*4947cdc7SCole Faust"filename.star".endswith(".star") # True 3805*4947cdc7SCole Faust``` 3806*4947cdc7SCole Faust 3807*4947cdc7SCole FaustThe `suffix` argument may be a tuple of strings, in which case the 3808*4947cdc7SCole Faustfunction reports whether any one of them is a suffix. 3809*4947cdc7SCole Faust 3810*4947cdc7SCole Faust```python 3811*4947cdc7SCole Faust'foo.cc'.endswith(('.cc', '.h')) # True 3812*4947cdc7SCole Faust``` 3813*4947cdc7SCole Faust 3814*4947cdc7SCole Faust 3815*4947cdc7SCole Faust<a id='string·find'></a> 3816*4947cdc7SCole Faust### string·find 3817*4947cdc7SCole Faust 3818*4947cdc7SCole Faust`S.find(sub[, start[, end]])` returns the index of the first 3819*4947cdc7SCole Faustoccurrence of the substring `sub` within S. 3820*4947cdc7SCole Faust 3821*4947cdc7SCole FaustIf either or both of `start` or `end` are specified, 3822*4947cdc7SCole Faustthey specify a subrange of S to which the search should be restricted. 3823*4947cdc7SCole FaustThey are interpreted according to Starlark's [indexing conventions](#indexing). 3824*4947cdc7SCole Faust 3825*4947cdc7SCole FaustIf no occurrence is found, `found` returns -1. 3826*4947cdc7SCole Faust 3827*4947cdc7SCole Faust```python 3828*4947cdc7SCole Faust"bonbon".find("on") # 1 3829*4947cdc7SCole Faust"bonbon".find("on", 2) # 4 3830*4947cdc7SCole Faust"bonbon".find("on", 2, 5) # -1 3831*4947cdc7SCole Faust``` 3832*4947cdc7SCole Faust 3833*4947cdc7SCole Faust<a id='string·format'></a> 3834*4947cdc7SCole Faust### string·format 3835*4947cdc7SCole Faust 3836*4947cdc7SCole Faust`S.format(*args, **kwargs)` returns a version of the format string S 3837*4947cdc7SCole Faustin which bracketed portions `{...}` are replaced 3838*4947cdc7SCole Faustby arguments from `args` and `kwargs`. 3839*4947cdc7SCole Faust 3840*4947cdc7SCole FaustWithin the format string, a pair of braces `{{` or `}}` is treated as 3841*4947cdc7SCole Fausta literal open or close brace. 3842*4947cdc7SCole FaustEach unpaired open brace must be matched by a close brace `}`. 3843*4947cdc7SCole FaustThe optional text between corresponding open and close braces 3844*4947cdc7SCole Faustspecifies which argument to use and how to format it, and consists of 3845*4947cdc7SCole Faustthree components, all optional: 3846*4947cdc7SCole Fausta field name, a conversion preceded by '`!`', and a format specifier 3847*4947cdc7SCole Faustpreceded by '`:`'. 3848*4947cdc7SCole Faust 3849*4947cdc7SCole Faust```text 3850*4947cdc7SCole Faust{field} 3851*4947cdc7SCole Faust{field:spec} 3852*4947cdc7SCole Faust{field!conv} 3853*4947cdc7SCole Faust{field!conv:spec} 3854*4947cdc7SCole Faust``` 3855*4947cdc7SCole Faust 3856*4947cdc7SCole FaustThe *field name* may be either a decimal number or a keyword. 3857*4947cdc7SCole FaustA number is interpreted as the index of a positional argument; 3858*4947cdc7SCole Fausta keyword specifies the value of a keyword argument. 3859*4947cdc7SCole FaustIf all the numeric field names form the sequence 0, 1, 2, and so on, 3860*4947cdc7SCole Faustthey may be omitted and those values will be implied; however, 3861*4947cdc7SCole Faustthe explicit and implicit forms may not be mixed. 3862*4947cdc7SCole Faust 3863*4947cdc7SCole FaustThe *conversion* specifies how to convert an argument value `x` to a 3864*4947cdc7SCole Fauststring. It may be either `!r`, which converts the value using 3865*4947cdc7SCole Faust`repr(x)`, or `!s`, which converts the value using `str(x)` and is 3866*4947cdc7SCole Faustthe default. 3867*4947cdc7SCole Faust 3868*4947cdc7SCole FaustThe *format specifier*, after a colon, specifies field width, 3869*4947cdc7SCole Faustalignment, padding, and numeric precision. 3870*4947cdc7SCole FaustCurrently it must be empty, but it is reserved for future use. 3871*4947cdc7SCole Faust 3872*4947cdc7SCole Faust```python 3873*4947cdc7SCole Faust"a{x}b{y}c{}".format(1, x=2, y=3) # "a2b3c1" 3874*4947cdc7SCole Faust"a{}b{}c".format(1, 2) # "a1b2c" 3875*4947cdc7SCole Faust"({1}, {0})".format("zero", "one") # "(one, zero)" 3876*4947cdc7SCole Faust"Is {0!r} {0!s}?".format('heterological') # 'is "heterological" heterological?' 3877*4947cdc7SCole Faust``` 3878*4947cdc7SCole Faust 3879*4947cdc7SCole Faust<a id='string·index'></a> 3880*4947cdc7SCole Faust### string·index 3881*4947cdc7SCole Faust 3882*4947cdc7SCole Faust`S.index(sub[, start[, end]])` returns the index of the first 3883*4947cdc7SCole Faustoccurrence of the substring `sub` within S, like `S.find`, except 3884*4947cdc7SCole Faustthat if the substring is not found, the operation fails. 3885*4947cdc7SCole Faust 3886*4947cdc7SCole Faust```python 3887*4947cdc7SCole Faust"bonbon".index("on") # 1 3888*4947cdc7SCole Faust"bonbon".index("on", 2) # 4 3889*4947cdc7SCole Faust"bonbon".index("on", 2, 5) # error: substring not found (in "nbo") 3890*4947cdc7SCole Faust``` 3891*4947cdc7SCole Faust 3892*4947cdc7SCole Faust<a id='string·isalnum'></a> 3893*4947cdc7SCole Faust### string·isalnum 3894*4947cdc7SCole Faust 3895*4947cdc7SCole Faust`S.isalnum()` reports whether the string S is non-empty and consists only 3896*4947cdc7SCole FaustUnicode letters and digits. 3897*4947cdc7SCole Faust 3898*4947cdc7SCole Faust```python 3899*4947cdc7SCole Faust"base64".isalnum() # True 3900*4947cdc7SCole Faust"Catch-22".isalnum() # False 3901*4947cdc7SCole Faust``` 3902*4947cdc7SCole Faust 3903*4947cdc7SCole Faust<a id='string·isalpha'></a> 3904*4947cdc7SCole Faust### string·isalpha 3905*4947cdc7SCole Faust 3906*4947cdc7SCole Faust`S.isalpha()` reports whether the string S is non-empty and consists only of Unicode letters. 3907*4947cdc7SCole Faust 3908*4947cdc7SCole Faust```python 3909*4947cdc7SCole Faust"ABC".isalpha() # True 3910*4947cdc7SCole Faust"Catch-22".isalpha() # False 3911*4947cdc7SCole Faust"".isalpha() # False 3912*4947cdc7SCole Faust``` 3913*4947cdc7SCole Faust 3914*4947cdc7SCole Faust<a id='string·isdigit'></a> 3915*4947cdc7SCole Faust### string·isdigit 3916*4947cdc7SCole Faust 3917*4947cdc7SCole Faust`S.isdigit()` reports whether the string S is non-empty and consists only of Unicode digits. 3918*4947cdc7SCole Faust 3919*4947cdc7SCole Faust```python 3920*4947cdc7SCole Faust"123".isdigit() # True 3921*4947cdc7SCole Faust"Catch-22".isdigit() # False 3922*4947cdc7SCole Faust"".isdigit() # False 3923*4947cdc7SCole Faust``` 3924*4947cdc7SCole Faust 3925*4947cdc7SCole Faust<a id='string·islower'></a> 3926*4947cdc7SCole Faust### string·islower 3927*4947cdc7SCole Faust 3928*4947cdc7SCole Faust`S.islower()` reports whether the string S contains at least one cased Unicode 3929*4947cdc7SCole Faustletter, and all such letters are lowercase. 3930*4947cdc7SCole Faust 3931*4947cdc7SCole Faust```python 3932*4947cdc7SCole Faust"hello, world".islower() # True 3933*4947cdc7SCole Faust"Catch-22".islower() # False 3934*4947cdc7SCole Faust"123".islower() # False 3935*4947cdc7SCole Faust``` 3936*4947cdc7SCole Faust 3937*4947cdc7SCole Faust<a id='string·isspace'></a> 3938*4947cdc7SCole Faust### string·isspace 3939*4947cdc7SCole Faust 3940*4947cdc7SCole Faust`S.isspace()` reports whether the string S is non-empty and consists only of Unicode spaces. 3941*4947cdc7SCole Faust 3942*4947cdc7SCole Faust```python 3943*4947cdc7SCole Faust" ".isspace() # True 3944*4947cdc7SCole Faust"\r\t\n".isspace() # True 3945*4947cdc7SCole Faust"".isspace() # False 3946*4947cdc7SCole Faust``` 3947*4947cdc7SCole Faust 3948*4947cdc7SCole Faust<a id='string·istitle'></a> 3949*4947cdc7SCole Faust### string·istitle 3950*4947cdc7SCole Faust 3951*4947cdc7SCole Faust`S.istitle()` reports whether the string S contains at least one cased Unicode 3952*4947cdc7SCole Faustletter, and all such letters that begin a word are in title case. 3953*4947cdc7SCole Faust 3954*4947cdc7SCole Faust```python 3955*4947cdc7SCole Faust"Hello, World!".istitle() # True 3956*4947cdc7SCole Faust"Catch-22".istitle() # True 3957*4947cdc7SCole Faust"HAL-9000".istitle() # False 3958*4947cdc7SCole Faust"Dženan".istitle() # True 3959*4947cdc7SCole Faust"DŽenan".istitle() # False ("DŽ" is a single Unicode letter) 3960*4947cdc7SCole Faust"123".istitle() # False 3961*4947cdc7SCole Faust``` 3962*4947cdc7SCole Faust 3963*4947cdc7SCole Faust<a id='string·isupper'></a> 3964*4947cdc7SCole Faust### string·isupper 3965*4947cdc7SCole Faust 3966*4947cdc7SCole Faust`S.isupper()` reports whether the string S contains at least one cased Unicode 3967*4947cdc7SCole Faustletter, and all such letters are uppercase. 3968*4947cdc7SCole Faust 3969*4947cdc7SCole Faust```python 3970*4947cdc7SCole Faust"HAL-9000".isupper() # True 3971*4947cdc7SCole Faust"Catch-22".isupper() # False 3972*4947cdc7SCole Faust"123".isupper() # False 3973*4947cdc7SCole Faust``` 3974*4947cdc7SCole Faust 3975*4947cdc7SCole Faust<a id='string·join'></a> 3976*4947cdc7SCole Faust### string·join 3977*4947cdc7SCole Faust 3978*4947cdc7SCole Faust`S.join(iterable)` returns the string formed by concatenating each 3979*4947cdc7SCole Faustelement of its argument, with a copy of the string S between 3980*4947cdc7SCole Faustsuccessive elements. The argument must be an iterable whose elements 3981*4947cdc7SCole Faustare strings. 3982*4947cdc7SCole Faust 3983*4947cdc7SCole Faust```python 3984*4947cdc7SCole Faust", ".join(["one", "two", "three"]) # "one, two, three" 3985*4947cdc7SCole Faust"a".join("ctmrn".codepoints()) # "catamaran" 3986*4947cdc7SCole Faust``` 3987*4947cdc7SCole Faust 3988*4947cdc7SCole Faust<a id='string·lower'></a> 3989*4947cdc7SCole Faust### string·lower 3990*4947cdc7SCole Faust 3991*4947cdc7SCole Faust`S.lower()` returns a copy of the string S with letters converted to lowercase. 3992*4947cdc7SCole Faust 3993*4947cdc7SCole Faust```python 3994*4947cdc7SCole Faust"Hello, World!".lower() # "hello, world!" 3995*4947cdc7SCole Faust``` 3996*4947cdc7SCole Faust 3997*4947cdc7SCole Faust<a id='string·lstrip'></a> 3998*4947cdc7SCole Faust### string·lstrip 3999*4947cdc7SCole Faust 4000*4947cdc7SCole Faust`S.lstrip()` returns a copy of the string S with leading whitespace removed. 4001*4947cdc7SCole Faust 4002*4947cdc7SCole FaustLike `strip`, it accepts an optional string parameter that specifies an 4003*4947cdc7SCole Faustalternative set of Unicode code points to remove. 4004*4947cdc7SCole Faust 4005*4947cdc7SCole Faust```python 4006*4947cdc7SCole Faust" hello ".lstrip() # "hello " 4007*4947cdc7SCole Faust" hello ".lstrip("h o") # "ello " 4008*4947cdc7SCole Faust``` 4009*4947cdc7SCole Faust 4010*4947cdc7SCole Faust<a id='string·partition'></a> 4011*4947cdc7SCole Faust### string·partition 4012*4947cdc7SCole Faust 4013*4947cdc7SCole Faust`S.partition(x)` splits string S into three parts and returns them as 4014*4947cdc7SCole Fausta tuple: the portion before the first occurrence of string `x`, `x` itself, 4015*4947cdc7SCole Faustand the portion following it. 4016*4947cdc7SCole FaustIf S does not contain `x`, `partition` returns `(S, "", "")`. 4017*4947cdc7SCole Faust 4018*4947cdc7SCole Faust`partition` fails if `x` is not a string, or is the empty string. 4019*4947cdc7SCole Faust 4020*4947cdc7SCole Faust```python 4021*4947cdc7SCole Faust"one/two/three".partition("/") # ("one", "/", "two/three") 4022*4947cdc7SCole Faust``` 4023*4947cdc7SCole Faust 4024*4947cdc7SCole Faust<a id='string·replace'></a> 4025*4947cdc7SCole Faust### string·replace 4026*4947cdc7SCole Faust 4027*4947cdc7SCole Faust`S.replace(old, new[, count])` returns a copy of string S with all 4028*4947cdc7SCole Faustoccurrences of substring `old` replaced by `new`. If the optional 4029*4947cdc7SCole Faustargument `count`, which must be an `int`, is non-negative, it 4030*4947cdc7SCole Faustspecifies a maximum number of occurrences to replace. 4031*4947cdc7SCole Faust 4032*4947cdc7SCole Faust```python 4033*4947cdc7SCole Faust"banana".replace("a", "o") # "bonono" 4034*4947cdc7SCole Faust"banana".replace("a", "o", 2) # "bonona" 4035*4947cdc7SCole Faust``` 4036*4947cdc7SCole Faust 4037*4947cdc7SCole Faust<a id='string·rfind'></a> 4038*4947cdc7SCole Faust### string·rfind 4039*4947cdc7SCole Faust 4040*4947cdc7SCole Faust`S.rfind(sub[, start[, end]])` returns the index of the substring `sub` within 4041*4947cdc7SCole FaustS, like `S.find`, except that `rfind` returns the index of the substring's 4042*4947cdc7SCole Faust_last_ occurrence. 4043*4947cdc7SCole Faust 4044*4947cdc7SCole Faust```python 4045*4947cdc7SCole Faust"bonbon".rfind("on") # 4 4046*4947cdc7SCole Faust"bonbon".rfind("on", None, 5) # 1 4047*4947cdc7SCole Faust"bonbon".rfind("on", 2, 5) # -1 4048*4947cdc7SCole Faust``` 4049*4947cdc7SCole Faust 4050*4947cdc7SCole Faust<a id='string·rindex'></a> 4051*4947cdc7SCole Faust### string·rindex 4052*4947cdc7SCole Faust 4053*4947cdc7SCole Faust`S.rindex(sub[, start[, end]])` returns the index of the substring `sub` within 4054*4947cdc7SCole FaustS, like `S.index`, except that `rindex` returns the index of the substring's 4055*4947cdc7SCole Faust_last_ occurrence. 4056*4947cdc7SCole Faust 4057*4947cdc7SCole Faust```python 4058*4947cdc7SCole Faust"bonbon".rindex("on") # 4 4059*4947cdc7SCole Faust"bonbon".rindex("on", None, 5) # 1 (in "bonbo") 4060*4947cdc7SCole Faust"bonbon".rindex("on", 2, 5) # error: substring not found (in "nbo") 4061*4947cdc7SCole Faust``` 4062*4947cdc7SCole Faust 4063*4947cdc7SCole Faust<a id='string·rpartition'></a> 4064*4947cdc7SCole Faust### string·rpartition 4065*4947cdc7SCole Faust 4066*4947cdc7SCole Faust`S.rpartition(x)` is like `partition`, but splits `S` at the last occurrence of `x`. 4067*4947cdc7SCole Faust 4068*4947cdc7SCole Faust```python 4069*4947cdc7SCole Faust"one/two/three".partition("/") # ("one/two", "/", "three") 4070*4947cdc7SCole Faust``` 4071*4947cdc7SCole Faust 4072*4947cdc7SCole Faust<a id='string·rsplit'></a> 4073*4947cdc7SCole Faust### string·rsplit 4074*4947cdc7SCole Faust 4075*4947cdc7SCole Faust`S.rsplit([sep[, maxsplit]])` splits a string into substrings like `S.split`, 4076*4947cdc7SCole Faustexcept that when a maximum number of splits is specified, `rsplit` chooses the 4077*4947cdc7SCole Faustrightmost splits. 4078*4947cdc7SCole Faust 4079*4947cdc7SCole Faust```python 4080*4947cdc7SCole Faust"banana".rsplit("n") # ["ba", "a", "a"] 4081*4947cdc7SCole Faust"banana".rsplit("n", 1) # ["bana", "a"] 4082*4947cdc7SCole Faust"one two three".rsplit(None, 1) # ["one two", "three"] 4083*4947cdc7SCole Faust"".rsplit("n") # [""] 4084*4947cdc7SCole Faust``` 4085*4947cdc7SCole Faust 4086*4947cdc7SCole Faust<a id='string·rstrip'></a> 4087*4947cdc7SCole Faust### string·rstrip 4088*4947cdc7SCole Faust 4089*4947cdc7SCole Faust`S.rstrip()` returns a copy of the string S with trailing whitespace removed. 4090*4947cdc7SCole Faust 4091*4947cdc7SCole FaustLike `strip`, it accepts an optional string parameter that specifies an 4092*4947cdc7SCole Faustalternative set of Unicode code points to remove. 4093*4947cdc7SCole Faust 4094*4947cdc7SCole Faust```python 4095*4947cdc7SCole Faust" hello ".rstrip() # " hello" 4096*4947cdc7SCole Faust" hello ".rstrip("h o") # " hell" 4097*4947cdc7SCole Faust``` 4098*4947cdc7SCole Faust 4099*4947cdc7SCole Faust<a id='string·split'></a> 4100*4947cdc7SCole Faust### string·split 4101*4947cdc7SCole Faust 4102*4947cdc7SCole Faust`S.split([sep [, maxsplit]])` returns the list of substrings of S, 4103*4947cdc7SCole Faustsplitting at occurrences of the delimiter string `sep`. 4104*4947cdc7SCole Faust 4105*4947cdc7SCole FaustConsecutive occurrences of `sep` are considered to delimit empty 4106*4947cdc7SCole Fauststrings, so `'food'.split('o')` returns `['f', '', 'd']`. 4107*4947cdc7SCole FaustSplitting an empty string with a specified separator returns `['']`. 4108*4947cdc7SCole FaustIf `sep` is the empty string, `split` fails. 4109*4947cdc7SCole Faust 4110*4947cdc7SCole FaustIf `sep` is not specified or is `None`, `split` uses a different 4111*4947cdc7SCole Faustalgorithm: it removes all leading spaces from S 4112*4947cdc7SCole Faust(or trailing spaces in the case of `rsplit`), 4113*4947cdc7SCole Faustthen splits the string around each consecutive non-empty sequence of 4114*4947cdc7SCole FaustUnicode white space characters. 4115*4947cdc7SCole FaustIf S consists only of white space, `S.split()` returns the empty list. 4116*4947cdc7SCole Faust 4117*4947cdc7SCole FaustIf `maxsplit` is given and non-negative, it specifies a maximum number of splits. 4118*4947cdc7SCole Faust 4119*4947cdc7SCole Faust```python 4120*4947cdc7SCole Faust"one two three".split() # ["one", "two", "three"] 4121*4947cdc7SCole Faust"one two three".split(" ") # ["one", "two", "", "three"] 4122*4947cdc7SCole Faust"one two three".split(None, 1) # ["one", "two three"] 4123*4947cdc7SCole Faust"banana".split("n") # ["ba", "a", "a"] 4124*4947cdc7SCole Faust"banana".split("n", 1) # ["ba", "ana"] 4125*4947cdc7SCole Faust"".split("n") # [""] 4126*4947cdc7SCole Faust``` 4127*4947cdc7SCole Faust 4128*4947cdc7SCole Faust<a id='string·elems'></a> 4129*4947cdc7SCole Faust### string·elems 4130*4947cdc7SCole Faust 4131*4947cdc7SCole Faust`S.elems()` returns an iterable value containing successive 4132*4947cdc7SCole Faust1-byte substrings of S. 4133*4947cdc7SCole FaustTo materialize the entire sequence, apply `list(...)` to the result. 4134*4947cdc7SCole Faust 4135*4947cdc7SCole FaustExample: 4136*4947cdc7SCole Faust 4137*4947cdc7SCole Faust```python 4138*4947cdc7SCole Faustlist('Hello, 世界'.elems()) # ["H", "e", "l", "l", "o", ",", " ", "\xe4", "\xb8", "\x96", "\xe7", "\x95", "\x8c"] 4139*4947cdc7SCole Faust``` 4140*4947cdc7SCole Faust 4141*4947cdc7SCole FaustSee also: `string·elem_ords`. 4142*4947cdc7SCole Faust 4143*4947cdc7SCole Faust 4144*4947cdc7SCole Faust<a id='string·codepoints'></a> 4145*4947cdc7SCole Faust### string·codepoints 4146*4947cdc7SCole Faust 4147*4947cdc7SCole Faust`S.codepoints()` returns an iterable value containing the sequence of 4148*4947cdc7SCole Faustsubstrings of S that each encode a single Unicode code point. 4149*4947cdc7SCole FaustEach invalid code within the string is treated as if it encodes the 4150*4947cdc7SCole FaustUnicode replacement character, U+FFFD. 4151*4947cdc7SCole Faust 4152*4947cdc7SCole FaustBy returning an iterable, not a list, the cost of decoding the string 4153*4947cdc7SCole Faustis deferred until actually needed; apply `list(...)` to the result to 4154*4947cdc7SCole Faustmaterialize the entire sequence. 4155*4947cdc7SCole Faust 4156*4947cdc7SCole FaustExample: 4157*4947cdc7SCole Faust 4158*4947cdc7SCole Faust```python 4159*4947cdc7SCole Faustlist('Hello, 世界'.codepoints()) # ['H', 'e', 'l', 'l', 'o', ',', ' ', '世', '界'] 4160*4947cdc7SCole Faust 4161*4947cdc7SCole Faustfor cp in 'Hello, 世界'.codepoints(): 4162*4947cdc7SCole Faust print(cp) # prints 'H', 'e', 'l', 'l', 'o', ',', ' ', '世', '界' 4163*4947cdc7SCole Faust``` 4164*4947cdc7SCole Faust 4165*4947cdc7SCole FaustSee also: `string·codepoint_ords`. 4166*4947cdc7SCole Faust 4167*4947cdc7SCole Faust<b>Implementation note:</b> `codepoints` is not provided by the Java implementation. 4168*4947cdc7SCole Faust 4169*4947cdc7SCole Faust<a id='string·splitlines'></a> 4170*4947cdc7SCole Faust### string·splitlines 4171*4947cdc7SCole Faust 4172*4947cdc7SCole Faust`S.splitlines([keepends])` returns a list whose elements are the 4173*4947cdc7SCole Faustsuccessive lines of S, that is, the strings formed by splitting S at 4174*4947cdc7SCole Faustline terminators (currently assumed to be a single newline, `\n`, 4175*4947cdc7SCole Faustregardless of platform). 4176*4947cdc7SCole Faust 4177*4947cdc7SCole FaustThe optional argument, `keepends`, is interpreted as a Boolean. 4178*4947cdc7SCole FaustIf true, line terminators are preserved in the result, though 4179*4947cdc7SCole Faustthe final element does not necessarily end with a line terminator. 4180*4947cdc7SCole Faust 4181*4947cdc7SCole FaustAs a special case, if S is the empty string, 4182*4947cdc7SCole Faust`splitlines` returns the empty list. 4183*4947cdc7SCole Faust 4184*4947cdc7SCole Faust```python 4185*4947cdc7SCole Faust"one\n\ntwo".splitlines() # ["one", "", "two"] 4186*4947cdc7SCole Faust"one\n\ntwo".splitlines(True) # ["one\n", "\n", "two"] 4187*4947cdc7SCole Faust"".splitlines() # [] -- a special case 4188*4947cdc7SCole Faust``` 4189*4947cdc7SCole Faust 4190*4947cdc7SCole Faust<a id='string·startswith'></a> 4191*4947cdc7SCole Faust### string·startswith 4192*4947cdc7SCole Faust 4193*4947cdc7SCole Faust`S.startswith(prefix[, start[, end]])` reports whether the string 4194*4947cdc7SCole Faust`S[start:end]` has the specified prefix. 4195*4947cdc7SCole Faust 4196*4947cdc7SCole Faust```python 4197*4947cdc7SCole Faust"filename.star".startswith("filename") # True 4198*4947cdc7SCole Faust``` 4199*4947cdc7SCole Faust 4200*4947cdc7SCole FaustThe `prefix` argument may be a tuple of strings, in which case the 4201*4947cdc7SCole Faustfunction reports whether any one of them is a prefix. 4202*4947cdc7SCole Faust 4203*4947cdc7SCole Faust```python 4204*4947cdc7SCole Faust'abc'.startswith(('a', 'A')) # True 4205*4947cdc7SCole Faust'ABC'.startswith(('a', 'A')) # True 4206*4947cdc7SCole Faust'def'.startswith(('a', 'A')) # False 4207*4947cdc7SCole Faust``` 4208*4947cdc7SCole Faust 4209*4947cdc7SCole Faust<a id='string·strip'></a> 4210*4947cdc7SCole Faust### string·strip 4211*4947cdc7SCole Faust 4212*4947cdc7SCole Faust`S.strip()` returns a copy of the string S with leading and trailing whitespace removed. 4213*4947cdc7SCole Faust 4214*4947cdc7SCole FaustIt accepts an optional string argument: 4215*4947cdc7SCole Faust`S.strip(cutset)` instead removes all leading 4216*4947cdc7SCole Faustand trailing Unicode code points contained in `cutset`. 4217*4947cdc7SCole Faust 4218*4947cdc7SCole Faust```python 4219*4947cdc7SCole Faust" hello ".strip() # "hello" 4220*4947cdc7SCole Faust" hello ".strip("h o") # "ell" 4221*4947cdc7SCole Faust``` 4222*4947cdc7SCole Faust 4223*4947cdc7SCole Faust<a id='string·title'></a> 4224*4947cdc7SCole Faust### string·title 4225*4947cdc7SCole Faust 4226*4947cdc7SCole Faust`S.title()` returns a copy of the string S with letters converted to title case. 4227*4947cdc7SCole Faust 4228*4947cdc7SCole FaustLetters are converted to upper case at the start of words, lower case elsewhere. 4229*4947cdc7SCole Faust 4230*4947cdc7SCole Faust```python 4231*4947cdc7SCole Faust"hElLo, WoRlD!".title() # "Hello, World!" 4232*4947cdc7SCole Faust"dženan".title() # "Dženan" ("Dž" is a single Unicode letter) 4233*4947cdc7SCole Faust``` 4234*4947cdc7SCole Faust 4235*4947cdc7SCole Faust<a id='string·upper'></a> 4236*4947cdc7SCole Faust### string·upper 4237*4947cdc7SCole Faust 4238*4947cdc7SCole Faust`S.upper()` returns a copy of the string S with letters converted to uppercase. 4239*4947cdc7SCole Faust 4240*4947cdc7SCole Faust```python 4241*4947cdc7SCole Faust"Hello, World!".upper() # "HELLO, WORLD!" 4242*4947cdc7SCole Faust``` 4243*4947cdc7SCole Faust 4244*4947cdc7SCole Faust## Dialect differences 4245*4947cdc7SCole Faust 4246*4947cdc7SCole FaustThe list below summarizes features of the Go implementation that are 4247*4947cdc7SCole Faustknown to differ from the Java implementation of Starlark used by Bazel. 4248*4947cdc7SCole FaustSome of these features may be controlled by global options to allow 4249*4947cdc7SCole Faustapplications to mimic the Bazel dialect more closely. Our goal is 4250*4947cdc7SCole Fausteventually to eliminate all such differences on a case-by-case basis. 4251*4947cdc7SCole FaustSee [Starlark spec issue 20](https://github.com/bazelbuild/starlark/issues/20). 4252*4947cdc7SCole Faust 4253*4947cdc7SCole Faust* String interpolation supports the `[ioxXc]` conversions. 4254*4947cdc7SCole Faust* String elements are bytes. 4255*4947cdc7SCole Faust* Non-ASCII strings are encoded using UTF-8. 4256*4947cdc7SCole Faust* Strings support hex byte escapes. 4257*4947cdc7SCole Faust* Strings have the additional methods `elem_ords`, `codepoint_ords`, and `codepoints`. 4258*4947cdc7SCole Faust* The `chr` and `ord` built-in functions are supported. 4259*4947cdc7SCole Faust* The `set` built-in function is provided (option: `-set`). 4260*4947cdc7SCole Faust* `set & set` and `set | set` compute set intersection and union, respectively. 4261*4947cdc7SCole Faust* `assert` is a valid identifier. 4262*4947cdc7SCole Faust* `if`, `for`, and `while` are permitted at top level (option: `-globalreassign`). 4263*4947cdc7SCole Faust* top-level rebindings are permitted (option: `-globalreassign`). 4264