[Tutor] using generators to mock raw_input for doctest

Kent Johnson kent37 at tds.net
Sun Aug 10 20:03:38 CEST 2008

On Sun, Aug 10, 2008 at 1:38 AM,  <broek at cc.umanitoba.ca> wrote:

> 2) Is there some better way to enable doctesting of code that uses
> raw_input? All I found when googling was the suggestion that in place of:
> def myfunc():
>   # code employing raw_input here
> one could write:
> def myfunc(input_meth=raw_input):
>   # code with raw_input calls replaced with input_meth calls
> but that seems like complicating my code for the non-doctest case.

It is not going to make your code more complicated - the client code
doesn't change at all and in myfunc you just change your use of
raw_input() to input_meth(). If you declare
  def myfunc(raw_input=raw_input):
you don't even have to change the body of myfunc.

> class myraw(object):
>    def __init__(self, values):
>        self.values = values
>        self.stream = self.mygen()
>    def mygen(self):
>        for i in self.values:
>            yield i
>    def readline(self):
>        return str(self.stream.next())

This is needlessly complex. The values argument must be iterable (or
the for loop would break) so you might as well use its iterator
instead of making your own:

class myraw(object):
  def __init__(self, values):
    self.stream = iter(values)
  def readline(self):
    return str(self.stream.next())


More information about the Tutor mailing list