How to identify generator/iterator objects?

"Martin v. Löwis" martin at v.loewis.de
Wed Oct 25 17:34:50 EDT 2006


Kenneth McDonald schrieb:
> To do this, I need to determine (as fair as I can see), what are
> Is there a way to do this? Or perhaps another (better) way to achieve
> this flattening effect? itertools doesn't seem to have anything that
> will do it.

As others have pointed out, there is a proper test for generator
objects; you are apparently interested in finding out whether a
function will produce a generator when called.

To do that, use the following code

def is_generator_function(f):
  return (f.func_code.co_flags & 0x20) != 0

Here, 0x20 is the numeric value of CO_GENERATOR (also available
through compiler.consts.CO_GENERATOR).

Regards,
Martin



More information about the Python-list mailing list