Python Glossary Русский

all Python 3typesterm

types.GeneratorType

generators and coroutines

The type of a generator object — what calling a function with yield or a generator expression returns. It does not describe the yield function itself.

Syntax

isinstance(obj, types.GeneratorType)

The main confusion is between a generator function and a generator: isinstance(gen_func, GeneratorType) is False, while isinstance(gen_func(), GeneratorType) is True. Second: range, map and zip are lazy iterators too, but not generators, so a GeneratorType check rejects them. If your code needs "something iterable", check collections.abc.Iterator or Iterable — that is broader and more honest.

Examples

import types
def count():
    yield 1
print(isinstance(count, types.GeneratorType))  # → False
print(isinstance(count(), types.GeneratorType))  # → True
print(isinstance((x for x in 'ab'), types.GeneratorType))  # → True
print(isinstance(map(str, [1]), types.GeneratorType))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy