What's better about Ruby than Python?

Alex Martelli aleax at aleax.it
Thu Aug 21 17:47:59 CEST 2003


Jacek Generowicz wrote:
   ...
> For this reason it is rarely a good idea to define a macro for a
> single use. However, it becomes an excellent idea if the idea the
> macro expresses must be expressed repeatedly. The same is true of
> functions, classes, modules ...

Not at all.  "Defining a function for a sinmgle use" is often a
perfectly valid way to make a program MUCH CLEARER.  Example:

def perimeter_of_right_triangle(leg1, leg2):
    def hypothenuse(leg1, leg2):
        return math.sqrt(leg1*leg1 + leg2*leg2)
    return leg1+leg2+hypothenuse(leg1,leg2)

Here, the local function 'hypotenuse' is introduced _purely for
readability purposes_ -- as a stylistic alternative to the
introduction of a _variable_ of the same name, i.e.:

def perimeter_of_right_triangle(leg1, leg2):
    hypothenuse = math.sqrt(leg1*leg1 + leg2*leg2)
    return leg1+leg2+hypothenuse

Breaking up a complicated expression with well-named intermediate
variables or functions is an excellent technique to enhance the
expression's readability.  The key, of course, is LOCALITY of
usage: if the function, or intermediate variable, was defined
far away, the purpose would be lost.  Being in the immediate
vicinity, the var or fun ISOLATES AND NAMES a well-defined part
of the expression,  If macros were similarly constrained, with
their definition immediately available, they wouldn't be
anywhere as dangerous (their usefulness, of course, would also
be diminished in roughly the same proportion).


Alex






More information about the Python-list mailing list