[TIP] Interesting getattr pattern [was: Re: [issue5728] Support telling TestResult objects a test run has finished]

Raphael Marvie raphael.marvie at lifl.fr
Fri Apr 10 23:56:45 PDT 2009


Interesting pattern mentioned (Michael tell me if I am wrong):

 startTestRun = getattr(result, 'startTestRun', None)
 if startTestRun is not None:

My question is "what would be the increase in cost of doing an empty
call compared to the if?" such as:

 startTestRun = getattr(result, 'startTestRun', lambda: None)

If the lambda hurts you, one can define donothing() like:

 def donothing():

 startTestRun = getattr(result, 'startTestRun', donothing)


Michael Foord wrote:
> Robert Collins wrote:
>> As the bugtracker is down, and I'm not sure whether it will process mail
>> or have things lost when it comes back, I'm resending this to the list
>> to avoid any chance of lossage.
>> ---
>> I've written up a patch for this; it works with old result classes too.
>> Hopefully the bugtracker will attach it in reply to this mail; if not
>> I'll put in via the webui this evening.
>> -Rob
> I like your getattr pattern, nice and simple - and only single lookup 
> compared to using hasattr which I would probably have defaulted to.
> Michael

Raphael Marvie, PhD                http://www.lifl.fr/~marvie/
Maître de Conférences / Associate Professor  @  LIFL  --  USTL
Directeur du Master Informatique Professionnel spécialité IAGL
Head of Master's in Software Engineering     +33 3 20 33 59 51

More information about the testing-in-python mailing list