Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify the literal generator type in Python?

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) == ???
like image 953
user1552512 Avatar asked Dec 21 '22 17:12

user1552512


2 Answers

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.

like image 71
BrenBarn Avatar answered Jan 13 '23 15:01

BrenBarn


import types
assert isinstance(la, types.GeneratorType)
like image 33
Andrew Clark Avatar answered Jan 13 '23 15:01

Andrew Clark