Hi, all!

I want to see metaclasses in cython. So I look into the code and I see
that classes are generated like this:

class Foo:
   xxx = 111

is transformed in something like:

Foo = Pyx_CreateClass('Foo', bases=(), attrs={})
# and then it does setattr()
Foo.xxx = 111

So nothing to do with metaclasses in Pyx_CreateClass() as attributes
are set after class is actually created ;(
Btw if class dict will be filled before class creation it's easy to
handle metaclass stuff in Pyx_CreateClass.
This this should be hard as PyDict_SetItem() and PyDict_GetItem()
should be used while class body creation

In python it works like this:

# based on Python/ceval.c:build_class()
def create_class(name, bases, attrs):
    if '__metaclass__' in attrs:
        metaclass = attrs.get('__metaclass__')
    elif len(bases) > 0:
        base = bases[0]
        if hasattr(base, '__class__'):
            metaclass = base.__class__
        else:
            metaclass = type(base)
    else '__metaclass__' in globals():
        metaclass = globals().get('__metaclass__')
    else:
        metaclass = type
    return metaclass(name, bases, attrs)

Another tricky way is to transform ClassDefNode, that has
__metaclass__ attribute into two classes:

class Foo(object):
   __metaclass__ = Bar
   xxx = 111

transform into:

Foo = create_class('Foo', (), {})
Foo.xxx = 111
Foo = create_class('Foo', (object,),  Foo.__dict__())

Second way is much easy to implement (I think) adding
MetaclassTransform into pipeline, but seems to be dirty hack.

I want to ask what is the best way to implement this?

vitja.
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to