From: Charles Comstock Date: 2004-04-06T02:59:24+09:00 Subject: Re: deciding between ruby and python Vadim Nasardinov wrote: > On Monday 05 April 2004 11:08, Gavin Sinclair wrote: > >>And there is an insurmountable limitation (I think): > > . > >> chars = words = lines = 0 >> str.each do |line| >> chars += line.chomp.length >> words += line.split >> lines += 1 >> end > > . > >>I don't believe [Python] can carry outside state into its >>"substitute for blocks". > > > Feature-by-feature comparisons are useful insofar as they help you > understand differences and similarities between the two languages > being compared. Consider English and German, for example. The former > has an "insurmountable" limitation of not having explicit case > markings for the nominative, genitive, accusative, and dative cases > the way German does. > > Now, this may be a useful thing to know, but it's useless as far as > comparing the overall expressiveness, naturalness, and ease of use of > these two languages. > > As Jim Weirich already pointed out in ruby-talk 96368, closures are a > poor man's objects. One way of making a function carry state in > Python is to implement it as a callable object: > > $ cat poor_mans_closure.py > #!/usr/bin/python > > class Foo: > "A poor man's closure" > > def __init__(self, state): > self.__call__ = self._call > self.state = state > > def _call(self, x, y): > return x * self.state + y > > > foo1 = Foo(1) > foo2 = Foo(42) > > print foo1(2,3) > print foo2(2,3) > > $ ./poor_mans_closure.py > 5 > 87 > Yea but that doesn't give you the guarenteed cleanup that the yield syntax allows. In c++ this would be accomplished by using a guarded object that would destruct when the scope was exited, there is no comparable operation in java, without explictely declaring a wrapping try / catch / finally. In C# V2.0 it is possible because of the existance of yield. It is not possible in C# 1.0. It is possible in ruby ala: def setup_and_teardown #code which must execute before code block a and b yield #code which must execute after code block a and b end setup_and_teardown() do # operation a) which may fail but we want setup and cleanup code # guarenteed end setup_and_teardown() do # operation b) which may fail but we want setup and cleanup code # guarenteed end Is there any sort of similar guarded block equivalent in python while still allowing multiple blocks to be called and not requiring a complex dispatcher routine? Charles Comstock