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