3

I need to check if a certain variable is a generator object. How would I specify the literal generator type in place of the ??? below?

def go():
    for i in range(999):
    yield i
la = go()
print repr(type(la))

<type 'generator'>

assert type(la) == ???
user1552512
  • 869
  • 1
  • 9
  • 14
  • 2
    It's probably the wrong question to ask. Instead, you can check [if a variable is iterable](http://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-a-variable-is-iterable). – Lev Levitsky Aug 21 '12 at 19:51

3 Answers3

8

Use types.GeneratorType (from the types module). You should think, though, about why you're doing this. It's usually better to avoid explicit type-checking and just try iterating over the object and see if it works.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2
import types
assert isinstance(la, types.GeneratorType)
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

In general you wouldn't. You'd look for attributes with the names of __iter__ and next, both functions.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 2
    That would be signs of iterables and iterators correspondingly, not generators. Solutions by BrenBarn and F.J are more accurate. – WGH Sep 04 '13 at 19:31