Advertisement
Guest User

iterable and stuff

a guest
Jul 10th, 2012
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. def the_gen():
  2.     i = 0
  3.     while True:
  4.         print "the_gen called", i
  5.         yield i
  6.         i += 1
  7.  
  8. def do(it):
  9.     n = 0
  10.     for i in it:
  11.         print "work on",i
  12.         n += 1
  13.         if n > 10:
  14.             break
  15.  
  16. def function(input):
  17.     """
  18.    Take an input that may be a iterable or not.
  19.    """
  20.  
  21.     iterable = None
  22.     if isinstance(input, basestring):
  23.         """ basestring is the only particular case as it is also an iterable"""
  24.         iterable = (input, )
  25.     else:
  26.         try:
  27.             iterable = (x for x in input)
  28.         except TypeError:
  29.             iterable = (input, )
  30.     if iterable is not None:
  31.         do(iterable)
  32.  
  33. gen = the_gen()
  34.  
  35. print "* generateur infini"        
  36. function(gen)
  37.  
  38. print "\n\n* string"
  39. function("bla bla bla")
  40.  
  41. print "\n\n* string split"
  42. function("bla bla bla".split())
  43.  
  44. print "\n\n* list comprehension (bad)"
  45. function([gen.next() for x in xrange(100)])
  46.  
  47. print "\n\n* generator (good)"
  48. function((gen.next() for x in xrange(100)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement