Python Tutorial Was: Guido's regrets: filter and map

Terry Hancock hancock at anansispaceworks.com
Tue Nov 26 07:00:11 EST 2002


On Tuesday 26 November 2002 02:16 am,  David Brown wrote:
> Good names are the key to readable and maintanable programming.  But there
> are plenty of cases where no name is better than some dummy name.  If you
> have to refer to something, it should have a good, sensible name.  If you
> don't have to refer to it, then it is an advantage to have no name - it
> saves cluttering namespaces, and it makes dir() more useful.

Yes, I agree. I think lambda does the same thing
for functions that literals do for basic variable types:

# Using a temporary variable...
a = 2
myfunc(a)

# ... is analogous to defining a single-use function ...
def a():
    return 2
mydispatch(a)

# ... whereas using a literal ...
myfunc(2)

# ... is like using lambda
mydispatch(lambda x: 2)

These are not only shorter than the temporary variable/named-function
versions, they are clearer -- since the name "a" doesn't carry any meaning.
It's only conceivable meaning is transparently what it does (i.e. return a 2),
so it serves no documentation purpose to name it. In this case, defining it
in place really makes more sense.

Of course if the function did something complicated, I'd far rather have a
descriptive name attached to it, and it would require more than a simple
expression (probably) to define it. The same thing applies to variables -- if
you must do some complex arithmetic to figure it out, it probably makes
sense to do the math, name it something appropriate to indicate
conceptually what the quantity is, and then pass it on to the function.

The existing lambda seems appropriate for encouraging this behavior, 
since it's difficult to express any function complicated enough to confuse
the reader as a simple expression (I've seen it done for show -- but it
doesn't seem like it would happen much in practice).

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list