Mark and Continue (a constrained case of GOTO)

There have been many discussions that relate to goto. For example:

There are many more, but as a new contributor, I’m not allowed to include more than two links in this post. The continuing recurrence of this theme suggests to me a general unsettledness on the issue.

I think Dijkstra was wise to champion the elimination of general goto in favor of while, for, and function calls. He argued that human comprehension was important, and the ability to reason about an abstraction required a contract around that abstraction. If you call a function, you need confidence that control flow will return to the call site and not jump to some arbitrary location in the code.

But why does this still keep coming up?

Nested loops (using break, continue) is one recurring theme. Another is workflow logic.

Consider an AI software-factory pipeline:

  1. Research the feature
  2. Plan an implementation
  3. Implement
  4. Review the implementation
    1. If needed, return to Implement
    2. If really needed, return to Plan
  5. Wrap up

Right now, to implement this logic, you’d need something like:

  • Multiple while loops with boolean flags to control continue
  • Multiple while loops with try-except blocks to use exceptions to return

In each case, we depend on while as the only construct for the idea “return to this earlier point of code.” But while was intended to mean “this block of code should run zero or more times”. While related, these are different concepts, and I believe that treating them the same is once source of the ongoing malcontent around break and continue.

As one who has written many workflows throughout his career to date, I would love the ability to present clear, concise workflow logic in Python code. Extra booleans that must be modified in concert—carefully set and cleared—just to communicate “go back to this point” introduces unnecessary complexity and violates the fundamental intent of a programming language: a language serves to bring the articulation of the solution closer to the human’s intuition while providing a deterministic, exact articulation of the bits to the processor. When the human must deviate from their intuition to accommodate the limitations of the language, and opportunity to consider the language emerges.

So, here’s what I propose.

print('hi')
mark research:
    print('Did research')

mark plan:
    print('Planned')

mark impl:
    print('Implemented')

mark review:
    decision = decide(...)
    if decision == 'bad approach':
        continue impl
    if decision == 'bad idea':
        continue plan

mark wrap:
    print('All done!')

What does this show?

  • mark is a new keyword. It represents a control statement like while, and within that block a continue might direct control flow back to this location. It accepts a valid Python identifier as a label for the mark.
  • Multiple mark statements chain together, like if and elif. A nestedcontinue can jump to any marks within the chained statement.
  • break would be used to exit the mark statement (i.e. the chain).

Importantly, this is not arbitrary goto. Just as break and continue are bounded by a containing loop, mark provides a scope for the logical jump, maintaining the boundaries of the abstraction.

Other thoughts:

  • Does it need to be continue? No—we could use goto, jump, or any other term. But continue already exists and already carries the semantics of “jump from here to another location”. This would just add an extended syntax.
  • How are nested mark statements handled? Can you continue to an outer mark? We allow nested try-except blocks, so my hunch would be yes. continue would find the first mark statement containing a matching label, searching from inner to outer, just like nested except blocks.
  • How do we determine the end of a mark chain? I’m not decided on this. You could have another keyword, like end, but it is only needed when the scope (i.e. function) requires multiple mark chains that must stay separate. It seems like a rare case to impose so much verbosity. My inclination is to just say that all mark statements of the same indentation within a scope are automatically chained. The code author can decide which mark labels to jump to or not.
  • This has nice similarities to while and addresses some nested while use-cases; what about for? This is definitely an open question, but my hunch so far is this: for is by definition more structured and bounded than while, and this more amenable to decomposition with function calls. Because for is bound to the state of the list (or other iterable), the logic of the loop can be transferred to another function that accepts the list. However, while is used when the state controlling the loop is more complex and often relies on and mutates multiple values within the scope. These scenarios are not amenable to decomposition because the new function isolates the state too much. Thus, it may be that most nested-for scenarios can be cleanly handled with function calls, while many nested-while scenarios might be simplified with mark syntax.
print('hi')
def research():
    print('Did research')
    return plan

def plan():
    print('Planned')
    return impl

def impl():
    print('Implemented')
    return review

def review():
    decision = decide(...)
    if decision == 'bad approach':
        return impl
    if decision == 'bad idea':
        return plan
    return wrap

