monthly gimite

試験運用中。

Pythonでブロック付きメソッド呼び出し

PythonRubyのブロック付きメソッド呼び出しみたいなのをやる方法メモ。

Ruby:

def foo()
  yield(1)
  yield(2)
  yield(3)
end

foo() do |i|
  puts(i)
end

Python:

def foo():
  yield(1)
  yield(2)
  yield(3)

for i in foo():
  print i

Rubyの方はputs(i)の部分がオブジェクト(Proc)化されてfooに渡されるみたいなイメージだけど、Pythonの方は逆にfooがオブジェクト(generator)化されてfor文に渡される感じなんですね…。

2007/1/14追記:

更にPython 2.5だと、Ruby

open("hoge.txt") do |f|
  ほげほげ
end

に対応する書き方

from __future__ import with_statement

with open("hoge.txt", "r") as f:
  ほげほげ

もあるらしい。