High Order Messages in Python
Alex Martelli
aleaxit at yahoo.com
Mon Oct 24 10:52:40 EDT 2005
Kent Johnson <kent37 at tds.net> wrote:
...
> For example to open a file and read from it uses two closures, one to wrap
> a block with the file open/close, one to iterate lines (from the pickaxe
> book):
>
> File.open("testfile") do |file|
> file.each_line { |line| puts line }
> end
Good example -- Ruby blocks are used both for iteration, and for
non-iterative wrapping of a single action with "try-finally" semantics.
Python's generators, up to 2.4, don't really support the non-iterative
part of this well, and have other limitations (they can get values "out"
with yield, but can't easily or naturally get results back "in"...). In
the forthcoming 2.5, Python generators will be enriched with enough
functionality for these purposes, and a new statement "with" to clearly
indicate the non-iterative case (while "for" indicates iteration).
So, in Python 2.5, the above snippet may become, in Python:
with opening("testfile") as my_file:
for line in my_file:
print line,
The fact that 2.5 will acquire extra functionality to "round out"
generators &c to the power of Ruby blocks may be taken as a clear
indication that, right now (Ruby 1.8.* vs Python 2.4.*), Ruby's blocks
are somewhat more powerful. As for the differences in style that will
remain when Python 2.5 is born, we'll be back to "personal taste" level
issues, it appears to me.
Alex
More information about the Python-list
mailing list