def wrap():
    print('All done!')

step = research
while step:
    step = step()
24 Likes

The example you include reads more like a state machine and there are many ways currently without new syntax to achieve state machines in Python.

I find the new continue syntax you are recommending to be something that would hinder readability. With continue <label> the “where am I” information lives only in the control flow, so a reader has to find every continue that targets a mark to know what can be true when that block starts.

1 Like

I would counter-propose that if anything, Python just adds Zig’s labeled blocks.

outer: while x:
  middle: while y:
    while z:
      if cond:
        continue :middle  # jumps to "while y"
      if other_cond:
        break :outer  # breaks out of the "while x" loop

(note, the label middle: and reference :middle may need to be written with different syntax in Python to avoid ambiguity)

or as a less readable alternative, PHP’s numbered break/continue:

while x:  # 3 points here
  while y:  # 2 points here
    while z:  # 1 points here
      if cond:
        continue 2  # jumps to "while y"
      if other_cond:
        break 3  # breaks out of the "while x" loop

I would suggest reading the linked pages to see how these work. It would be nice if something got added to address this, since this topic keeps coming up (and I feel like I’ve made these proposals before, too). Personally I believe the Zig solution is the correct one since it’s more readable and you don’t have to adjust a bunch of numbers if you insert a new loop in the middle of the hierarchy.

1 Like

Based on the solution you are solving it looks a lot more what you are after is a better way to declare workflows, often those workflows are implemented using durable execution and I think this could be done via the @durable: compile generators into picklable state machines - #14 by jcampbell05 proposal

I’ve used the stack approach before. This approach works fine when the state is easily compartmentalized and you are willing to pass everything along to each call. It get’s really bloated when the state is complicated.

It also requires that any dependencies of downstream steps be passed through earlier steps, further adding to bloat.

Another similar approach is instead of using recursion to “return to” an earlier step, you can raise a step-specific exception which is caught by the relevant step:

def plan():
    while True:
        try:
            print('plan')
            impl()
        except ReturnToPlan:
            pass
def impl():
    ...
    if bad_impl:
        raise ReturnToPlan()

But I think the strongest argument against either of these approaches is: in both cases we are clearly bending the intuitive, natural way of solving the problem to accommodate the limitations of the language.

This proposal is not about making workflows possible; there exist plenty of ways demonstrating that is possible. This proposal is about describing workflows (a domain I have significant experience in, although I believe other logical constructs will come up) in an intuitive, accurate, straightforward way.

Fair concern.

My thoughts:

  • We already do this with continue: the reader must look outward to find the nearest while or for to understand what happens next; but the indentation leads the user to the answer.
  • mark is the same: you cannot use continue label outside of a mark block, so finding the containing mark is no more difficult than while
  • mark statements are chained like if-elif, so if you know the containing mark, finding siblings is no more difficult.
  • mark blocks are scoped to a function, just like while, if-elif, etc. So comprehending the impact of a mark on the logic is constrained in scope and should ultimately be thematic to the function (if it isn’t, the author has other fish to fry)

So, in the end, I don’t think mark adds any more complexity than we already deal with using loops and conditional branching.

1 Like

There’s no longer any indented suite within which continue occurs. It can occur anywhere after a mark has been seen. Reasoning about code like that is (IMO, at least) significantly harder.

2 Likes

You should really check out my durable workflow proposal I linked to above

it basically implements something along those lines like workflow engines like AWS etc

The main argument against arbitrary jumps is that it gets really hard to mentally track and reason about program state. Even the current continue/break can get tricky when the surrounding state is complex enough. To me the state being so complicated that it can’t easily be passed to a function call is a big indication that it also is too messy to use gotos. So what is the actual use case then?

3 Likes

Funny you mention this. I have a durable execution framework of my own (warning: it’s under active refactor, so read at your own risk: GitHub - beanlab/quest_framework: A Python framework for fault-tolerant workflows · GitHub ).

I’ve written and used many workflow engines, including AWS StepFunctions. Quest is designed using replay, much like Temporal.

