0

I have a list of iterative Python commands:

def command_list(start_at):
    step1
    step2
    step3
    # ...
    stepN

Now I want to start_at different steps in this list of commands and then execute until the end. It seems there is no goto command and the case statement sadly has an implied break, so what is the best way to implement this?

3
  • 4
    It depends. If they're functions (or could be extracted to functions) you could do e.g. for command in commands[start_at:]: command(). But what's the context here?
    – jonrsharpe
    Commented May 29 at 9:15
  • Thanks, that looks like a good idea, most of the commands are functions already, so I just would have to create functions for those commands that aren't yet.
    – Sur3
    Commented May 29 at 9:21
  • @jonrsharpe Can you formulate an answer like this, so I can tag it as solution?
    – Sur3
    Commented May 29 at 9:29

1 Answer 1

0

There are many ways to implement it depending on the type of command the steps are:

  1. 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.

  1. 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.