basic generator question

Chris Angelico rosuav at gmail.com
Wed Feb 4 09:32:28 EST 2015


On Thu, Feb 5, 2015 at 12:23 AM, Neal Becker <ndbecker2 at gmail.com> wrote:
> Now I want gen to be a callable that repeats N times.  I'm thinking, this
> sounds perfect for yield
>
> class rpt:
>   def __init__ (self, value, rpt):
>     self.value = value; self.rpt = rpt
>   def __call__ (self):
>     for i in range (self.rpt):
>       yield self.value
>
> so I would do:
>
> my_rpt_obj = obj (rpt ('hello', 5))
>
> to repeat 'hello' 5 times (for example).
>
> But this doesn't work.  when obj calls self.gen(), that returns a generator, not
> the next value.
>
> How can I make this work?  I can't change the interface of the existing class
> obj, which expects a callable to get the next value.

So, if I understand you correctly, you want your rpt object to return
'hello' five times to five consecutive calls?

>>> a = rpt()
>>> a()
'hello'
>>> a()
'hello'
>>> a()
'hello'
>>> a()
'hello'
>>> a()
'hello'

You could do that with a generator by repeatedly calling next() on it,
or you could just keep track of the number of times you were called:

class rpt:
  def __init__ (self, value, rpt):
    self.value = value; self.rpt = rpt
  def __call__ (self):
    if self.rpt:
      self.rpt -= 1
      return self.value
   # ... otherwise?

Up to you to figure out what to do when self.rpt hits zero.

ChrisA



More information about the Python-list mailing list