[Python-Dev] metaclass insanity

Walter Dörwald walter@livinglogic.de
Wed, 06 Nov 2002 11:56:57 +0100

Guido van Rossum wrote:

>>Even better would to have "X.Y.__outerclass__ is X",
>>i.e. __outerclass__ as a (weak) reference to the class
>>in which X.Y was defined. What I came up with is this:
>>class nestedtype(type):
>>    def __new__(cls, name, bases, dict):
>>       dict["__outerclass__"] = None
>>       res = type.__new__(cls, name, bases, dict)
>>       for (key, value) in dict.items():
>>          if isinstance(value, type):
>>             value.__outerclass__ = res
>>       return res
>>    def __fullname__(cls):
>>       name = cls.__name__
>>       while 1:
>>          cls = cls.__outerclass__
>>          if cls is None:
>>             return name
>>          name = cls.__name__ + "." + name
>>    def __repr__(cls):
>>       return "<class %s/%s at 0x%x>" % \
>>          (cls.__module__, cls.__fullname__(), id(cls))
> I kind of like __fullname__ as a useful attribute (though I'd make it
> an attribute or property [== computed attribute] rather than a
> method).  But if setting the __name__ of an inner class to
> "Outer.Inner" doesn't break too much existing code, I'd prefer that --
> no new attributes needed.

I guess this shouldn't be a problem.

> I don't see any use for __outerclass__ *except* for computing the full
> name.  And there are better ways to do that if you have help from the
> parser.

Exactly, I only used __outerclass__, because I didn't have the help
of the parser and couldn't think of any other way to implement it.

What I wonder is how this will work with classes that are defined
outside but assigned inside an outer class, i.e.:

class NotInner:

class Outer:
    Inner = NotInner

Will this set NotInner.__name__ to "Outer.NotInner" or not?

    Walter Dörwald