Control statements โ
Since Python doesn't allow its control statements to be overloaded, SmartPy uses its own control statements for statements that need to be executed on-chain.
Internally, we use with
-blocks introduced by sp.if_
, sp.else_
, sp.for_
and sp.while_
.
These constructions are regular Python and can be used directly. In practice, they are usually preferred by power-users and are also much more IDE-friendly.
We also pre-process the SmartPy script for sugared versions: sp.if
, sp.else
, sp.for
, sp.while
.
If statement โ
A if
condition that is evaluated on-chain.
sp.if x == 10 :
self.data.result = 0
sp.else:
self.data.result += x
The desugared version is
with sp.if_(x == 10):
self.data.result = 0
with sp.else_():
self.data.result += x
If we use e.g. sp.if
instead of a plain if
, the result
will be a SmartPy conditional instead of a Python one.
SmartPy conditionals are executed once the contract has been constructed and has been deployed or is being simulated. On the other hand, Python conditionals are executed immediately. Therefore the condition after the if
cannot depend on the state of the contract.
When in doubt, it is reasonable to use the sp.
prefix inside a smart contract. :::
For statement โ
A for
loop that is evaluated on-chain.
sp.for x in params:
self.data.result += x
The desugared version is
with sp.for_("x", params) as x:
self.data.result += x
and
Michelson MAPWhile statement โ
A while
loop that is evaluated on-chain.
sp.while 1 < y.value:
self.data.value += 1
y.value //= 2
The desugared version is
with sp.while_(1 < y.value):
self.data.value += 1
y.value //= 2