Trivial performance questions

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Oct 17 09:41:42 EDT 2003


"Brian Patterson" <bp at computastore.com> wrote in
news:bmopfb$sb5$1 at titan.btinternet.com: 

> I have noticed in the book of words that hasattr works by calling
> getattr and raising an exception if no such attribute exists.  If I
> need the value in any case, am I better off using getattr within a try
> statement myself, or is there some clever implementation enhancement
> which makes this a bad idea? 

If you were to inline the code, but you check the existence of an attribute 
in more than one place, then you would naturally extract the duplicated 
code out into a single function which you call from each location. The 
presence of 'hasattr' means the potentially duplicated code is already 
extracted into a support function, so you should use it *where appropriate* 
to make your code shorter & easier to read.
> 
> i.e. should I prefer:
>     if hasattr(self,"datum"):
>         datum=getattr("datum")
>     else:
>         datum=None
>         self.datum=None
> 
> over:
>     try:
>         datum=self.getattr("datum")
>     except:
>         self.datum=None
>         datum=None
> 
Probably you should prefer:

    datum = getattr(self, "datum", None)

although this doesn't have the side effect of setting self.datum if it was 
unset. Alternatively you could set self.datum every time with:

    self.datum = datum = getattr(self, "datum", None)

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list