Pushpak Dagade Pushpak Dagade - 1 year ago 146
Python Question

How to check if an object is a generator object in python?

In python, how do I check if an object is a generator object?

Trying this -

>>> type(myobject, generator)

gives the error -

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'generator' is not defined

(I know I can check if the object has a
method for it to be a generator, but I want some way using which I can determine the type of any object, not just generators.)

Answer Source

You can use GeneratorType from types:

>>> import types
>>> types.GeneratorType
<class 'generator'>
>>> gen = (i for i in range(10))
>>> isinstance(gen, types.GeneratorType)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download