[Python-ideas] Ruby-style Blocks in Python Idea

Mathias Panzenböck grosser.meister.morti at gmx.net
Tue Mar 10 03:16:48 CET 2009


Guido van Rossum wrote:
 > On Mon, Mar 9, 2009 at 4:09 PM, Terry Reedy <tjreedy at udel.edu> wrote:
 >> Like many other Pythonistas I recognize that that an uninformative stock
 >> name of '<lambda>' is defective relative to an informative name that points
 >> back to readable code.  What I dislike is the anonymity-cult claim that the
 >> defect is a virtue.
 >>
 >> Since I routinely use standard names 'f' and 'g' (from math) to name
 >> functions whose name I do not care about, I am baffled (and annoyed) by
 >> (repeated) claims such as "Having to name a one-off function adds additional
 >> cognitive overload to a developer." (Tav).  Golly gee, if one cannot decide
 >> on standard one-char name, how can he manage the rest of Python?
 >>
 >> (I also, like others, routinely use 'C' for class and 'c' for C instance.
 >>  What next?  A demand for anonymous classes? Whoops, I just learned that
 >> Java has those.)
 >>
 >> But I have no problem with the use of lambda expressions as a convenience,
 >> where appropriate.
 >
 > Andrew Koening once gave me a good use case where lambdas are really a
 > lot more convenient than named functions. He was initializing a large
 > data structure that was used by an interpreter for some language. It
 > was a single expression (probably a list of tuples or a dict). Each
 > record contained various bits of information (e.g. the operator symbol
 > and its precedence and associativity) as well as a function (almost
 > always a very simple lambda) that implemented it. Since this table was
 > 100s of records long, it would have been pretty inconvenient to first
 > have to define 100s of small one-line functions and give them names,
 > only to reference them once in the initializer.
 >
 > This use case doesn't have a nice equivalent without anonymous
 > functions (though I'm sure that if there really was no other way it
 > could be done, e.g. using registration=style decorators).
 >

With a small trick you don't need lambdas for this, if the keys are python 
identifiers. If they aren't you can add the real key to the info tuple and then 
generate a new dict in a oneliner. But yeah, it's a bit ugly/abusive. But it is 
possible without defining parts of the tuple at different places! :)

def info(*args):
	def wrapper(f):
		return args + (f,)
	
	return wrapper

def mkdict():
	@info("a",12,9.9,None)
	def foo():
		print "this is foo"

	@info("b",23,0.0,foo)
	def bar():
		print "this is bar"
		
	@info("c",42,3.1415,None)
	def baz():
		print "this is baz"

	return locals()
	
print mkdict()



	-panzi



More information about the Python-ideas mailing list