There are many ways to implement it depending on the type of command the step
s are:
- If the steps are functions, put them into a
list
and iterate through them, like this:
def command_list(start_at):
commands = [func1, func2, func3, func4, ...]
for c in commands[start_at:]:
c()
This can be generalized and improved like this:
def func_command_exec(command_l, start_at=1, arguments=()):
""" Arguments shall be passed-in in the form:
tuple[dict[str, dict|list], ...]
Example:
({'kwargs':{'a':1, 'b':2}, 'posargs': [1, 2]}, ..)
"""
# add some validation here
if not isinstance(start_at, int) or not (0<start_at<len(command_l):
# do some kind of action here, for example raise an exception or print something. I'm just going to return here.
return
if len(arguments) != len(command_l):
# do some kind of action here, for example raise an exception or print something. I'm just going to return here.
return
rets = []
for i, a in zip(command_l[start_at:], arguments):
k, p = a['kwargs'], a['posargs']
retn = i(*p, **k)
rets.append(retn)
return rets
In the above code, I added the arguments
parameter of the function so that you can use this generically in many different scenarios. Also, I made the function list as an argument to be passed-in so it is not a fixed value. Returning a list
containing all the return values of the functions is also a very convenient feature in many situations.
- If the commands are statements, put them in a
list
as strings and iterate over the list
, using the built-in function exec()
to execute the statement strings, as follows:
def command_list(start_at):
commands = ['statement1', 'statement2', 'statement3', 'statement4'...]
for c in commands[start_at:]:
exec(c)
In summary, although there is no goto
in python, there is many ways to mimic the behavior of it.
for command in commands[start_at:]: command()
. But what's the context here?