itertools candidate: warehouse()

Robert Brewer fumanchu at amor.org
Mon Oct 18 20:05:51 EDT 2004


Michael Hoffman wrote:
> Robert Brewer wrote:
> > 
> > What do you all think? I've been using a class-based 
> variant of this in
> > production code (business app) for six months now, and have found it
> > extremely helpful. I saw a pointer to itertools today and figured a
> > function-based version might be nice to include in that 
> module someday.
> 
> Could you give a real-world example of its use?

Sure. Here's a bit of presentation-layer logic from a webapp of mine.
The user checks a bunch of checkboxes on an HTML page to show which
staff members are working on a project on each day in the given range.
An example form:

Name    10/12 10/13 10/14 10/15 10/16
Bob      [ ]   [X]   [ ]   [X]   [ ]
Doug     [X]   [ ]   [X]   [X]   [ ]
Wendy    [ ]   [ ]   [ ]   [X]   [X]

In this case, there is already a set of persistent WorkDate objects;
when the user edits the form (even just one checkbox), you can:

a) destroy all the relevant previous WorkDate objects and make a new
set,
b) make horribly long control names using each object's ID (including
the blank ones!),
c) reuse the existing objects and rewrite the date and worker for each
one

Reuse is nice, but means you probably have to create new WorkDate
objects when you run out, and go through a formal destroy procedure if
you don't reuse them all. The warehouse function helps that out by
keeping track of the iteration (and on-the-fly object creation) for you:

parms = UI.requestParams
for worker in job.Worker():
    
    avail, rem = dejavu.warehouse(worker.dates(), WorkDate)
    
    for day in days:
        control_name = u'%s:%s' % (worker.ID, day.strftime('%m/%d/%Y'))
        if parms.has_key(control_name):
            # The appropriate checkbox was turned ON.
            # Reuse an existing WorkDate (or make a new one).
            wd = avail.next()
            wd.WorkerID = worker.ID
            wd.Date = day
            if not wd.sandbox:
                # The object is new. Make it persist in storage.
                UI.sandbox.memorize(wd)
    
    # Forget (destroy) any remaining workdate objects.
    for wd in rem:
        wd.forget()




Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list