Options and variants
Options
TIP
Options are a particular case of variants described below with two cases: None
and Some
.
In SmartPy usage of the value None
is reflected in the type: for example, an optional integer is of type sp.option[sp.int]
. This type is inhabited by None
and by sp.Some(n)
for any value n
of type sp.int
.
- x.is_none() → sp.bool
Checks whether the given value is
None
. For exampleNone.is_none() == True
andsp.Some(42).is_none() == False
- x.is_some() → sp.bool
Checks whether the given value is of the form
sp.Some(...)
. For exampleNone.is_some() == False
andsp.Some(42).is_some() == True
.
- x.unwrap_some([error=exception: t]) → t
Extracts the argument of an option value if it is of the form
sp.Some(...)
. Raises an exception (that can be specified aserror
) ifx == None
. Iferror
is specified, the parameter must be named.For example,
sp.Some(42).unwrap_some() == 42
, whereasNone.unwrap_some(error="oops")
raises the exception"oops"
.
Variants
Variants in SmartPy are enumerations of cases, where each case comes with an extra value. In other languages similar features, such as enums, sum types, and tagged/disjoint unions, exist.
For example, sp.variant(Circle=sp.int, Rectangle=sp.pair[sp.int, sp.int])
is a variant type with two cases. Its values are sp.variant.Circle(r)
(for any r
of type sp.int
) and sp.variant.Rectangle(h, w)
(for any h
and w
of type sp.int
).
- x.is_variant.V() → sp.bool
Checks whether a value is of the given variant
V
, for example:smartpyc = sp.variant.Circle(2) assert c.is_variant.Circle()
- x.unwrap.V([error=exception: t]) → t
Obtains the argument of a given variant
V
. Raises an error if it is of a different variant. Iferror
is specified, the parameter must be named. For example:smartpyc = sp.variant.Circle(2) assert c.unwrap.Circle() == 2 r = c.unwrap.Rectangle() # raises an exception r = c.unwrap.Rectangle(error="Err") # raises "Err"
Matching over options and variants
To match over variants, one can use with sp.match(my_variant)
and then with sp.case.<case>
or with sp.case.<case> as <value>
or with None
.
- with sp.match(v: sp.variant[t]) →
Matches over a variant.
For example:
smartpyv = sp.variant.Circle(2) with sp.match(v): with sp.case.Circle as radius: assert radius == 2 with sp.case.Rectangle as dimensions: ... # Do something with `dimensions.h` and `dimensions.w`.
When matching over options, one can use
with None
to match over theNone
case.For example:
smartpyo = sp.Some(5) with sp.match(o): with sp.case.Some as value: assert value == 5 with None: ...