python contextmanagers and ruby blocks

Alia Khouri alia_khouri at yahoo.com
Sat Feb 21 03:46:08 EST 2009


As an exercise, I recently translated one of my python scripts (http://
code.activestate.com/recipes/576643/) to haskell (a penultimate
version exists at http://groups.google.com/group/comp.lang.haskell/browse_thread/thread/fb1ebd986b44244e#
in case anyone is interested) with the result that haskell has now
become my second favourite language (after python of course :-)

Just to change mental gears a bit, I'd now like to do the same and
create a ruby version. As I've progressed on the latter, I've been
struck by how pervasive the use of blocks is in ruby. For example:

class Builder
    attr_accessor :name
    def machine &block
        @name = "m1"
        block.call
    end

    def build(x, &block)
        puts x
        block.call
    end
end

builder = Builder.new

builder.machine do
    puts "hello #{builder.name}"
end

builder.build "hello" do
    puts "world"
end

which should print out:
hello m1
hello
world

Now, python's relatively new contextmanagers seem to provide something
similar such that one can write:

from __future__ import with_statement
from contextlib import contextmanager

class Builder:
    @contextmanager
    def machine(self):
        self.name = "m1"
        yield

    @contextmanager
    def build(self, x):
        print x
        yield

builder = Builder()

with builder.machine():
    print 'hello %s' % builder.name

with builder.build("hello"):
    print 'world'

Which brings me to my questions:

1. To what extent are python's contextmanagers similar or equivalent
to ruby's blocks?

2. If there is a gap in power or expressiveness in python's context
managers relative to ruby's blocks, what are possible (syntactic and
non-syntactic) proposals to bridge this gap?

Thank you for your responses.

AK



More information about the Python-list mailing list