Variants โ
Variants in SmartPy are of type sp.TVariant(**kargs
) where kargs
is a Python dict
of SmartPy types indexed by strings. They generalize the Michelson type
Variants are used to define sum-types, similar to enums in other languages with the extra feature that these enums contain values.
See reference Variant template.
Literals โ
sp.variant(<name>,ย <value>)
Introduce a variant.
Example โ
sp.variant('a_field', 10)
and
Michelson RIGHTOperations โ
Add left variant โ
sp.left(value)
Introduce a left/right variant.
Example โ
sp.left("field1")
Add right variant โ
sp.right(value)
Introduce a left/right variant.
Example โ
sp.right("field2")
Check if is variant โ
expr.is_variant(v)
For a variant, checks whether expr
is sp.variant(v, ...)
.
Example โ
variant_type = sp.TVariant(
action1 = sp.TNat,
action2 = sp.TString,
)
variant = sp.variant("action1", 10)
sp.if variant.is_variant("action1"):
# This is true, above we built an action1 variant
sp.if variant.is_variant("action2"):
# This is false
Check if is left variant โ
expr.is_left()
For a left/right variant, checks whether it is sp.left(...)
.
Example โ
expr.is_left()
Check if is right variant โ
expr.is_right()
For a left/right variant, checks whether it is sp.right(...)
.
Example โ
expr.is_right()
Open a variant โ
expr.open_variant(v)
If expr
is equal to sp.variant(v, x)
, return x
. Otherwise fail.
Example โ
variant_type = sp.TVariant(
action1 = sp.TNat,
action2 = sp.TString,
)
variant1 = sp.variant("action1", 10)
variant2 = sp.variant("action2", "Hello World")
variant1.open_variant("action1") # 10
variant1.open_variant("action2") # "Hello World"
Match cases โ
<expr>.match_cases(v)
Similar to a switch case statement, where expr
is a variant.
Only one branch is executed. The notion of fallthrough
doesn't exist.
Example โ
variant_type = sp.TVariant(
action1 = sp.TNat,
action2 = sp.TString,
)
variant = sp.variant("action1", 10)
with variant.match_cases() as arg:
with arg.match("action1") as a1:
# Will be executed
sp.verify(a1 == 10, 'Expected value to be (10).')
with arg.match("action2") as a2:
# Will not be executed