AND, last week I built a small proof-of-concept to support goto-like behavior that relies on replay:

from functools import wraps
from typing import Concatenate, ParamSpec, TypeVar, Callable


class _GoBack(BaseException):
    def __init__(self, to_step):
        self.to_step = to_step
        super().__init__(to_step)


class ControlFlow(dict):
    """
    Learns what steps exist by initial should_run queries
    Raises an exception to return to an earlier step
    """

    def __init__(self):
        super().__init__()
        self._first_pass = True
        self._steps: dict[str, bool] = {}

    def first_pass(self) -> bool:
        return self._first_pass

    def should_run(self, step_name: str) -> bool:
        should = self._steps.get(step_name, True)
        self._steps[step_name] = False
        return should

    def __call__(self, step_name: str) -> bool:
        return self.should_run(step_name)

    def return_to(self, step_name: str):
        if step_name not in self._steps:
            raise ValueError(f'Unrecognized step: {step_name}')
        raise _GoBack(step_name)

    def __bool__(self):
        return not self._steps or any(self._steps.values())

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        should_run = False
        if exc_type is _GoBack:
            self._first_pass = False
            for step in self._steps:
                if step == exc_val.to_step:
                    should_run = True
                self._steps[step] = should_run
            return True  # i.e. swallow the exception
        return False  # i.e. allow the exception to continue to raise


P = ParamSpec("P")
R = TypeVar("R")


def with_control(func: Callable[Concatenate[ControlFlow, P], R]):
    @wraps(func)
    def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
        control = ControlFlow()
        # noinspection PyInconsistentReturns
        # ControlFlow will always be truthy on the first pass
        # And ControlFlow will always be truthy if the function should run again
        # And ControlFlow will always be falsy if func did not complete
        #  so the only way out is for func to complete
        while control:
            with control:
                return func(control, *args, **kwargs)

    return new_func


if __name__ == '__main__':
    # A demo of how to use ControlFlow
    # State that must persist between passes should be stored in `control`
    # and initialized under a `control.first_pass()` block
    
    @with_control
    def main(control: ControlFlow):
        if control.first_pass():
            control['count'] = 0

        if control('greeting'):
            print('Hi!')
            
        if control('plan'):
            control['count'] += 1
            print('PLAN', control['count'])

        if control('build'):
            print('BUILD')

        if control('review'):
            decision = 'bad_idea' if control['count'] < 2 else 'great'
            print('REVIEW', decision)
            if decision == 'bad_idea':
                control.return_to('plan')

        if control('wrap-up'):
            print('WRAP UP')


    main()

So, I have workarounds to Python’s limitations. But the point of this proposal is not a StackOverflow-esque “how do I?” but a “why is this not simpler in Python?”.

I think what python needs is built in primatives to make it easier to build these workflows

basically having batteries included, this is how async support started in python which is why I was going that angle

I think syntax changes risk making python way more complex and I don’t think are needed in any case.

in fact I have a POC that could be used to do what you are suggesting if it was built into python itself it would look something like this

from durable import durable

# --- Durable Actions ---

@durable
def do_research():
    print('Did research')
    return 'research_done'

@durable
def do_plan():
    print('Planned')
    return 'plan_done'

@durable
def do_impl():
    print('Implemented')
    return 'impl_done'

@durable
def do_review():
    return decide()

@durable
def do_wrap():
    print('All done!')

def decide():
    # Replace with your actual decision logic
    return 'approved'


# --- Durable Workflow ---

@durable
def main_workflow():
    print('hi')

    # Step 1: Research runs once initially
    yield do_research()

    # Step 2: Loop structures represent the label jumps (continue plan / continue impl)
    while True:
        yield do_plan()

        while True:
            yield do_impl()

            decision = yield do_review()

            if decision == 'bad approach':
                # 'continue impl': repeats the inner loop
                continue
            elif decision == 'bad idea':
                # 'continue plan': breaks out to the outer loop
                break
            else:
                # Step approved: break out of implementation loop
                break

        # If not sent back to plan, exit the outer loop
        if decision != 'bad idea':
            break

    # Step 3: Wrap up
    yield do_wrap()

