generator testing and attrs

Tim Peters tim.one at comcast.net
Fri Oct 10 20:10:21 EDT 2003


[Mike]
> ...
> Ahh -- Looks like the original PEP (255) held the key:
>
> >>> hex(f.func_code.co_flags)
> '0x43'
> >>> hex(g.func_code.co_flags)
> '0x63'
> >>>

Of course that's not guaranteed to work forever.  Neither is the following,
but it's got a better chance at working longer:

def is_generator(f):
    from compiler.consts import CO_GENERATOR
    return f.func_code.co_flags & CO_GENERATOR != 0

Then, e.g.,

>>> def f():
...     pass
>>> is_generator(f)
False

>>> def g():
...     yield 1
>>> is_generator(g)
True






More information about the Python-list mailing list