beginner, idiomatic python

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Aug 27 14:02:24 CEST 2007


bambam a écrit :
> Thank you, I have been through the tutorial several times, I guess
> I'm just not smart enough. Perhaps I have been led astray by what
> I read here?
> 
> My code started like this:
> 
> for i in range(self.parent.GetPageCount()):
> 
> I was asked:
> 
>> Does page count change? i.e. is it necessary to retrieve it in every loop
> 
> 
> Is self.parent.GetPageCount() 'retrieved every loop'?

If your question is 'is self.parent.GetPageCount()' called for each 
iteration of this loop, then the answer is obviously 'no', and it's 
quite easy to check it out:

Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> def test():
...     print "test called"
...     return range(5)
...
 >>> for x in test(): print x
...
test called
0
1
2
3
4
 >>>


Now if you need to use the result of self.parent.GetPageCount() more 
than once in the same function and this result is not likely to change 
during the function's execution, you're certainly better storing it in a 
local variable - but now that's such a CS101 thing that it's probably 
not even worth mentionning.

IOW, Zentrader's remark was at best misleading, at worst plain wrong...



More information about the Python-list mailing list