Records
Records in SmartPy are of type sp.record(field1=..., field2=...)
. They are written as e.g. sp.record(field1=1, field2="A string"), which is of type
sp.record(a=sp.int, b=sp.string. A record's components can be accessed with
.`-notation, for example:
x = sp.record(a=42, b="abc", c=True)
assert x.a == 42
assert x.b == "abc"
assert x.c == True
Layouts
By default records are compiled to Michelson tuples as right-combs. Different layouts can be specified in the type as follows.
.layout(layout)
A record type, i.e. something of the form sp.record(...)
, can be used to define a record type with a layout by doing:
t: type = sp.record(
owner=sp.address, operator=sp.address, token_id=sp.string
).layout(("owner", ("operator", "token_id")))
Accessing fields
<record>.<field>
If record
is a record and field
one of its fields, we can obtain the field's value by writing <record>.<field>
.
Example
record = sp.record(x=1, y=2)
value = record.x # 1
Furthermore, records can be matched using the following statements:
record(a, b).match = x
Ifx
is a SmartPy record of typesp.record(a=int, b=int)
, this assignsx.a
to a new variablea
andx.b
to a new variableb
. If the variable name differs from the field name, the parameters must be named:record(a=y, b=z).match x
.sp.modify_record(r) as x
A variant of this command allows modifying a record (r
) that is held in the contract storage or in a local variable:pythonwith sp.modify_record(self.data) as data: ... data.x = 12 data.y += 1
This command tells the SmartPy compiler to open the record, handle its fields independently and recreate the record afterwards in a linear way. It is mostly useful when dealing with tickets.