473,799 Members | 3,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

itertools candidate: warehouse()

def warehouse(stock , factory=None):
"""warehouse(st ock, factory=None) -> iavailable, iremainder.

Iterate over stock, yielding each value. Once the 'stock' sequence
is
exhausted, the factory function (or any callable, such as a class)
is
called to produce a new valid object upon each subsequent call to
next().

If factory is None, the class of the first item in the sequence is
used
as a constructor. If the factory function is not a bound method, it
does
not receive any arguments, so if your class has mandatory arguments
to
__init__, wrap the class in a function which can supply those.

A common use for warehouse is to reuse a set of existing objects,
often
because object creation and/or destruction is expensive. The
warehouse
function returns the second iterable ('iremainder') to allow
consumers to
"clean up" any items from the initial sequence which did not get
re-used.

For example, given a homogeneous iterable named 'i':

available, remainder = warehouse(i)
for thing in some_other_sequ ence:
thing.use(avail able.next())
for item in remainder:
item.close()
"""

if not hasattr(stock, 'next'):
stock = iter(stock)

def pull():
"""An inner generator from itertools.wareh ouse()."""
for item in stock:
yield item

if factory is None:
try:
local_factory = item.__class__
except NameError:
raise ValueError("Emp ty sequence and no factory
supplied.")
else:
local_factory = factory

while True:
yield local_factory()

return pull(), stock
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.
Robert Brewer
MIS
Amor Ministries
fu******@amor.o rg
Jul 18 '05 #1
6 1741
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?
--
Michael Hoffman
Jul 18 '05 #2
On Tue, 19 Oct 2004 00:19:43 +0100, Michael Hoffman
<m.************ *************** ******@example. com> 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?


I think Robert is referring to a conversation where I took part
earlier today. My problem was to evaluate some alternatives for a
recursive generator. The problem with the recursive generator is that
one has to loop over the nested generators simply to yield back the
results to the original caller; for example, if you are at depth three
on the recursive generator, each yield in the inner generator will in
turn generate two more yields on as you go up the recursion stack,
before finally yielding the value to the original caller.

The warehouse may be useful in that situation; the solution is not
exactly the same, but it allows to express similar ideas and may be a
good alternative when designing generator-based code for complex
structures.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #3
Robert Brewer wrote:
def warehouse(stock , factory=None):
[snip documentation]
if not hasattr(stock, 'next'):
stock = iter(stock)
Note that unconditional use of iter() is usually harmless:
it = iter("abc")
it is iter(it) True
def pull():
"""An inner generator from itertools.wareh ouse()."""
for item in stock:
yield item

if factory is None:
try:
local_factory = item.__class__
except NameError:
raise ValueError("Emp ty sequence and no factory
supplied.")
else:
local_factory = factory

while True:
yield local_factory()

return pull(), stock
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.


Most of the building blocks for the warehouse() are already there, but you
didn't use them, oddly enough.
So here comes a variant written in terms of current (2.4) itertools:
from itertools import *
def peek(iterable): .... a, b = tee(iterable)
.... try:
.... return a, b.next()
.... except StopIteration:
.... raise ValueError("can not peek into an empty iterable")
.... iterable = iter("abc")
iterable, first = peek(iterable)
factory = first.__class__
data = range(10)
for a, b in izip(data, chain(iterable, starmap(factory , repeat(())))):

.... print a, repr(b)
....
0 'a'
1 'b'
2 'c'
3 ''
4 ''
5 ''
6 ''
7 ''
8 ''
9 ''

Ok, I see I'm suffering from a functional overdose :-)
I would have suggested chain(iterable, starmap(factory , repeat(()))) for
inclusion in the collection of recipes in the documentation, but upon
checking the development docs I see that Raymond Hettinger has already been
there, done that with the starmap() part.

So now you can do

chain(iterable, repeatfunc(fact ory))

after putting a copy of these recipes into your site-packages. Why aren't
they already there, btw?

The only extra your warehouse() has to offer is the (last) item's class as
the default factory for the padding items. I don't think that is needed
often enough to warrant the inclusion in the itertools.

Peter

Jul 18 '05 #4
Peter Otten <__*******@web. de> wrote:
...
iavailable = chain(stock, starmap(random. random, repeat(())))
... No, you cannot pass a callable to repeat() and have it called. In the above
line repeat(()) yields the same empty tuple ad infinitum. The trick is that
starmap() calls random.random() with that empty tuple as the argument list,


Stylistically, I prefer
iter(random.ran dom, None)
using the 2-args form of the built-in iter, to
itertools.starm ap(random.rando m, itertools.repea t(()))

However, itertools IS a speed demon...:

kallisti:~/cb alex$ python -m timeit -s 'import random, itertools as it'
\ > 'list(it.islice (iter(random.ra ndom, None), 666))'
1000 loops, best of 3: 884 usec per loop

kallisti:~/cb alex$ python -m timeit -s 'import random, itertools as it'
\ > 'list(it.islice (it.starmap(ran dom.random, it.repeat(())), 666))'
1000 loops, best of 3: 407 usec per loop
Alex
Jul 18 '05 #5
On Tue, Oct 19, 2004 at 09:30:31PM +0200, Alex Martelli wrote:
Peter Otten <__*******@web. de> wrote:
...
>iavailable = chain(stock, starmap(random. random, repeat(()))) ...
No, you cannot pass a callable to repeat() and have it called. In the above
line repeat(()) yields the same empty tuple ad infinitum. The trick is that
starmap() calls random.random() with that empty tuple as the argument list,
Stylistically, I prefer
iter(random.ran dom, None)
using the 2-args form of the built-in iter, to
itertools.starm ap(random.rando m, itertools.repea t(()))

kallisti:~/cb alex$ python -m timeit -s 'import random, itertools as it'

\ > 'list(it.islice (it.starmap(ran dom.random, it.repeat(())), 666))'

unrelated, I also often import itertools as 'it'. It bothers me because
I do it frequently (grep says 25 of 97 modules). Moving all of itertools into
builtins seems like overkill, but could we hang them off the 'iter' builtin?
Making the above:
kallisti:~/cb alex$ python -m timeit -s 'import random'

\ > 'list(iter.isli ce(iter.starmap (random.random, iter.repeat(()) ), 666))'

My life would definitely get easier, no more assuming 'it' is imported and
then adding the import when I find out differently.

A quick dir() of iter shows no conflicts.
dir(iter)

['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute __', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__' , '__repr__', '__self__', '__setattr__', '__str__']
-Jack

Jul 18 '05 #6
[Raymond Hettinger]
FWIW, I prefer loading the itertools recipes so I can write:

repeatfunc(rand om.random)

IMO, that is plainer than both the iter() and starmap() versions.

[Alex Martelli] I agree, but I cannot distribute Python code containing that, since the
itertools recipes aren't part of the stdlib.
Hogwash (see below).
--- in a separate note ---
[Robert Brewer] But in general, I don't write scripts for my own limited use;
I'm writing frameworks, which shouldn't depend upon little
recipes scattered hither and yon. :/


Double hogwash ;-)

Just paste the relevant recipe in your code and be done. No need for code
scattered hither and yon. Just apply a pre-made solution ready for re-use.

It is not a sin to write little helper functions to make the rest of your code
more readable. Recipes are perfect for this use because they have been tested
and refined for generic re-use.

Since when did a design pattern or code technique have to be in the standard
library to be useful?
Raymond
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3389
by: Jeremy Fincher | last post by:
Sometimes I find myself simply wanting the length of an iterator. For example, to collect some (somewhat useless ;)) statistics about a program of mine, I've got code like this: objs = gc.get_objects() classes = len() functions = len() modules = len() dicts = len() lists = len()
0
1577
by: expecthealth | last post by:
JOB DESCRIPTION Data Warehouse Architect (Permanent, Full-Time) ______________________________________________________________________ _________ Position Description: The Data Warehouse Architect is responsible for design, specifications, development, testing and deployment for Oracle data warehouse functionality, reports, extracts and interfaces. Leads
1
3793
by: Steven Bethard | last post by:
Is there a reason that itertools.islice doesn't support None arguments for start and step? This would be handy for use with slice objects: >>> r = range(20) >>> s1 = slice(2, 10, 2) >>> s2 = slice(2, 10) >>> s3 = slice(10) >>> list(itertools.islice(r, s1.start, s1.stop, s1.step)) >>> list(itertools.islice(r, s2.start, s2.stop, s2.step))
18
2639
by: Ville Vainio | last post by:
For quick-and-dirty stuff, it's often convenient to flatten a sequence (which perl does, surprise surprise, by default): ]]] -> One such implementation is at http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2302348
21
2188
by: Steven Bethard | last post by:
Jack Diederich wrote: > > itertools to iter transition, huh? I slipped that one in, I mentioned > it to Raymond at PyCon and he didn't flinch. It would be nice not to > have to sprinkle 'import itertools as it' in code. iter could also > become a type wrapper instead of a function, so an iter instance could > be a wrapper that figures out whether to call .next or __getitem__ > depending on it's argument. > for item in...
0
1471
by: DB2 DBA wanted | last post by:
Maines Paper & Food Service is a $2 billion/yr food distribution company with 9 distribution centers in the US. We are currently interviewing for the position detailed below. Relocation to Binghamton, NY will be necessary. If interested, please forward a resume to Bill.Kimler@maines.net ========================================================== Job Title: Database Architect
41
2683
by: rurpy | last post by:
The code below should be pretty self-explanatory. I want to read two files in parallel, so that I can print corresponding lines from each, side by side. itertools.izip() seems the obvious way to do this. izip() will stop interating when it reaches the end of the shortest file. I don't know how to tell which file was exhausted so I just try printing them both. The exhausted one will generate a
7
5578
by: Karol R | last post by:
Can anyone please explain me main differences between relational DB and warehouse (Point me to web site) ? Apart from theoretical differences I would like to know how Warehouse DB is updated ? If data needs to remain unchanged then what is happening for instance if in source relational DB address for a customer will change and record gets the update. How this is loaded to DB ?
2
1354
by: cjshea | last post by:
I am running DB2 UDB Workgroups V8.2 on Linux. I don't believe I installed the Data Warehouing capability when I installed. Is it difficult to enable that capability post installation?, and a second question is "Are the data warehousing capabilities available with my install limited, or are they full blown capabilities?, or is full Data Warehousing a separate product and install?, with a separate purchase price? If so I will proceed to...
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10251
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10225
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7564
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.