Optional (:)

WMA link


Optional[pattern, default]

pattern : default

is a pattern matching pattern; when pattern is omitted, default is substituted for pattern.

Optional is used to specify optional arguments in function signatures.

Set up a default value of 1 for the pattern y_ in function f:

Above, we put no spaces before or after :, but they can be added. So:

is the same as the above.

When we specify a value for the y parameter, it has the value provided:

But if the y parameter is missing, we replace the parameter using the default given in the delayed assignment above:

Both Optional and Pattern use : as their operator symbol. And both operators are used to represent a pattern.

The way to disambiguate which of the two is used is by the first or left operand. When this is a symbol, like y, the : operator indicates a Pattern:

In contrast, we have a pattern to the left of the colon, like y_ we have an Optional expression:

The special form y_. is equivalent to Optional[y_]:

In this situation, when the is y parameter omitted, the value comes from Default:

Note that the Optional operator binds more tightly than the Pattern. Keep this in mind when there is more than one colon, juxtaposed, each representing different operators: