Working w/ Yield

Gabriel Genellina gagsl-py at yahoo.com.ar
Thu Dec 14 18:13:52 EST 2006


At Wednesday 13/12/2006 08:35, Javier Subervi wrote:

>I'm trying to tweak a script I found here:
>
><http://zopelabs.com/cookbook/1118667115>http://zopelabs.com/cookbook/1118667115
>
>to get it to do what I want.

You didn't say what you want. But lately I've improved my mind 
reading skills, so I can tell you want to choose an element at random 
along a Zope hierarchy of objects.

>I'm no wizard at Python, much less newfangled tools like yield. I 
>understand that one cannot use "return" when working with yield, but 
>I don't understand how to achieve the same result. Here's my code:

Just don't use a generator then. If you want to choose one element at 
random, you will have to know how many of them are, and then choose 
one of the previously seen elements. Unless you have a huge amount of 
items, just collect them on a list.
You are interested only on "quotes", not Folder items, right? If 
they're the only thing contained in your Folders:

def CollectItems(folder, itemList):
   dirs = []
   objs = folder.objectValues()
   for obj in objs:
     if isdir(obj):
       dirs.append(obj)
     else:
       itemList.append(obj)
   for obj in dirs:
     CollectItems(obj, itemList)

def isdir(obj):
   return obj.meta_type == 'Folder'

def getRandomQuote(self):
   root = self.restrictedTraverse('/theSite/en-us/Books')
   quotes = []
   CollectItems(root, quotes)
   num = randrange(len(quotes))
   luckyWinner = quotes[num]
   path = luckyWinner.absolute_url()
   return path

Should work, untested...


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list