ctypes inheritance issue

Carl Banks pavlovevidence at gmail.com
Thu Feb 24 11:54:46 CET 2011

On Feb 23, 9:38 am, Steve <steve.f.thomp... at gmail.com> wrote:
> After looking at some metaclass examples it appears this information
> is readily available.  A metaclass gets a dictionary containing
> information about the parent class (or should, at least).

What examples did you look at?

> It seems
> like it must have this information in order to dynamically make
> decisions about how to create classes...  So, "bug" or not, shouldn't
> this just work?

No.  Information about parent class members is available if you dig
for it but it doesn't "just work".

A metaclass gets three pieces of information it uses when constructing
a class: the name of the class, a list of bases, and a dictionary
containing everything defined in the class's scope (and only the
class's scope, not the scope of any base classes).  Some, if not most,
metaclasses inspect and modify this dictionary before passing it to
the type constructor (type.__new__); inheritance hasn't even come into
play at that point.

A metaclass can look at the list of bases and try to extract
attributes from them, but that's not just working; that's digging.
(Needless to say, a lot of implementors don't go through the effort to

> Is there something that prevents it from being
> implemented?  Would this break something?

As I said, it's inherently a chicken-and-egg problem.  You have a
situation where you want to inherit the information needed to create a
class, but inheritance doesn't come into play until the class is

I guess you could elimiate the paradox by breaking down type
construction into steps (set up the inheritance relationships first,
then construct the type object, giving the metaclass time to get data
from the bases).

Some other language will have to try that, though.  Yes it would break
things.  Not a lot of things but there cases where you don't want to
inherit.  I use the following pattern fairly often:

class KeepTrackOfSubtypesMetaclass(type):

    subtypes = {}

    def __new__(metatype,name,bases,class_dct):
        key = class_dct.get('key')
        self = type.__new__(metatype,name,bases,class_dct)
        if key is not None:
            metatype.subtypes[key] = self
        return self

Any instance of this metaclass that defines key in its scope will be
added to the dict of subtypes.  But I don't want a derived class to
overwrite its parent's entry in the subtype dict--it should define its
own key.

Carl Banks

More information about the Python-list mailing list