Skip to content Skip to sidebar Skip to footer

In Python, Is There Any Way To Test A Generator Object To Find Out Which Generator Created It?

Given a generator object, is it possible to test whether it was created by a given generator? Perhaps better stated, is it possible to test what 'type' of generator we have? Since

Solution 1:

The name of the generating function (if any) is stored in the __name__ attribute as a string. If the string is all you needed, then you're done.

To get the actual function object, it's complicated. The generator itself does not hold any reference to the function object, and the logic operates using a reference to a code object.

function object (`gen1`) -----> <codeobject >
                                    ^
generator object (`g1`)  -----------╯

Armed with the generator function's original name, you could conceivably use getattr on the containing module to try and retrieve the originating function. This method is not necessarily reliable: there is an assumption here that the function object still exists and is still bound to that name. However, it's possible that the name has been deleted or rebound. In CPython, the function could also have been garbage collected already if the reference count decreased to 0.

Post a Comment for "In Python, Is There Any Way To Test A Generator Object To Find Out Which Generator Created It?"