TransWikia.com

Why does smartpy use sp.for/sp.while instead of the default loops provided by python?

Tezos Asked by Anshu Jalan on August 19, 2021

So I just started out with smartpy and I am kinda confused about the point of having separate expression for loops. My understanding is that it is may be because it’s a part of on-chain computations, but I’m not quite sure.

When using the default for loop expression, I got this error:

Error: ‘Expr’ object cannot be interpreted as an integer

 for i in range(1, params.op + 1):

One Answer

Your understanding is quite correct.

SmartPy is a Python library, not a Python-inspired language so we use Python everywhere and overload Python's constructions. This approach is called meta-programming and is extremely important for bigger templates.

Control operators such as if, for, while cannot be overloaded in Python. So we have our own pure-python ones sp.if_, sp.for_, etc., and use some syntax transformation, called syntactic sugar, to present them nicely to developers.

Some information is here: https://www.smartpy.io/dev/reference.html#_control_and_syntactic_sugar

Your first error is in the range, you should use sp.range since params.op is a SmartPy expression, not an integer (as Python is telling you).

Then, you will need to you sp.for as SmartPy will tell you because this needs to be executed on-chain, not at compile time.

Correct answer by FFF on August 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP