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

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


You can use GeneratorType from types:

>>> import types>>> types.GeneratorType<class 'generator'>>>> gen = (i for i in range(10))>>> isinstance(gen, types.GeneratorType)True


You mean generator functions ? use inspect.isgeneratorfunction.

EDIT :

if you want a generator object you can use inspect.isgenerator as pointed out by JAB in his comment.


I think it is important to make distinction between generator functions and generators (generator function's result):

>>> def generator_function():...     yield 1...     yield 2...>>> import inspect>>> inspect.isgeneratorfunction(generator_function)True

calling generator_function won't yield normal result, it even won't execute any code in the function itself, the result will be special object called generator:

>>> generator = generator_function()>>> generator<generator object generator_function at 0x10b3f2b90>

so it is not generator function, but generator:

>>> inspect.isgeneratorfunction(generator)False>>> import types>>> isinstance(generator, types.GeneratorType)True

and generator function is not generator:

>>> isinstance(generator_function, types.GeneratorType)False

just for a reference, actual call of function body will happen by consuming generator, e.g.:

>>> list(generator)[1, 2]

See also In python is there a way to check if a function is a "generator function" before calling it?