Happy to be wrong but seems like it would be better to create this common seam that handles control flow and figure out any syntax changes later on

Providing a link to the POC will make it easier for people to consider it.

“Arbitrary” is in the eye of the behold. One might argue what while + continue allows arbitrary loop continuation and we should restrain ourselves to only well-defined for loops. Yes, this proposal is more permissive than a while loop, and given that the programming community has largely been constrained to while for several decades, anything more flexible could be cast as allowing “arbitrary” behavior. But mark is a long shot from goto with targets on any possible line of code.

Yes, continue can get tricky when the surrounding code is complex, just like nested while, if, etc. ANY language feature can be accused of being hard to understand when the code is complicated. And ANY language feature can be abused in ways to make the code harder.

I think the more helpful question is: can this language feature be used to simplify code?

So far, I think the workflow scenario is a strong use case. Describing a sequence of steps with multiple back loops is not so uncommon.

Here’s another example from my work this very morning.

Here’s what I ended with, given the current constraints of Python:

async def example():
    async with Workflow('demo', workflow) as work:
        identities = [None]
        while True:
            try:
                async with work.resource_stream(identities) as stream:
                    async for resources in stream:
                        ...
                        ident, name = ...
                        result = await work.invoke_action(ident, name, *args)
                        if name == 'name.put' and result not in identities:
                            raise NewIdentity(result)
                break
            except NewIdentity as new_id:
                identities.append(new_id.identity)

Here’s what this could look like with mark:

async def example_with_mark():
    identities = [None]
    mark new_identities:
        async with work.resource_stream(identities) as stream:
            async for resources in stream:
                ...
                ident, name = ...
                result = await work.invoke_action(ident, name, *args)
                if name == 'name.put' and result not in identities:
                    identities.append(result)
                    continue new_identites

Less indentation. Clear handling of the nested loops mark new_identites and async for resources. No try, no break.

Yes, I could also have solved the problem by breaking out the for body into another function and switching on the return type (is it a new identity or a clean exit). The existence of a workaround is not an argument against a language feature who’s purpose would be to avoid workarounds.

I think your example conflates durable execution (a wonderful idea about which I am passionate) and expanded control flow (the point of this discussion thread).

The control flow in your example (specifically, continuing a specific loop in a series of nested loops) does not rely at all on whether the code supports durable execution. Thus, you make the case for labeled loops with expanded continue syntax. This has been proposed many times. There are merits to the idea. mark could be used to address many nested-loop scenarios (but not all of them as it currently stands), but it also addresses control-flow scenarios that are not simply nested loops.

I’m not sure I follow. In this proposal, continue label can only occur within an indented block of a mark statement.

Inasmuch as while and mark both define targets to jump to with continue, there is significant overlap. Loops imply the logic of looping back by default, but might move on, whereas mark would imply moving on by default but might loop back.

The move-on-by-default also allows mark to be used to address the absence of switch statements in Python (statements, not expressions). mark would enable switch-with-fallthrough behavior.

That said, there are some problems where the nested loop structure is probably the clearest representation of the solution, and having the ability to continue a desired loop would be awesome.

I much prefer Zig’s labeled approach over PHP’s numbered approach.

I wonder if we can both? Introduce mark but allow while and for to be likewise labeled and continued.

That’s not what your original post showed. The continue impl is not in the scope of the mark impl block.

1 Like

I see what you are describing.

The point is that mark blocks would chain together like elif blocks. So finding a continue target requires stepping up to the containing mark block then scanning its siblings for the label.

It is more to scan than a single while. But given that mark blocks only chain within the function’s scope, the search space is syntactically constrained and organized by indentation.

So, to any mark block within a single function? Yes. But inasmuch as goto can literally jump anywhere, I’m not sure I would use that term to describe the behavior of mark.

It would be better than a workaround if you could give a meaningful name to the subpart that gets broken out. For example, is that processing one job? Maybe what you have is a workflow, and separately, a handler for a single job (which can be a separate function). Yes, it’s a workaround if the ONLY reason for the function is to be able to return from it, but often the boundary where you want to multi-level break is also a meaningful categorizaiton in its own right.