gahooa
gahooa

Reputation: 137252

Python: Identify the generator function that created a generator

Given a generator object, is it possible to identify the function used to create it?

def gen_func():
    yield

gen = gen_func()

// From `gen`, how do I get a reference to `gen_func` ?

I am implementing a decorator used to decorate a generator function with an additional attribute. I need to access that attribute later from the generator itself.

Upvotes: 2

Views: 232

Answers (1)

sah
sah

Reputation: 476

What you're literally asking for isn't possible in a clean way, both because generator objects don't have access to their generator function, and because new attributes can't be created on a generator.

But what you're trying to achieve probably is possible. Here's an example decorator that wraps the generator in an iterator object, and adds custom attributes to the iterator object:

def add_stuff(f):
    def replacement(*args, **kwargs):
        gen = f(*args, **kwargs)
        class FakeGenerator(object):
            def __iter__(self):
                return self
            def next(self):
                return gen.next()
        fakegen = FakeGenerator()
        fakegen.foo = "whatever"
        fakegen.generator_function = f
        return fakegen
    return replacement

@add_stuff
def gen_func():
    yield

gen = gen_func()
print gen
print gen.foo

Upvotes: 1

Related Questions