Python Glossary Русский

all Python 3inspectfunction

inspect.isgenerator()

coroutines and generators

Checks that an object is a generator: the result of calling a function with yield, or a generator expression.

Syntax

inspect.isgenerator(object) -> bool

A generator is a special kind of iterator, not a synonym: iter([]), map() and range() give False. To ask 'can I call next() on it' use isinstance(x, collections.abc.Iterator). Checking for a generator matters when you rely on its own send() and throw() methods or on it being single-use: a second pass over an exhausted generator silently yields nothing.

Examples

import collections.abc, inspect
def gen():
    yield 1
g = gen()
print(inspect.isgenerator(g), inspect.isgenerator(x for x in []))  # → True True
print(inspect.isgenerator(iter([])), inspect.isgenerator(range(3)))  # → False False
print(isinstance(iter([]), collections.abc.Iterator))  # → True
print(list(g), list(g))  # → [1] []

See also

Open in the full glossarydocs.python.orgReport an inaccuracy