qrtt1
qrtt1

Reputation: 7957

How to get the type of an object in a python generator?

from types import GeneratorType
from typing import Iterable


def return_str_generator() -> Iterable[str]:
    yield "1"
    yield "2"
    yield "3"


def return_dict_generator() -> Iterable[dict]:
    yield dict(v=1)
    yield dict(v=2)
    yield dict(v=3)


if __name__ == '__main__':
    x = return_str_generator()
    y = return_dict_generator()

    print(x, isinstance(x, GeneratorType))
    print(y, isinstance(y, GeneratorType))



Is there any functions to check the type of an object inside a generator?

For example,

  1. get str type from return_str_generator
  2. get dict type from return_ dict_generator

Here is a work-around to fetch the type. Could anyone know something better than it?


def wrapper_generator(g):
    return_type = False
    for x in g:
        if not return_type:
            yield type(x)
            return_type = True
        yield x

if __name__ == '__main__':

    # my work around was trying to wrapper it
    for v in wrapper_generator(return_str_generator()):
        print(v)

Upvotes: 0

Views: 293

Answers (1)

trincot
trincot

Reputation: 349964

No, there is no such "look-ahead" to get the yielded data type. This is because:

  • A single iterator may produce different objects, each of a different type. Although this would not be good practice, it is quite possible.

  • An iterator may end before producing any values, i.e. it may be "empty".

  • Your solution, where you produce an extra (first) value, requires that any algorithm that uses it, is adapted accordingly. It is not a change that is "backwards compatible".

Upvotes: 2

Related Questions