unittest.TestCase, lambda and __getitem__

Steven Bethard steven.bethard at gmail.com
Mon Sep 13 22:39:10 CEST 2004

Alex Martelli <aleaxit <at> yahoo.com> writes:
> There is no indication on the PEP that Guido means to remove the ability
> to use a single line such as def name(): return 23.

Yeah, I noticed the if thing wasn't in the PEP, but it is in the Wiki at 
http://www.python.org/moin/Python3_2e0.  'Course the Wiki is really just 
things he's been quoted as saying -- presumably the PEP is thing that he's 
been quoted as saying and intends to pursue...

Regardless, I personally can't bring myself to write one-line defs.  ;)

> All in all I think changing lambdas into defs is a worthy endeavour and
> enhances your code.

Yeah, I actually did end up changing some of them.  For example, one of my 
testing methods now looks something like:

def getitem(obj, item):
	return obj[item]

self.assertRaises(IndexError, getitem, myobj, -10)
self.assertRaises(IndexError, getitem, myobj, 9)
self.assertRaises(IndexError, getitem, myobj2, -5)
self.assertRaises(IndexError, getitem, myobj2, 4)

It does make sense in situations like this when you're repeating the same kind 
of code a number of times, and because it's apparent from the code that 
getitem does in fact execute obj[item], I feel more comfortable with this than 
something like operator.getitem where I can't see what code is really executed.

> And if it should ever turn out in the future that
> you do need a line break after the : in "def name(): ...", it's a
> trivial and totally mechanical transformation...

Good point.

> > Hmm...  Well, if this is really the only option, I'll probably leave these
> > lambdas until I absolutely have to remove them...
> I've never seen a syntax proposed for an "anonymous def" that Guido
> would find in the least acceptable, if that's what you mean.

No, I wasn't actually expecting anonymous defs.  They've come up so many times 
without ever being accepted that I expect they won't ever make it into the 
language.  All-in-all, I don't really consider this a loss.  Really, 
assertRaises is the only time I've really wanted them, and only because 
testing code often has lots of special cases that don't necessarily generalize 



More information about the Python-list mailing list