New syntax
With version 0.17.0 SmartPy introduces a new syntax. This allows users to write code in a syntax even closer to Python. Highlights:
No more
sp.if
,sp.for
,sp.while
. Just writeif
,for
,while
instead.No more
x = sp.local("x", ...)
andx = sp.compute(...)
. Just writex = ...
instead.No more
x.value
to access a variable's value. Just writex
instead.With module syntax, the contract
__init__
function can be written in a more Python-like style: instead of callingself.init(x = ...)
we can use assignment syntax, just like in Python:self.data.x = ...
.
The old syntax is still enabled by default. In order to use the new syntax add new_syntax = True
to sp.entrypoint
.
@sp.entrypoint(new_syntax = True)
def squareRoot(self, x):
assert x >= 0
y = x
while y * y > x:
y = (x / y + y) / 2
assert y * y <= x and x < (y + 1) * (y + 1)
self.data.value = y
In order to write an entire contract in the new syntax, you can include it into a module:
@sp.module
def main():
class Calculator(sp.Contract):
def __init__(self):
self.data.result = 0
@sp.entrypoint
def multiply(self, x, y):
self.data.result = x * y
Note that in __init__
storage fields are assigned to, in contrast to the call to self.init
in the old syntax.
The module (here main
) needs to be given as an argument to sp.test_scenario
:
@sp.add_test(name = "Calculator")
def test():
scenario = sp.test_scenario(main)
c = main.Calculator()
scenario += c