Ruby like syntactic sugar

F Jamitzky fxj at mpe.mpg.de
Tue Mar 2 16:26:17 EST 2004


It is rather easy to define functions in python that mimic the special
ruby syntactic sugar like:

5.times { print "Hello World!" }

or

[toast, cheese, wine].each { |food| eat food }

In python these fragments can be written as:

5 *times(lambda: printf("Hello World!") )

or

[toast, cheese, wine] *each (lambda food: eat(food) )

by defining a Times class like that:

class Times:
    def __rmul__(self,n):
        for i in range(n):
            self.func()
    def __call__(self,func):
        self.func=func
        return self
times=Times()

Was this intended as a language feature or is this style an
"unpythonic"
missuse of the syntax ? I like the way of writing loops and list
comprehensions that way, but I think there will be an outcry of some
people. What do you guys think about extensions like that ?

cheers
Ferdinand



More information about the Python-list mailing list