简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM