Skip to content
On this page

Records โ€‹

Records in SmartPy are of type sp.TRecord(**kargs) where kargs is a Python dict of SmartPy types indexed by strings.

They generalize the Michelson type

Michelson pair.

Literals โ€‹

sp.record(**kargs)
Introduce a record of type sp.TRecord(field1 = sp.TNat, field2 = sp.TString)

Example โ€‹

python
aRecord = sp.record(field1 = 1, field2 = "A string")

Layouts โ€‹

The default layout can be changed by specifying default_record_layoutflag.

.layout(layout)
A record type, i.e. something of the form sp.TRecord(...), can be used to define a record type with a layout by doing:

python
t = sp.TRecord(owner = sp.TAddress, operator = sp.TAddress, token_id = sp.TString)
t_with_layout = t.layout(("owner", ("operator", "token_id")))

.right_comb()
Like .layout(...) but the geometry used is (f1,ย (f2, ..ย (f_{k-1}, f_k))))), the list of fields is determined automatically and sorted alphabetically.

.with_fields(fields)
Adds some fields to the TRecord(...) where fields is a Python (string, type)-dictionary of fields.

.without_fields(fields)
Removes some fields from the TRecord(...) where fields is a Python list of fields.

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

  • sp.match_record(x,ย *fields)
    If x is a SmartPy record (i.e. a value of type sp.TRecord(...)), this returns a Python tuple of selected record fields. The list of fields can be all the record's fields or just some of them. This is typically used as follows:

    python
    fld1, fld2, fld3 = sp.match_record(x, "fld1", "fld2", "fld3" )
  • sp.modify_record(x,ย nameย =ย None)
    A variant of this command allows modifying a record that is held in the contract storage or in a local variable:

    python
    with sp.modify_record(self.data, "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.
This command is mostly useful when dealing with tickets.

See reference Modify and Tickets templates for examples.