In Python, is there a way to test the generator object to find out which generator created it?

Given the generator object, is it possible to check if it was created by this generator? Perhaps it’s better said, is it possible to verify that we have a β€œtype” of generator? Since generator objects are of type generator, testing with typeor isinstancewill not work.

Consider the code below:

>>> def gen1():
...     yield 1
... 
>>> def gen2():
...     yield 2
... 
>>> g1 = gen1()
>>> g2 = gen2()
>>> 
>>> def do_something(f):
...     # need to know if f is a gen1 generator or a gen2 generator here
...     # isinstance(f, gen1)  raises a TypeError since gen1 is not a type
...     # type(f) is gen1 returns false
...     print(f)
... 
>>> do_something(g1)
<generator object gen1 at 0x100dcb370>
>>> do_something(g2)
<generator object gen2 at 0x100dcb3c0>

Note that if I were to implement the generator using the iterator class instead, then it would work as typeand isinstancesince the generated objects would be of the type indicated by the iterator class:

>>> class gen():
...     def __next__(self):
...          return 1
... 
>>> f = gen()
>>> type(f) is gen
True
>>> isinstance(f, gen)
True

( , , , ) , yield?

+4
1

( ) __name__ . , .

, . , .

function object (`gen1`) -----> <code object >
                                    ^
generator object (`g1`)  -----------β•―

, getattr , . : , - . , . CPython , 0.

+6

Source: https://habr.com/ru/post/1531641/


All Articles