[Baypiggies] introspecting for generator vs non-generator function

Jean Brouwers mrjean1 at gmail.com
Sat Nov 15 23:11:28 CET 2008


Two more (less;-) esoteric bits:
- Function types have a 'func_code' attribute in Python 2.x.  That attribute
is called '__code__'  in Python 3.0.

- There are 'func_code' resp. '__code__' objects which do not have a
'co_flags' attribute, notably a 'getset_descriptor'.

Attached is an attempt to handle those.

HTH too,

/Jean Brouwers


On Sat, Nov 15, 2008 at 11:01 AM, Matt Good <matt at matt-good.net> wrote:

> On Nov 14, 2008, at 9:23 PM, wesley chun wrote:
>
>  On Fri, Nov 14, 2008 at 8:04 PM, Alex Martelli <aleaxit at gmail.com> wrote:
>>
>>> On Fri, Nov 14, 2008 at 7:44 PM, Matt Good <matt at matt-good.net> wrote:
>>>
>>>> There's a co_flags for that:
>>>> "The following flag bits are defined for co_flags: ... bit 0x20 is set
>>>> if
>>>> the function is a generator."
>>>>
>>>> So:
>>>> def is_generator(func):
>>>> return bool(func.func_code.co_flags & 0x20)
>>>>
>>>
>>> Yes it was -- I just approved it.  Thanks!  If there's one thing that
>>> makes me even happier than teaching, it's learning!-)
>>>
>>
>>
>> i have to agree with alex... that was a great find matt!  for those
>> interested in exploring further where he found it, it's in the 2.5.2
>> docs:
>>
>
> Thanks.  I'll admit that I didn't know that one off the top of my head, so
> I just did a quick dump of attributes that differed between the two:
>
> for k in dir(f.func_code):
>  if getattr(f.func_code, k, None) != getattr(g.func_code, k, None):
>    print k
>
> When I saw co_flags I remembered the bit about the generator flag from
> looking into the varargs flags not too long ago.
>
> HTH someone else digging into these esoteric bits of the language :)
>
> -- Matt
>
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20081115/2495c986/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: isgenerator.py
Type: text/x-python-script
Size: 2812 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20081115/2495c986/attachment.bin>


More information about the Baypiggies mailing list