Skip to content
On this page

Options โ€‹

Optional values in SmartPy are of type sp.TOption(t).

The corresponding type in Michelson is

Michelson option.

They represent values of type t or nothing.

Optional values are useful for accommodating missing data: e.g. if your contract has an optional expiry date, you can add a field expiryDate = sp.none to the constructor. Then, if you want to set the expiry date, you write expiryDate = sp.some(sp.timestamp(1571761674)).

Conversely, if you want to unset it again, you write expiryDate = sp.none. SmartPy automatically infers the type sp.TOption(sp.TTimestamp) for x, so you don't have to make it explicit.

Define an empty optional value โ€‹

sp.none
Define an optional value not containing any element.

Example โ€‹

python
optionalValue = sp.none
Michelson NONE

Define an optional value โ€‹

sp.some(<expr>)
Define an optional value containing an element expr.

Example โ€‹

python
optionalValue = sp.some(1)
Michelson SOME

Check if an optional value exists โ€‹

expr.is_some()
Check that an optional value contains an element, i.e., checks whether it is of the form sp.some(...).

Example โ€‹

python
sp.if expr.is_some():
    # ...
Michelson IF_NONE

Get optional value โ€‹

expr.open_some(messageย =ย None)
If expr is equal to sp.some(x), return x; otherwise fail. message is the optional error raised in case of error.

Example โ€‹

python
# expr is of type sp.TOption<sp.TNat>
value = expr.open_some(message = "Value is None")
Michelson IF_NONE