![]() |
Mystery (to me) Function
I picked this function up on the net. It is described as an accumulator generator, but I cannot figure out what it can be used for. Any help?
:
def make_acc(start=0): |
I'm guessing it's meant for debugging, to see how many times a function is being called. The only thing, is there's no argument to handle the function as a parameter. Once I added that in, and a default for "inc", I could make a demonstration.
:
def make_acc(func, start=0): |
I understand how the accumulator function works, but how come the curr variable has to be a list? Why doesn't the following work?
:
def make_acc(start=0): |
Wow Sane, I think you hit the hammer on the nail!
I think the list here behaves like a static variable. |
Quote:
|
Quote:
To follow this up with an example: :
# Python's version of a static variable |
Quote:
Remember that "curr += inc" is equivalent to "curr = curr + inc", so it's an assignment. Because it's the first such assignment in the local scope, it's also a declaration. Thus, curr is first defined, and assigned the value "curr + inc". Unfortunately, because curr is defined before the assignment is evaluated, the curr in "curr + inc" refers to the variable you've just defined. Since you haven't assigned this curr a value yet, an error arises. This problem can be circumvented by an explicit declaration keyword; let's call it "var". Then, the code would look like: :
def make_acc(start=0)::
def make_acc(start=0): |
To which I add:
:
def make_acc(start=0):As to where you'd use an accumulator generator - you could use it with a language where functional programming is more pleasant than OO, and you want to store state for (eg) an accounting program - ie you need to store many totals. You could use an accumulator generator for each. Even with an OO program using one probably decreases the chances of bugs - "=" rather than "+=", for instance. You could probably also use it usefully for something domain-specific-ish in (eg) Ruby since you don't need brackets to call it. -T. *handwave* "These are not the droids you are looking for" *handwave* |
Aha! A rather elegant solution to the problem you have there, hydroxide.
|
Small bit of background that may help explain part of the comment: I originally posted that code on devshed as what I considered to be a prettier way of writing an acc gen (and by extension any stateful closure). I misread Dietrich's reply as where would _I_ use an acc gen (answer "Never") - sorry, D. Glad someone liked it :D.
Python is probably either getting an "outer" declaration or else the "global" declaration will look in successively outer scopes. Not sure if this will be 2.6 or 3.0 tho. Cheers, -T. |
| All times are GMT -5. The time now is 12:50 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC