Mark and Continue (a constrained case of GOTO)

My point was that I am showing that you don’t need a marker you just need a workflow engine that can tell the runner what it should do next in this case by yielding an object.

In my example its about durable execution but it can apply to workflows where you don’t need it to be durable.

If the state is really complicated, I think you really should make it explicit.

I like Serhiy’s approach, but instead of just returning a function, return a class with a method:

class Step:
    def step(self) -> Step:
        raise NotImplementedError

@dataclass
class PlanStep(Step):
    some_data: int

    def step(self) -> Step:
        print("planned")
        return ImplStep(...)  # send whatever data he needs.

# etc.

Now all of the data transmission is explicit rather than be implicit. You can also do things like wrap or inherit from Step.

I personally am against new syntax for the case of emulating existing design patterns. Maybe what you are lacking instead is a good framework rather than syntax and such framework is best managed in a 3rd party library (though I don’t know of any on top of my head).

The only reason why I want to actually have goto-like constructions is for error handlings and just to avoid locals or nested ifs. If multiple errors paths have the same “error” handling, I’d rather have a single “goto error” path and be done with it rather than duplicating it. However, as I said in a previous post (My ideas for Python 3.16 (goto and clear terminal) - #6 by picnixz), goto is entirely replacable with a better logic or with a bit of churn (wrapper for instance to handle the error case uniformly).

There has been lots of proposals for goto-like semantics and none of them were accepted or gained enough support. If I were to choose one proposal, I would just choose to emulate the exact same goto as we have in C, possibly with the same constraints about scoping and cross-assignments. But any other kind of goto-like syntax is likely to get a strong -1 from me.


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

Have you considered the cost of introducing this? new syntax like that always comes with the cost of (1) teaching this (2) adding internals (3) answering questions about scope and lifetimes.

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

The control flow of mark seems much harder to follow, considering the examples that were given in the thread. And unlike in a loop, the break/continue only applies to the parent loop. However, continue is another beast. You can also jump to anywhere that is at the same level of indentation of the mark block (in your original example, impl is at the same level as review and thus you jump back; but with (existing) continue or break, you can only move forwards or repeat the same block. You don’t go before the block).

mark statements are chained like if-elif, so if you know the containing mark, finding siblings is no more difficult.

Your marks seem to contain complex logic, not just simple ones. Finding siblings will be difficult as it is with complex if-elif. And unlike if-elif-etc, marks are not exclusive. You can jump to any of them at any time and they just look like different pieces of logic (namely function bodies).


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.

In this case, I think the issue is not the syntax but how the problem is solved in the first place. We should not create new syntax just because the alternatives may not look nicer. I believe that switching on the return type would have been much cleaner here.

3 Likes

If the new syntax is just “syntactic sugar”—making an established way of doing things easier—I think you would have a strong argument. But if the current way of doing things is a well-established workaround for a language limitation, perhaps there is an opportunity to consider a language change?

I have worked with or written multiple frameworks for running workflows (including AWS StepFunctions, Cadence/Temporal, CWL, NextFlow, AirFlow, 3 different proprietary engines [2 of which I wrote], and my current quest framework). Proposing a language feature was not my first stop.

I think your example of “go to error” is a great use case for the feature.

Yes. I currently teach programming for a living. Developer experience (DevX) is an core part of my ongoing research. I honestly think this feature would be easier to teach than := or match expressions.

I’ve also considered core internals, but admittedly have less experience there. I figured that if a core CPython developer thought it was reasonable to float a more expansive version of goto, then a more restricted version should probably be viable (yes, I read your other thread before I started this one. :slight_smile: )

Difficulty is certainly in the eye of the beholder. For me, personally, it has never been difficult to set my cursor at a given level of indentation and scroll. But if tracking if-elif is considered difficult, then yes, mark would be as difficult.

Yes, my simple toy examples are, well, simple. And simple things are easy to reconstruct in different ways. When you boil an example down to its essence, you risk it being treated as a straw man.

I think there is an opportunity for the Python community to consider a new way to think about problems, not just refine the current way we think about problems. What kinds of algorithms could we make, and how simply would they be expressed if we had a more direct way to describe them?

As a workflow author, I often encounter situations where the simplest, most straightforward approach would be to say “go back to this line” or “jump ahead and skip this part”. But Python currently requires reformulating those simple concepts into terms of loops, branches, and functions.

But if the current way of doing things is a well-established workaround for a language limitation, perhaps there is an opportunity to consider a language change?

Is it? I would definitely not call it a language limitation. Many other languages do it (that is, using something else than goto).

I figured that if a core CPython developer thought it was reasonable to float a more expansive version of goto, then a more restricted version should probably be viable

For me, it’s either “we have gotos with some scoping semantics” (like in any other language supporting gotos) or we have none of it. Workflows are one of the use cases, but they are others and since all proposals for gotos were rejected in the past decade, it’s hard to see why it would be accepted now (AFAIR, none of them got support from core devs and that’s the first thing you want in general if the proposal wants to become a PEP at some point).

But Python currently requires reformulating those simple concepts into terms of loops, branches, and functions.

I believe this is exactly where we diverge. Python is meant to be written that way. I believe that if Python specifically doesn’t meet the requirements for specific tasks, then maybe it’s not the appropriate language.

For me, personally, it has never been difficult to set my cursor at a given level of indentation and scroll

My point was more on the fact that marks can appear at any point and jump to anything, unlike if-elif. You read a program from top to bottom in general. Once you are past an if, you cannot go in the elif branch. However, with marks, you can go to a sibling mark at the same indentation level. And like in C, such a reading flow is not necessarily natural. It’s really great for jumping at the end of the function for instance. In pseudocode, gotos are also widely used, both in teaching or academia. But it’s still harder to read that if it were a simpler loop most of the time IMO or explicit returns at every code path to stress what is being returned. It may be more error prone but it’s also more flexible when it comes to what the cleanup for the specific exit branch is.


I wanted to chime in this discussion because as a core developer I believed I need to tell you in advance that this idea is unlikely to be adopted since we also rejected (or more precisely, didn’t give support to) in the past all features related to goto. Unless a core developer comes forward with a proposal (including the treatment of lifetimes and scopes), I don’t think we will ever have gotos in the language.

That being said, I understand why you suggest that and I understand why this feature could be meaningful for people. At the same time, this can be both an argument for and against. “For” because it may simplify some logic for some code and “Against” because it is specifically used for something that could be written differently if it were thought differently in the first place. The same can be said for my use case of goto error, where people would simply tell me “return something else + add a wrapper to handle it and call that wrapper” instead.

3 Likes

I appreciate the candid warnings. I’ve loosely followed the arguments for/against goto in Python over the years and had a sense that this would immediately face opposition.

I teach an advanced course on framework-oriented design. Frameworks are something I think about often. One of the big ideas of frameworks is the creativity to rethink how things are expressed. It’s to imagine the clearest, most obvious way of expressing a solution, then making that form of expression possible. This contrasts with the approach of figuring out how to express the solution in the currently available constructs. There is a place for both approaches.

The motivation for a new framework is never “this is how we do things” but instead “this other way would be more intuitive”. The more closely aligned a framework is with intuition, the more it is adopted. It makes it genuinely easier to solve problems.

The very fact that proposals for some form of goto keep coming up suggests to me that there is an element of human intuition we have not yet modeled in Python. Why Python? Why not Python! This is hands down my favorite language to work in. It’s versatile, extensible, adopted, supported, intuitive (mostly…). We all love Python—why not make it more intuitive?

These use cases seem to be relevant:

  • Nested loops
  • State machines
  • Error handling
  • Switch statements

The fact that it exists is many (modern) languages and hasn’t sunk any ships suggests it’s a safe language feature, to be used with judgment and skill. If we can be so bold as to introduce pattern matching, might we be willing to consider a feature many languages already support?

That all said, I humbly recognize my incompetence in this matter: I’m not going to be the one that implements it. That is too far out of my wheelhouse. This will certainly be a lot of real work. I really appreciate the attention this proposal has received so far. Some good points have been made. I think I’ve said enough (at least for now) to make my case and let it ride on whatever merits it has.

While I may not have the right skillset for implementing the feature, I think I might have some intuition for how it might be used. If there is ever any interest in exploring the idea more seriously, I’d be delighted to be part of the conversation.

That’s true, but it’s worth noting that the first and most “obvious” idea is not always the best one. Sure, you might think “goto can solve my problem”, but that doesn’t mean nothing else could also solve it.

One thing that frameworks may find useful would be code snippets. Let’s say you let people edit some bits of code that are linked together in some way. There’s no law says they have to edit the entire .py file as a whole; you could, for example, provide a series of snippet editors, and then you combine those into your runner framework and build an actual executable module. That would allow you to have whatever clunky boundary code you need, without the “real” work needing to worry about it. (The most obvious example here would be to have them all be different functions.) You can also create your own special syntax for some specific feature, which then translates into something much more verbose - again, it can be something ugly and messy, but it’s hidden behind the nice tidy syntax.

Is that “Python-with augmentations”? Is it “a domain-specific language that looks a lot like Python”? Is it something else? It doesn’t really matter, as long as it’s of pragmatic value :slight_smile:

Fair enough. But what makes you think you have spotted a model that no-one else has thought of, throughout all the years people have been suggesting goto-like additions? Is this proposal somehow different, or is it just another in a long line of possible control structures? What makes this one special?

You are dismissive of existing approaches to solving the problem you describe as being “workarounds”. I don’t see how you can be so sure of that - workflows and state machines are incredibly common patterns, and it seems unlikely to me that the approaches that have evolved to handle them in Python would have survived this long if they were simply a (clumsy[1]) workaround catering for a gap in the language.

I personally find your proposal awkward and difficult to follow, whereas approaches like the continuation-style “return a function implementing the next step” approach that @storchaka demonstrated right at the start, look far more understandable to me. We can agree to differ on that, but I object to your claim that mark and continue is clearly a better solution.

Ultimately, a change like this will need a PEP, which in turn requires at least one core developer to sponsor it. And then, it will need broad consensus that the idea is a good one. Right now, this thread doesn’t seem to indicate that you’re anywhere near the level of support that would result in a successful PEP. That doesn’t mean you should drop the idea (ideas are good!) but it does mean that you need to spend more time understanding people’s reservations, and trying to incorporate them into your proposal. You teach advanced framework design, and that gives you a certain insight here. But please remember that the objections you’re seeing are coming from people with extensive experience designing the world’s most popular programming language. Your expertise, while relevant, is only part of the story.


  1. If they aren’t clumsy, what makes them workarounds rather than solutions? ↩︎

3 Likes

The way I do it today :

if research := True:
    print('Did research')

if plan := False
    print('Planned')

if impl := True:
    print('Implemented')
...

This (personal) way my script conveys that only the True and False values are to be edited before running…

The use case is more when I have a lot of complex process steps and I need to experiment several chains of operations. This has to be done at a higher level place.

What I could wish is more like (indicatively) :

block configure_system:
    os.system(...)  # install modules, modify config files, etc...

block prepare_data:
    download_files()
    generate_files()

block quick_study:
    quick_process(data_label)

block full_study:
    full_process(data_label)

data_label = "sample_1"

## comment/uncomment as needed
#run configure_system
run prepare_data
run quick_study
#run full_study

What is meant here is to clearly convey which part of the scripts are to be edited to adapt a chain of global operations… But there is no new functionality coming from here thus I never thought it might be subject to proposal.
(Idk whether I am off-topic here)

So, like, functions?

2 Likes

Yes, except when I look at the code I clearly know the blocks are the function-like, “macro-scale”, “pseudo-independent” steps that are meant to be ran at different times or in a different ordering.

FWIW, when I have code (a procedure, or proc) that I want to split up like this, I use a class with this pattern:

@dataclasses.dataclass(frozen=True)
class FooArg:
  # Often I'd have like 5-10 arguments here, so it's easier
  # for me to use a dataclass than list them all in __init__.
  x: str
  y: int

class FooProc:
  def __init__(self, arg: FooArg, /):
    self._arg = arg

  def run(self) -> SomeType:
    self._step1()
    self._step2()
    self._step3()
    return self._step4()

  def _step1(self) -> None:
    ...

  ...

Individual steps will often store intermediate results in private attributes other than _arg, to be read by later steps.

Usage:

result = FooProc(FooArg(...)).run()

The class always gets named something ending in Proc, and the dataclass passed to __init__ gets the same name but ending in Arg. If SomeType is created specifically for the proc (often it is another frozen dataclass) then it similarly gets named the same but ending in Ret.

Yes, I’ve heard “a class with only one public method other than __init__ is an antipattern,” but I disagree with that particular statement - it’s incredibly useful in this situation, and I haven’t seen a better pattern for it.

I make sure not to put any significant logic in __init__, in case I want it to become async at some point: run can easily become async, but __init__ can’t.

Macro-scale, like functions; pseudo-independent, like functions; and meant to be run at different times or in a different ordering, like functions?

I think you’re looking for functions here.

3 Likes

FWIW I don’t think you are asking for a goto statement

I think you are asking for a form of control flow management without recursion that’s easy to read

we have four options

  1. a new language construct which people are against
  2. A new primative provided by a framework either externally or internally in a python library - you say this isn’t enough
  3. Use existing python elements to do this - you don’t like this hence this thread
  4. Propose stackless functions a bit like inlining a function in a langauge like C - no syntax change
2 Likes

I wouldn’t say I’ve spotted a model no one else has thought of. I think my motivation was better characterized by “hey, I have similar opinions to these other people, but their ideas aren’t gaining traction; maybe I should add my voice to the cause.”

I apologize for coming across as “dismissive.” My desire for “a form of control flow management without recursion that’s easy to read” (well stated, @jamestwebber) is not because I don’t know how to solve a problem. I’ve been solving these problems for years using workflows and state machines. That these kinds of problems can be solved is well established.

My argument for a refresh on control flow hinges on the question: is there a more intuitive, fundamental, direct way to solve these problems that the ways we already use? When an answer says “you could solve it this way”, it’s missed the point of the question. Now, that very well could be poor delivery of the question on my part. This conversation has helped me see how to better articulate my point.

Why wouldn’t workarounds have have survived this long if there was no alternative? If the language doesn’t provide a more direct way to solve the problem, but the problem continues to exist, then by-hook-or-crook solutions will continue to exist.

That said, the existing patterns for workflows and state machines are not terrible. They work, enough people understand them, we’ve solved problems. I’m not claiming a superior approach, but rather a design that some people might find more intuitive.

It reminds me of the walrus operator story. Did we have existing solutions without := ? Sure. But did the introduction of := allow for more intuitive, direct solutions to some problems? I think it did (and I believe that was the prevailing motivation that justified the feature). Just because := exists, some people still choose to write:

while True
    item = input(...)
    ...
    if not item:
        break

instead of

while item := input(...):
   ...

In the := story, the argument was essentially “there could be another way enough users will appreciate” versus “we already have ways”.

Likewise, I think there is an unmet desire in the community for “better control flow”. While not everyone feels the need (“why would you want this?”), enough do that it keeps coming up.

I’m not claiming my idea (mark) is the right way to solve this problem. It may be that a simple C-style goto is the sweet spot.

@picnixz Could you please elaborate more on what “gotos with some scoping semantics” would look like?

I think this is very well stated.

I would state #1 differently:

  1. A new language construct which some people are against and which the decision makers are (rightfully) cautious to adopt.

#2 (a framework) and #3 (build-your-own) is enough to get the job done. Throughout my career (let alone the multitudes of other programmers across this globe) these approaches have been sufficient to ship real solutions to real problems.

But seeking for this language feature is not about “there is no good way to do this” but rather “let’s consider if we might have an even better way to do this”.

Maybe I chose my words poorly, but when I said “scoping semantics” but my initial concern was mainly about lifetimes and where we can use goto and to what kind of block we can jump to (and how locals/globals would interact).

gotos in C and in C++/Golang have different semantics and you’re not allowed for instance to cross over variable initializations in some cases. In Python, we shouldn’t have much issues since variables are not tied to a specific type at runtime but this is a question that needs to be answered whether as a non-question or by clarifying exactly what happens and how the VM would handle such jumps.

A label could be a point where execution can jump to, like inlining a function body but we should only be able to jump in the current scope. For instance, a class body is executed as suite of statements so should we be allowed to use goto outside a method definition? should we be allowed to do it outside a function? should we be able to have labels outside functions? how do we indent them? where should we put them when it’s a loop? can we maybe have label: for [...] instead to avoid an additional indentation for the loop body for instance?

So, when I say “goto with some scoping semantics”, I just mean “we need to be clear on what goto are allowed to do and where would they be allowed”. In addition, using new syntax features is also motivated by its usability within the stdlib itself so knowing that in advance is a prerequisite IMO. It wouldn’t reflect well if we wouldn’t even be able to use our own new features.

The main problem I have with goto in Python is that a label implies some indentation. Which then makes look the entire block as a function block. For instance:

def foo():
    a:
       <body-a>
    b:
       <body-b>
    <body-c>
    if a: goto a
    else: goto b

I see body-a and body-b as part of foo and at the same level of c. So I wished we had

def foo():
a:  body-a
b:  body-b
    body-c
    if a: goto a
    else: goto b

Visiually it makes more sense to me. Otherwise I see branching and don’t consider each labelled blocks identically (the above example isn’t the best but my point is that I don’t have any good way of labelling a line in Python without introducing an indentation block).

I think conceptually for me perhaps the simple approach is for Python to allow inlining of functions.

In my imagined scenario you can decorate a function with inline similar to how you can with asyncor property

inline def do_research():
    print("Did research")

inline def do_plan():
    print("Planned")

inline def do_impl():
    print("Implemented")

inline def do_review(inout decision):
    # Pure logic: evaluates or receives external state, sets decision
    decision = check_status()  # e.g., 'bad approach', 'bad idea', 'approved'

    if decision == "bad approach":
        do_impl()   # Jumps directly back to do_impl
    elif decision == "bad idea":
        do_plan()   # Jumps directly back to do_plan
    else:
        pass        # Falls through naturally to do_wrap

inline def do_wrap():
    print("All done!")

def main_workflow():
    decision = None

    do_research()
    do_plan()
    do_impl()
    do_review(decision)
    do_wrap()

Inlined functions keep most of the same rules as standard functions with the following exceptions

  1. These functions are stackless
  2. State is passed in via args, all local state in the inline function is lost since no stack
  3. Like with async generators return is banned because needs stack

Bytecode could look something like this

=== Parent Frame: main_workflow ===
Slot 0: decision

Offset  Opcode               Arg / Target           Comment
----------------------------------------------------------------------------------
# --- Prologue ---
00      LOAD_CONST           None
02      STORE_FAST           0 (decision)

# --- do_research() ---
04      LOAD_GLOBAL          print
06      LOAD_CONST           'Did research'
08      CALL                 1
10      POP_TOP

# ================================================================================
# PARENT TARGET 1: do_plan callsite (Offset 12)
# ================================================================================
12      LOAD_GLOBAL          print
14      LOAD_CONST           'Planned'
16      CALL                 1
18      POP_TOP
        # Falls through naturally to Offset 20

# ================================================================================
# PARENT TARGET 2: do_impl callsite (Offset 20)
# ================================================================================
20      LOAD_GLOBAL          print
22      LOAD_CONST           'Implemented'
24      CALL                 1
26      POP_TOP
        # Falls through naturally to Offset 28

# ================================================================================
# INLINED: do_review(decision)
# ================================================================================
28      LOAD_GLOBAL          check_status
30      CALL                 0
32      STORE_FAST           0 (decision)           # Mutates parent slot 0

# Check condition 1:
34      LOAD_FAST            0 (decision)
36      LOAD_CONST           'bad approach'
38      COMPARE_OP           ==
40      POP_JUMP_IF_FALSE    48                     # Not matched -> test next condition

# --- Jump to Parent's Target 2 ---
42      JUMP_BACKWARD        20                     # ---> Jump to PARENT OFFSET 20 (do_impl)

# Check condition 2:
48      LOAD_FAST            0 (decision)
50      LOAD_CONST           'bad idea'
52      COMPARE_OP           ==
54      POP_JUMP_IF_FALSE    62                     # Not matched -> FALLBACK into parent

# --- Jump to Parent's Target 1 ---
56      JUMP_BACKWARD        12                     # ---> Jump to PARENT OFFSET 12 (do_plan)

# ================================================================================
# FALLBACK: Resumes normal parent code (Offset 62)
# ================================================================================
62      LOAD_GLOBAL          print                  # do_wrap()
64      LOAD_CONST           'All done!'
66      CALL                 1
68      POP_TOP

70      LOAD_CONST           None
72      RETURN_VALUE

The offsets are all relative to the first non-inlined function doing the call, perhaps this could also be done using the new syntactic macro proposal (it certainly could be simulated using decorators and AST module) ?