[Python-Dev] "as" mania

Andrew Koenig ark at acm.org
Tue Mar 7 20:00:48 CET 2006

> Thinking over it, this is too much a difference between the with-"as" and
> my "as", so I'm abandoning this idea. My "as" would just have been a
> shortcut to avoid writing longish expressions that have to be checked for
> true-ness and then tinkered with.

ML has a similar feature, which you may consider as an argument either for
or against it depending on your taste.  The point is that ML lets you write
"patterns" that decompose data structures, and the "as" usage lets you talk
about the whole data structure and the decomposed one at the same time.

For example, in ML, :: works like "cons" in Lisp, so that x::y is a list
with a first element of x and a tail of y, which must be a list.  In other
words, [3, 4, 5] is equivalent to (3::4::5::nil) in ML.

Now consider the following:

	fun merge(nil, y) = y
	  | merge(x, nil) = x
	  | merge (x as xh::ht, y as yh::yt) =
		if xh < yh
		then xh::merge(xt, y)
		else xt::merge(x, yt)

Without the "as" clause, we would have had to write

	fun merge(nil, y) = y
	  | merge(x, nil) = x
	  | merge(x, y) =
		let val xh::xt = x
		    val yh::yt = y
		 in if xh < yh
		    then xh::merge(xt, y)
		    else xt::merge(x, yt)

which is somewhat longer and harder to follow.

As it turns out, Python has similar ways of decomposing data structures:

	(x, y) = foo


	def bar((x, y)):
		# etc.

and I have sometimes wished I could write

	z as (x, y) = foo


	def bar(z as (x, y)):
		# etc.

However, it's not real high on my list of priorities, and I suspect that
many Pythonists consider these usages to be a frill anyway.

More information about the Python-Dev mailing list