Skip to content
On this page

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 typesp.record(a=sp.int, b=sp.string. A record's components can be accessed with.`-notation, for example:

smartpy
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:

python
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

python
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
    If x is a SmartPy record of type sp.record(a=int, b=int), this assigns x.a to a new variable a and x.b to a new variable b. 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:

    python
    with 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.

See test_ticket.py (ide/download) for examples.