Skip to content
On this page

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

Michelson or.

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 โ€‹

python
sp.variant('a_field', 10)
Michelson LEFT

and

Michelson RIGHT

Operations โ€‹

Add left variant โ€‹

sp.left(value)
Introduce a left/right variant.

Example โ€‹

python
sp.left("field1")
Michelson LEFT

Add right variant โ€‹

sp.right(value)
Introduce a left/right variant.

Example โ€‹

python
sp.right("field2")
Michelson RIGHT

Check if is variant โ€‹

expr.is_variant(v)
For a variant, checks whether expr is sp.variant(v, ...).

Example โ€‹

python
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
Michelson IF_LEFT

Check if is left variant โ€‹

expr.is_left()
For a left/right variant, checks whether it is sp.left(...).

Example โ€‹

python
expr.is_left()
Michelson IF_LEFT

Check if is right variant โ€‹

expr.is_right()
For a left/right variant, checks whether it is sp.right(...).

Example โ€‹

python
expr.is_right()
Michelson IF_LEFT

Open a variant โ€‹

expr.open_variant(v)
If expr is equal to sp.variant(v, x), return x. Otherwise fail.

Example โ€‹

python
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"
Michelson IF_LEFT

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 โ€‹

python
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