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

ID : 20129

viewed : 40

Tags : pythongeneratorpython

Top 5 Answer for How to check if an object is a generator object in python?

vote vote

96

You can use GeneratorType from types:

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

80

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.

vote vote

76

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?

vote vote

66

The inspect.isgenerator function is fine if you want to check for pure generators (i.e. objects of class "generator"). However it will return False if you check, for example, a izip iterable. An alternative way for checking for a generalised generator is to use this function:

def isgenerator(iterable):     return hasattr(iterable,'__iter__') and not hasattr(iterable,'__len__') 
vote vote

58

You could use the Iterator or more specifically, the Generator from the typing module.

from typing import Generator, Iterator g = (i for i in range(1_000_000)) print(type(g)) print(isinstance(g, Generator)) print(isinstance(g, Iterator)) 

result:

<class 'generator'> True True 

Top 3 video Explaining How to check if an object is a generator object in python?

Related QUESTION?