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

Raphael Marvie raphael.marvie at lifl.fr
Sat Apr 11 02:00:16 PDT 2009


In fact my question was, would any one consider the proposal I made a
bad choice regarding performance. I am most often not limited by
performance issues. I just like to avoid tests when I can use some kind
of polymorphism, which I find cleaner to read. I'll remember the noop
name instead of donothing.

r.

Robert Collins wrote:
> On Sat, 2009-04-11 at 08:56 +0200, Raphael Marvie wrote:
>> Hi,
>>
>> Interesting pattern mentioned (Michael tell me if I am wrong):
>>
>>  startTestRun = getattr(result, 'startTestRun', None)
>>  if startTestRun is not None:
>>      startTestRun()
> 
> Thats the pattern in my patch, yes. As its only done twice a test run,
> in this case clarity really should win. So the performance aspect is
> entirely notional :). But in an inner loop it matters a great deal
> more :).
> 
>> 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)
>>  startTestRun()
>>
>> If the lambda hurts you, one can define donothing() like:
>>
>>  def donothing():
>>      pass
> 
> Either way you would be unconditionally constructing a callable
> regardless of whether the attribute lookup succeeds, and thus would be
> paying the cost of that. If you're in a loop where performance matters I
> would expect the way I wrote it to be the cheapest unless you factor out
> the lambda outside the loop (but keep it a local so you're not incurring
> another lookup). That said, encountering such a performance critical
> loop in a situation that wouldn't also call for a C extension is pretty
> rare IME.
> 
> 
> e.g.
> 
> noop = lambda: None
> for thing in things:
>     getattr(thing, 'method', noop)()
> 
> -Rob
> 

-- 
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