Python equivalent of continuations with Ruby

What is the Python equivalent of the following code in Ruby?

def loop
  for i in 1..4
    puts i
    callcc {|continuation| cont=continuation} if i==2
  return cont

> c=loop

Reference: Secrets of lightweight development success, Part 9: Continuations-based frameworks

Asked by: Joyce404 | Posted: 24-09-2021

Answer 1

The article you quoted contains a link to Continuations Made Simple And Illustrated in the Resources section, which talks about continuations in the Python language.

Answered by: Elise247 | Posted: 25-10-2021

Answer 2

take a look at the yield statement to make generators.

I don't speak any ruby, but it seems like you're looking for this:

def loop():
    for i in xrange(1,5):
        print i
        if i == 2:

for i in loop():
    print "pass"

Edit: I realize this is basically a specialization of real continuations, but it should be sufficient for most purposes. Use yield to return the continuation and the .next() message on the generator (returned by just calling loop()) to reenter.

Answered by: Agata812 | Posted: 25-10-2021

Answer 3

Using generator_tools (to install: '$ easy_install generator_tools'):

from generator_tools import copy_generator

def _callg(generator, generator_copy=None):
    for _ in generator: # run to the end
    if generator_copy is not None:
        return lambda: _callg(copy_generator(generator_copy))

def loop(c): # advance to yield's expression
    return _callg(c, copy_generator(c))

if __name__ == '__main__':
    def loop_gen():
        i = 1
        while i <= 4:
            print i
            if i == 2:
            i += 1

    c = loop(loop_gen())
    print("c:", c)
    for _ in range(2):
        print("c():", c())


('c:', <function <lambda> at 0x00A9AC70>)
('c():', None)
('c():', None)

Answered by: Edward859 | Posted: 25-10-2021

Answer 4

There are many weak workarounds which work in special cases (see other answers to this question), but there is no Python language construct which is equivalent to callcc or which can be used to build something equivalent to callcc.

You may want to try Stackless Python or the greenlet Python extension, both of which provide coroutines, based on which it is possible to build one-shot continutations, but that's still weaker than Ruby's callcc (which provides full continuations).

Answered by: Elian858 | Posted: 25-10-2021

Answer 5

def loop():    
    def f(i, cont=[None]):        
        for i in range(i, 5):
            print i
            if i == 2:
                cont[0] = lambda i=i+1: f(i)
        return cont[0]
    return f(1)

if __name__ == '__main__':
    c = loop()

Answered by: Roland843 | Posted: 25-10-2021

Similar questions

conventions - I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?

I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not seem to be as clearly defined is how exactly the overflowing text should be formatted. Do I push it all the way back to col 1? To the col where the original line starts? To the start of the parenthese...

Why do indented explicit line continuations not allow comments in Python?

I'm writing a Python parser to learn Flex and Bison, and I'm trying to find out why only the first of these programs is valid Python. \ # This is valid Python produces no error. \ # This is not valid Python produces this error: File "", line 1 \ ^ IndentationError: unex...

Continuations in python

is there any equivalent construct for continuations in python. I have been reading about continuations and am just being curious and want to know as there is nothing about that in the docs.

python - Regular expression to match line continuations that begin with whitespace?

I'm trying to extract "entries" from a text file using a regular expression. Each line of the file is a separate entry unless the line begins with whitespace, in which case that line is a continuation of the previous line. Example: import re INPUT = """\ This is entry 1. This is entry 2. And this is entry 3. This is entry 4.""" OUTPUT = ["This is entry 1.", "This\n is\n entry 2.",...

numpy - Readability of Scientific Python Code (Line Continuations, Variable Names, Imports)

Do Python's stylistic best practices apply to scientific coding? I am finding it difficult to keep scientific Python code readable. For example, it is suggested to use meaningful names for variables and to keep the namespace ordered by avoiding import *. Thus, e.g. : import numpy as np normbar = np.random.normal(mean, std, np.shape(foo)) But these sugg...

continuations - Cleanest way to compute less in a function by implicitly knowing what the callback / caller function is in Python?

The specific use case I have in mind is that say I have two matrices like A = [[1, 1], [1, 1]] B = [[2, 2], [2, 2]] and I want to write a function like multiply to compute their dot product like this: def multiply(X, Y): # some code to compute the ij-th entry of the resultant matrix return result however immediately after this computat...

How to avoid line continuations in Python imports

I have a number of classes / functions to import from a module and linters/ style checkers (pylint, flake, pep8) are complaining that the line is too long and I am forced to use line continuation which is ugly: from my_lengthy_module import FirstClass, SecondClass, ThirdClass, \ foo_bar_with_long_name, bar_foo_with_longer_name, \ FourthClass, bar_foo_with_longer_name...

lambda - yet another question about python continuations

all trying to work out how continuations work in python. i have the following code to calculate fibonacci using a python cps implementation ( i realize that it is building a stack, but for this question i am hoping this code will be sufficient ). def fact_cps(n, k): print(&quot;n:%s&quot; %(n)) if n == 1: return k(1) else: return fact_cps(n - 1, lambda v: k(v * n) ) if __name__ =...

Python, how to read a file with some multi-line continuations into a dictionary?

I am trying to iterate through a file which is delimited by = and create a Python dictionary. It has varying line structure and length with: 1.) Some easy to delimit key / value pairs 2.) Some commented lines 3.) Some empty lines 4.) Some multi-lines using \ to indicate continuation. It is the multi-line part I am struggling to read into the dictionary. Below is a representation of the file (called file.txt)...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python