Flow control: after, cond, while_loop
cond
When using Python to develop a TinyChain service, it’s important to remember that the output of your code is a compute graph which will be served by a TinyChain host; your Python code itself won’t be running in production. This means that you can’t use Python control flow operators like if
or while
the way that you’re used to. For example:
after
It’s also important to keep in mind that TinyChain by default resolves all dependencies concurrently, and does not resolve unused dependencies. Consider this function:
This Op will always resolve to zero. This may seem counterintuitive at first, because you can obviously see the table.insert
statement, but notice that the return value table.count
does not actually depend on table.insert
; table.insert
is only intended to create a side-effect, so its result is unused. To handle situations like this, use the after
flow control:
Now, since the program explicitly indicates that table.count
depends on a side-effect of table.insert
, TinyChain won’t execute table.count
until after the call to table.insert
has completed successfully.
while_loop
Loops are probably the most difficult part of TinyChain to get used to if you've never used a graph runtime before.
Consider this simple while loop:
In a TinyChain compute graph, you have to account for the facts that a) you need the loop to run at execution time (when a user executes your graph), not encoding time (when the TinyChain Python client exports your graph configuration as JSON), and b) TinyChain Value
s are immutable:
Nested conditionals
Consider this example:
In this case, TinyChain is unable to resolve the dependencies of the state to return
without executing both branches of a
, which would make a
no longer a conditional (the table
would be deleted!). For this reason, nested conditionals are not allowed. The most foolproof way to handle a nested conditional is to use an Op
:
Examples: updating a Tensor conditionally
For more detailed examples on how to use common flow controls, take a look at the client tests.
Last updated