[Tutor] functions and default argument
Alan Gauld
alan.gauld at btinternet.com
Sat Oct 22 02:32:27 CEST 2011
On 21/10/11 21:40, Albert-Jan Roskam wrote:
> Interesting thread and webpages. Insightful, but is this really used as
> a technique in daily practice?
Yes, one example is where you use it for a counter to
determine how often a function gets called:
def reserveScarceResource(p1,p2,count = [0]): : count is mutable
count[0] += 1
if count[0] > 100:
raise UsedTooManyException
# allocate resources
Its not really a hack, it's an implementation feature and it's
a fair impression of a closure in languages like Lisp, which makes it
useful for certain classes of problem.
It can also be useful in state machines where you want to carry
through a state value across transitions but don't need to retain
it after the state sequence completes.
You don't need it often but its nice to have when you do!
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list